idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
36,300
def sourcekey ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) self . _replace_none ( kwargs_copy ) try : return NameFactory . sourcekey_format . format ( ** kwargs_copy ) except KeyError : return None
Return a key that specifies the name and version of a source or component
36,301
def galprop_gasmap ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) self . _replace_none ( kwargs_copy ) localpath = NameFactory . galprop_gasmap_format . format ( ** kwargs_copy ) if kwargs . get ( 'fullpath' , False ) : return self . fullpath ( localpath = localpath ...
return the file name for Galprop input gasmaps
36,302
def merged_gasmap ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) self . _replace_none ( kwargs_copy ) localpath = NameFactory . merged_gasmap_format . format ( ** kwargs_copy ) if kwargs . get ( 'fullpath' , False ) : return self . fullpath ( localpath = localpath ) ...
return the file name for Galprop merged gasmaps
36,303
def diffuse_template ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) self . _replace_none ( kwargs_copy ) localpath = NameFactory . diffuse_template_format . format ( ** kwargs_copy ) if kwargs . get ( 'fullpath' , False ) : return self . fullpath ( localpath = localp...
return the file name for other diffuse map templates
36,304
def spectral_template ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) localpath = NameFactory . spectral_template_format . format ( ** kwargs_copy ) if kwargs . get ( 'fullpath' , False ) : return self . fullpath ( localpath = localpath ) return localpath
return the file name for spectral templates
36,305
def srcmdl_xml ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) localpath = NameFactory . srcmdl_xml_format . format ( ** kwargs_copy ) if kwargs . get ( 'fullpath' , False ) : return self . fullpath ( localpath = localpath ) return localpath
return the file name for source model xml files
36,306
def nested_srcmdl_xml ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) self . _replace_none ( kwargs_copy ) localpath = NameFactory . nested_srcmdl_xml_format . format ( ** kwargs_copy ) if kwargs . get ( 'fullpath' , False ) : return self . fullpath ( localpath = loca...
return the file name for source model xml files of nested sources
36,307
def ft1file ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) kwargs_copy [ 'dataset' ] = kwargs . get ( 'dataset' , self . dataset ( ** kwargs ) ) self . _replace_none ( kwargs_copy ) localpath = NameFactory . ft1file_format . format ( ** kwargs_copy ) if kwargs . get ...
return the name of the input ft1 file list
36,308
def ft2file ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) kwargs_copy [ 'data_time' ] = kwargs . get ( 'data_time' , self . dataset ( ** kwargs ) ) self . _replace_none ( kwargs_copy ) localpath = NameFactory . ft2file_format . format ( ** kwargs_copy ) if kwargs . ...
return the name of the input ft2 file list
36,309
def ccube ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) kwargs_copy [ 'dataset' ] = kwargs . get ( 'dataset' , self . dataset ( ** kwargs ) ) kwargs_copy [ 'component' ] = kwargs . get ( 'component' , self . component ( ** kwargs ) ) localpath = NameFactory . ccube_...
return the name of a counts cube file
36,310
def mcube ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) kwargs_copy [ 'dataset' ] = kwargs . get ( 'dataset' , self . dataset ( ** kwargs ) ) kwargs_copy [ 'component' ] = kwargs . get ( 'component' , self . component ( ** kwargs ) ) self . _replace_none ( kwargs_co...
return the name of a model cube file
36,311
def angprofile ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) self . _replace_none ( kwargs_copy ) localpath = NameFactory . angprofile_format . format ( ** kwargs_copy ) if kwargs . get ( 'fullpath' , False ) : return self . fullpath ( localpath = localpath ) return...
return the file name for sun or moon angular profiles
36,312
def template_sunmoon ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) kwargs_copy [ 'dataset' ] = kwargs . get ( 'dataset' , self . dataset ( ** kwargs ) ) kwargs_copy [ 'component' ] = kwargs . get ( 'component' , self . component ( ** kwargs ) ) self . _replace_none ...
return the file name for sun or moon template files
36,313
def residual_cr ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) kwargs_copy [ 'dataset' ] = kwargs . get ( 'dataset' , self . dataset ( ** kwargs ) ) kwargs_copy [ 'component' ] = kwargs . get ( 'component' , self . component ( ** kwargs ) ) localpath = NameFactory . ...
Return the name of the residual CR analysis output files
36,314
def galprop_rings_yaml ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) self . _replace_none ( kwargs_copy ) localpath = NameFactory . galprop_rings_yaml_format . format ( ** kwargs_copy ) if kwargs . get ( 'fullpath' , False ) : return self . fullpath ( localpath = lo...
return the name of a galprop rings merging yaml file
36,315
def catalog_split_yaml ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) self . _replace_none ( kwargs_copy ) localpath = NameFactory . catalog_split_yaml_format . format ( ** kwargs_copy ) if kwargs . get ( 'fullpath' , False ) : return self . fullpath ( localpath = lo...
return the name of a catalog split yaml file
36,316
def model_yaml ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) self . _replace_none ( kwargs_copy ) localpath = NameFactory . model_yaml_format . format ( ** kwargs_copy ) if kwargs . get ( 'fullpath' , False ) : return self . fullpath ( localpath = localpath ) return...
return the name of a model yaml file
36,317
def fullpath ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) self . _replace_none ( kwargs_copy ) return NameFactory . fullpath_format . format ( ** kwargs_copy )
Return a full path name for a given file
36,318
def generic ( self , input_string , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) kwargs_copy [ 'dataset' ] = kwargs . get ( 'dataset' , self . dataset ( ** kwargs ) ) kwargs_copy [ 'component' ] = kwargs . get ( 'component' , self . component ( ** kwargs ) ) self . _replace...
return a generic filename for a given dataset and component
36,319
def make_filenames ( self , ** kwargs ) : out_dict = dict ( ft1file = self . ft1file ( ** kwargs ) , ltcube = self . ltcube ( ** kwargs ) , ccube = self . ccube ( ** kwargs ) , bexpcube = self . bexpcube ( ** kwargs ) , srcmaps = self . srcmaps ( ** kwargs ) , mcube = self . mcube ( ** kwargs ) ) return out_dict
Make a dictionary of filenames for various types
36,320
def create_spectrum_from_dict ( spectrum_type , spectral_pars , fn = None ) : if fn is None : fn = pyLike . SourceFactory_funcFactory ( ) . create ( str ( spectrum_type ) ) if spectrum_type == 'PiecewisePowerLaw' : build_piecewise_powerlaw ( fn , spectral_pars ) for k , v in spectral_pars . items ( ) : v . setdefault (...
Create a Function object from a parameter dictionary .
36,321
def get_priors ( like ) : npar = len ( like . params ( ) ) vals = np . ones ( npar ) errs = np . ones ( npar ) has_prior = np . array ( [ False ] * npar ) for i , p in enumerate ( like . params ( ) ) : prior = like [ i ] . log_prior ( ) if prior is None : continue par_names = pyLike . StringVector ( ) prior . getParamN...
Extract priors from a likelihood object .
36,322
def get_source_pars ( src ) : fnmap = src . getSrcFuncs ( ) keys = fnmap . keys ( ) if 'Position' in keys : ppars = get_function_pars ( src . getSrcFuncs ( ) [ str ( 'Position' ) ] ) elif 'SpatialDist' in keys : ppars = get_function_pars ( src . getSrcFuncs ( ) [ str ( 'SpatialDist' ) ] ) else : raise Exception ( 'Fail...
Extract the parameters associated with a pyLikelihood Source object .
36,323
def nFreeParams ( self ) : nF = 0 pars = self . params ( ) for par in pars : if par . isFree ( ) : nF += 1 return nF
Count the number of free parameters in the active model .
36,324
def Ts2 ( self , srcName , reoptimize = False , approx = True , tol = None , MaxIterations = 10 , verbosity = 0 ) : saved_state = LikelihoodState ( self ) if verbosity > 0 : print ( "*** Start Ts_dl ***" ) source_attributes = self . getExtraSourceAttributes ( ) self . logLike . syncParams ( ) src = self . logLike . get...
Computes the TS value for a source indicated by srcName .
36,325
def _make_scatter_logfile_name ( cls , key , linkname , job_config ) : logfile = job_config . get ( 'logfile' , "%s_%s_%s.log" % ( cls . default_prefix_logfile , linkname , key ) ) job_config [ 'logfile' ] = logfile
Hook to inster the name of a logfile into the input config
36,326
def create ( cls , ** kwargs ) : linkname = kwargs . setdefault ( 'linkname' , cls . clientclass . linkname_default ) job_archive = kwargs . get ( 'job_archive' , None ) if job_archive is None : job_archive = JobArchive . build_temp_job_archive ( ) kwargs . setdefault ( 'job_archive' , job_archive ) kwargs_client = dic...
Build and return a ScatterGather object
36,327
def _check_link_completion ( self , link , fail_pending = False , fail_running = False ) : status_vect = JobStatusVector ( ) for job_key , job_details in link . jobs . items ( ) : if job_key . find ( JobDetails . topkey ) >= 0 : continue job_details . status = self . _interface . check_job ( job_details ) if job_detail...
Internal function to check the completion of all the dispatched jobs
36,328
def _build_job_dict ( self ) : if self . args [ 'dry_run' ] : status = JobStatus . unknown else : status = JobStatus . not_ready base_config = self . scatter_link . args for jobkey , job_config in sorted ( self . _job_configs . items ( ) ) : full_job_config = base_config . copy ( ) full_job_config . update ( job_config...
Build a dictionary of JobDetails objects for the internal Link
36,329
def _invoke ( self , argv , stream = sys . stdout , resubmit_failed = False ) : args = self . _run_argparser ( argv ) if args . action not in ACTIONS : sys . stderr . write ( "Unrecognized action %s, options are %s\n" % ( args . action , ACTIONS ) ) if args . action == 'skip' : return JobStatus . no_job elif args . act...
Invoke this object to preform a particular action
36,330
def update_args ( self , override_args ) : self . args = extract_arguments ( override_args , self . args ) self . _job_configs = self . build_job_configs ( self . args ) if not self . _scatter_link . jobs : self . _build_job_dict ( ) self . _latch_file_info ( )
Update the arguments used to invoke the application
36,331
def clear_jobs ( self , recursive = True ) : if recursive : self . _scatter_link . clear_jobs ( recursive ) self . jobs . clear ( )
Clear the self . jobs dictionary that contains information about jobs associated with this ScatterGather
36,332
def check_status ( self , stream = sys . stdout , check_once = False , fail_pending = False , fail_running = False , no_wait = False , do_print = True , write_status = False ) : running = True first = True if not check_once : if stream != sys . stdout : sys . stdout . write ( 'Checking status (%is): ' % self . args [ '...
Loop to check on the status of all the jobs in job dict .
36,333
def run_jobs ( self , stream = sys . stdout , resubmit_failed = False ) : self . _build_job_dict ( ) self . _interface . _dry_run = self . args [ 'dry_run' ] scatter_status = self . _interface . submit_jobs ( self . scatter_link , job_archive = self . _job_archive , stream = stream ) if scatter_status == JobStatus . fa...
Function to dipatch jobs and collect results
36,334
def resubmit ( self , stream = sys . stdout , fail_running = False , resubmit_failed = False ) : self . _build_job_dict ( ) status_vect = self . check_status ( stream , check_once = True , fail_pending = True , fail_running = fail_running ) status = status_vect . get_status ( ) if status == JobStatus . done : return st...
Function to resubmit failed jobs and collect results
36,335
def clean_jobs ( self , recursive = False ) : self . _interface . clean_jobs ( self . scatter_link , clean_all = recursive )
Clean up all the jobs associated with this object .
36,336
def print_update ( self , stream = sys . stdout , job_stats = None ) : if job_stats is None : job_stats = JobStatusVector ( ) job_det_list = [ ] job_det_list += self . _scatter_link . jobs . values ( ) for job_dets in job_det_list : if job_dets . status == JobStatus . no_job : continue job_stats [ job_dets . status ] +...
Print an update about the current number of jobs running
36,337
def print_failed ( self , stream = sys . stderr ) : for job_key , job_details in sorted ( self . scatter_link . jobs . items ( ) ) : if job_details . status == JobStatus . failed : stream . write ( "Failed job %s\n log = %s\n" % ( job_key , job_details . logfile ) )
Print list of the failed jobs
36,338
def read_sources_from_numpy_file ( npfile ) : srcs = np . load ( npfile ) . flat [ 0 ] [ 'sources' ] roi = ROIModel ( ) roi . load_sources ( srcs . values ( ) ) return roi . create_table ( )
Open a numpy pickle file and read all the new sources into a dictionary
36,339
def read_sources_from_yaml_file ( yamlfile ) : f = open ( yamlfile ) dd = yaml . load ( f ) srcs = dd [ 'sources' ] f . close ( ) roi = ROIModel ( ) roi . load_sources ( srcs . values ( ) ) return roi . create_table ( )
Open a yaml file and read all the new sources into a dictionary
36,340
def merge_source_tables ( src_tab , tab , all_sources = False , prefix = "" , suffix = "" , roi_idx = None ) : if roi_idx is not None and 'roi' not in tab . columns : tab . add_column ( Column ( name = 'roi' , data = len ( tab ) * [ roi_idx ] ) ) remove_rows = [ ] for i , row in enumerate ( tab ) : if not all_sources a...
Append the sources in a table into another table .
36,341
def fill_livetime_hist ( skydir , tab_sc , tab_gti , zmax , costh_edges ) : if len ( tab_gti ) == 0 : shape = ( len ( costh_edges ) - 1 , len ( skydir ) ) return ( np . zeros ( shape ) , np . zeros ( shape ) ) m = ( tab_sc [ 'START' ] < tab_gti [ 'STOP' ] [ - 1 ] ) m &= ( tab_sc [ 'STOP' ] > tab_gti [ 'START' ] [ 0 ] )...
Generate a sequence of livetime distributions at the sky positions given by skydir . The output of the method are two NxM arrays containing a sequence of histograms for N sky positions and M incidence angle bins where the bin edges are defined by costh_edges . This method uses the same algorithm as gtltcube with the ex...
36,342
def create ( cls , ltfile ) : if not re . search ( '\.txt?' , ltfile ) is None : files = np . loadtxt ( ltfile , unpack = True , dtype = 'str' ) elif not isinstance ( ltfile , list ) : files = glob . glob ( ltfile ) ltc = cls . create_from_fits ( files [ 0 ] ) for f in files [ 1 : ] : ltc . load_ltfile ( f ) return ltc
Create a livetime cube from a single file or list of files .
36,343
def create_empty ( cls , tstart , tstop , fill = 0.0 , nside = 64 ) : cth_edges = np . linspace ( 0 , 1.0 , 41 ) domega = utils . edge_to_width ( cth_edges ) * 2.0 * np . pi hpx = HPX ( nside , True , 'CEL' , ebins = cth_edges ) data = np . ones ( ( len ( cth_edges ) - 1 , hpx . npix ) ) * fill return cls ( data , hpx ...
Create an empty livetime cube .
36,344
def create_skydir_ltcube ( self , skydir , tab_sc , tab_gti , zmax ) : skydir = SkyCoord ( np . array ( [ skydir . ra . deg ] ) , np . array ( [ skydir . dec . deg ] ) , unit = 'deg' ) lt , lt_wt = fill_livetime_hist ( skydir , tab_sc , tab_gti , zmax , self . costh_edges ) ipix = self . hpx . skydir_to_pixel ( skydir ...
Create a new livetime cube by scaling this one by the observing profile ratio in the direction skydir . This method can be used to generate an approximate livetime cube that is accurate in the vicinity of skydir .
36,345
def write ( self , outfile ) : hdu_pri = fits . PrimaryHDU ( ) hdu_exp = self . _create_exp_hdu ( self . data ) hdu_exp . name = 'EXPOSURE' hdu_exp_wt = self . _create_exp_hdu ( self . _data_wt ) hdu_exp_wt . name = 'WEIGHTED_EXPOSURE' cols = [ Column ( name = 'CTHETA_MIN' , dtype = 'f4' , data = self . costh_edges [ :...
Write the livetime cube to a FITS file .
36,346
def make_cube_slice ( map_in , loge_bounds ) : axis = map_in . geom . axes [ 0 ] i0 = utils . val_to_edge ( axis . edges , 10 ** loge_bounds [ 0 ] ) [ 0 ] i1 = utils . val_to_edge ( axis . edges , 10 ** loge_bounds [ 1 ] ) [ 0 ] new_axis = map_in . geom . axes [ 0 ] . slice ( slice ( i0 , i1 ) ) geom = map_in . geom . ...
Extract a slice from a map cube object .
36,347
def plot_sed ( sed , showlnl = False , ** kwargs ) : ax = kwargs . pop ( 'ax' , plt . gca ( ) ) cmap = kwargs . get ( 'cmap' , 'BuGn' ) annotate_name ( sed , ax = ax ) SEDPlotter . plot_flux_points ( sed , ** kwargs ) if np . any ( sed [ 'ts' ] > 9. ) : if 'model_flux' in sed : SEDPlotter . plot_model ( sed [ 'model_fl...
Render a plot of a spectral energy distribution .
36,348
def run ( self , gta , mcube_map , ** kwargs ) : prefix = kwargs . get ( 'prefix' , 'test' ) format = kwargs . get ( 'format' , self . config [ 'format' ] ) loge_bounds = [ None ] + self . config [ 'loge_bounds' ] for x in loge_bounds : self . make_roi_plots ( gta , mcube_map , loge_bounds = x , ** kwargs ) imfile = ut...
Make all plots .
36,349
def _plot_extension ( self , gta , prefix , src , loge_bounds = None , ** kwargs ) : if loge_bounds is None : loge_bounds = ( self . energies [ 0 ] , self . energies [ - 1 ] ) name = src [ 'name' ] . lower ( ) . replace ( ' ' , '_' ) esuffix = '_%.3f_%.3f' % ( loge_bounds [ 0 ] , loge_bounds [ 1 ] ) p = ExtensionPlotte...
Utility function for generating diagnostic plots for the extension analysis .
36,350
def extract_parameters ( pil , keys = None ) : out_dict = { } if keys is None : keys = pil . keys ( ) for key in keys : try : out_dict [ key ] = pil [ key ] except ValueError : out_dict [ key ] = None return out_dict
Extract and return parameter names and values from a pil object
36,351
def update_gtapp ( gtapp , ** kwargs ) : for key , val in kwargs . items ( ) : if key in [ 'pfiles' , 'scratch' ] : continue if val is None : continue try : gtapp [ key ] = val except ValueError : raise ValueError ( "gtapp failed to set parameter %s %s" % ( key , val ) ) except KeyError : raise KeyError ( "gtapp failed...
Update the parameters of the object that can run ScienceTools applications
36,352
def build_gtapp ( appname , dry_run , ** kwargs ) : pfiles_orig = _set_pfiles ( dry_run , ** kwargs ) gtapp = GtApp . GtApp ( appname ) update_gtapp ( gtapp , ** kwargs ) _reset_pfiles ( pfiles_orig ) return gtapp
Build an object that can run ScienceTools application
36,353
def run_gtapp ( gtapp , stream , dry_run , ** kwargs ) : if stream is None : stream = sys . stdout pfiles_orig = _set_pfiles ( dry_run , ** kwargs ) update_gtapp ( gtapp , ** kwargs ) stream . write ( "%s\n" % gtapp . command ( ) ) stream . flush ( ) if dry_run : _reset_pfiles ( pfiles_orig ) return 0 try : stdin , std...
Runs one on the ScienceTools apps
36,354
def run_analysis ( self , argv ) : args = self . _parser . parse_args ( argv ) components = Component . build_from_yamlfile ( args . comp ) NAME_FACTORY . update_base_dict ( args . data ) model_dict = make_library ( ** args . __dict__ ) model_manager = model_dict [ 'ModelManager' ] models = load_yaml ( args . models ) ...
Build the manifest for all the models
36,355
def copy_ccube ( ccube , outsrcmap , hpx_order ) : sys . stdout . write ( " Copying counts cube from %s to %s\n" % ( ccube , outsrcmap ) ) try : hdulist_in = fits . open ( ccube ) except IOError : hdulist_in = fits . open ( "%s.gz" % ccube ) hpx_order_in = hdulist_in [ 1 ] . header [ 'ORDER' ] if hpx_order_in > hpx_or...
Copy a counts cube into outsrcmap file reducing the HEALPix order to hpx_order if needed .
36,356
def append_hdus ( hdulist , srcmap_file , source_names , hpx_order ) : sys . stdout . write ( " Extracting %i sources from %s" % ( len ( source_names ) , srcmap_file ) ) try : hdulist_in = fits . open ( srcmap_file ) except IOError : try : hdulist_in = fits . open ( '%s.gz' % srcmap_file ) except IOError : sys . stdou...
Append HEALPix maps to a list
36,357
def assemble_component ( compname , compinfo , hpx_order ) : sys . stdout . write ( "Working on component %s\n" % compname ) ccube = compinfo [ 'ccube' ] outsrcmap = compinfo [ 'outsrcmap' ] source_dict = compinfo [ 'source_dict' ] hpx_order = AssembleModel . copy_ccube ( ccube , outsrcmap , hpx_order ) hdulist = Assem...
Assemble the source map file for one binning component
36,358
def run_analysis ( self , argv ) : args = self . _parser . parse_args ( argv ) manifest = yaml . safe_load ( open ( args . input ) ) compname = args . compname value = manifest [ compname ] self . assemble_component ( compname , value , args . hpx_order )
Assemble the source map file for one binning component FIXME
36,359
def read_block ( self , address ) : buf = [ self . ReadCommand , address // 256 , address % 256 , self . EndMark , self . ReadCommand , address // 256 , address % 256 , self . EndMark , ] if not self . dev . write_data ( buf ) : return None return self . dev . read_data ( 32 )
Read 32 bytes from the weather station .
36,360
def write_byte ( self , address , data ) : buf = [ self . WriteCommandWord , address // 256 , address % 256 , self . EndMark , self . WriteCommandWord , data , 0 , self . EndMark , ] if not self . dev . write_data ( buf ) : return False buf = self . dev . read_data ( 8 ) if buf is None : return False for byte in buf : ...
Write a single byte to the weather station .
36,361
def inc_ptr ( self , ptr ) : result = ptr + self . reading_len [ self . ws_type ] if result >= 0x10000 : result = self . data_start return result
Get next circular buffer data pointer .
36,362
def dec_ptr ( self , ptr ) : result = ptr - self . reading_len [ self . ws_type ] if result < self . data_start : result = 0x10000 - self . reading_len [ self . ws_type ] return result
Get previous circular buffer data pointer .
36,363
def get_raw_data ( self , ptr , unbuffered = False ) : if unbuffered : self . _data_pos = None idx = ptr - ( ptr % 0x20 ) ptr -= idx count = self . reading_len [ self . ws_type ] if self . _data_pos == idx : result = self . _data_block [ ptr : ptr + count ] if len ( result ) >= count : return result else : result = lis...
Get raw data from circular buffer .
36,364
def get_data ( self , ptr , unbuffered = False ) : result = _decode ( self . get_raw_data ( ptr , unbuffered ) , self . _reading_format [ self . ws_type ] ) return result
Get decoded data from circular buffer .
36,365
def current_pos ( self ) : new_ptr = _decode ( self . _read_fixed_block ( 0x0020 ) , self . lo_fix_format [ 'current_pos' ] ) if new_ptr == self . _current_ptr : return self . _current_ptr if self . _current_ptr and new_ptr != self . inc_ptr ( self . _current_ptr ) : logger . error ( 'unexpected ptr change %06x -> %06x...
Get circular buffer location where current data is being written .
36,366
def _find_device ( self , idVendor , idProduct ) : for bus in usb . busses ( ) : for device in bus . devices : if ( device . idVendor == idVendor and device . idProduct == idProduct ) : return device return None
Find a USB device by product and vendor id .
36,367
def _adapt_WSDateTime ( dt ) : try : ts = int ( ( dt . replace ( tzinfo = pytz . utc ) - datetime ( 1970 , 1 , 1 , tzinfo = pytz . utc ) ) . total_seconds ( ) ) except ( OverflowError , OSError ) : if dt < datetime . now ( ) : ts = 0 else : ts = 2 ** 63 - 1 return ts
Return unix timestamp of the datetime like input . If conversion overflows high return sint64_max if underflows return 0
36,368
def _predicate ( self , i ) : if isinstance ( i , slice ) : if i . step is not None : raise TypeError ( "Slice step not permitted" ) if ( ( i . start is not None and not isinstance ( i . start , datetime ) ) or ( i . stop is not None and not isinstance ( i . stop , datetime ) ) ) : raise TypeError ( "Slice indices must...
Given a valid datetime or slace return the predicate portion of the SQL query a boolean indicating whether multiple items are expected from the result and a dictionary of parameters for the query
36,369
def set_locale ( lang ) : lc , encoding = locale . getdefaultlocale ( ) try : if '.' in lang : locale . setlocale ( locale . LC_ALL , lang ) else : locale . setlocale ( locale . LC_ALL , ( lang , encoding ) ) except locale . Error : return False return True
Set the locale used by a program .
36,370
def set_application_language ( params ) : lang = params . get ( 'config' , 'language' , None ) if lang : set_locale ( lang ) set_translation ( lang )
Set the locale and translation for a pywws program .
36,371
def get ( self , section , option , default = None ) : with self . _lock : if not self . _config . has_option ( section , option ) : if default is not None : self . _set ( section , option , default ) return default return self . _config . get ( section , option )
Get a parameter value and return a string .
36,372
def set ( self , section , option , value ) : with self . _lock : self . _set ( section , option , value )
Set option in section to string value .
36,373
def unset ( self , section , option ) : with self . _lock : if not self . _config . has_section ( section ) : return if self . _config . has_option ( section , option ) : self . _config . remove_option ( section , option ) self . _dirty = True if not self . _config . options ( section ) : self . _config . remove_sectio...
Remove option from section .
36,374
def check_params ( self , * keys ) : for key in keys : if not self . params [ key ] : raise RuntimeError ( '"{}" not set in weather.ini' . format ( key ) )
Ensure user has set required values in weather . ini .
36,375
def monitor ( i ) : count = 0 for x in i : count += 1 if count % 10000 == 0 : logger . info ( "%d records so far, current record is %s" , count , x [ "idx" ] ) yield x
Given an iterator yields data from it but prints progress every 10 000 records
36,376
def calibrate_data ( params , raw_data , calib_data ) : start = calib_data . before ( datetime . max ) if start is None : start = datetime . min start = raw_data . after ( start + SECOND ) if start is None : return start del calib_data [ start : ] calibrator = Calib ( params , raw_data ) def calibgen ( inputdata ) : co...
Calibrate raw data using a user - supplied function .
36,377
def generate_hourly ( calib_data , hourly_data , process_from ) : start = hourly_data . before ( datetime . max ) if start is None : start = datetime . min start = calib_data . after ( start + SECOND ) if process_from : if start : start = min ( start , process_from ) else : start = process_from if start is None : retur...
Generate hourly summaries from calibrated data .
36,378
def generate_daily ( day_end_hour , use_dst , calib_data , hourly_data , daily_data , process_from ) : start = daily_data . before ( datetime . max ) if start is None : start = datetime . min start = calib_data . after ( start + SECOND ) if process_from : if start : start = min ( start , process_from ) else : start = p...
Generate daily summaries from calibrated and hourly data .
36,379
def generate_monthly ( rain_day_threshold , day_end_hour , use_dst , daily_data , monthly_data , process_from ) : start = monthly_data . before ( datetime . max ) if start is None : start = datetime . min start = daily_data . after ( start + SECOND ) if process_from : if start : start = min ( start , process_from ) els...
Generate monthly summaries from daily data .
36,380
def process_data ( context ) : logger . info ( 'Generating summary data' ) last_raw = context . raw_data . before ( datetime . max ) if last_raw is None : raise IOError ( 'No data found. Check data directory parameter.' ) day_end_hour , use_dst = get_day_end_hour ( context . params ) rain_day_threshold = float ( contex...
Generate summaries from raw weather station data .
36,381
def before ( self , idx ) : if not isinstance ( idx , datetime ) : raise TypeError ( "'%s' is not %s" % ( idx , datetime ) ) day = min ( idx . date ( ) , self . _hi_limit - DAY ) while day >= self . _lo_limit : if day < self . _rd_cache . lo or day >= self . _rd_cache . hi : self . _load ( self . _rd_cache , day ) self...
Return datetime of newest existing data record whose datetime is < idx .
36,382
def after ( self , idx ) : if not isinstance ( idx , datetime ) : raise TypeError ( "'%s' is not %s" % ( idx , datetime ) ) day = max ( idx . date ( ) , self . _lo_limit ) while day < self . _hi_limit : if day < self . _rd_cache . lo or day >= self . _rd_cache . hi : self . _load ( self . _rd_cache , day ) self . _rd_c...
Return datetime of oldest existing data record whose datetime is > = idx .
36,383
def nearest ( self , idx ) : hi = self . after ( idx ) lo = self . before ( idx ) if hi is None : return lo if lo is None : return hi if abs ( hi - idx ) < abs ( lo - idx ) : return hi return lo
Return datetime of record whose datetime is nearest idx .
36,384
def clear ( self ) : for root , dirs , files in os . walk ( self . _root_dir , topdown = False ) : for file in files : os . unlink ( os . path . join ( root , file ) ) os . rmdir ( root ) root_dir = os . path . abspath ( os . path . join ( self . _root_dir , os . pardir ) ) self . __init__ ( root_dir )
Clears all data from the data store permanently
36,385
def pressure_trend_text ( trend ) : _ = pywws . localisation . translation . ugettext if trend > 6.0 : return _ ( u'rising very rapidly' ) elif trend > 3.5 : return _ ( u'rising quickly' ) elif trend > 1.5 : return _ ( u'rising' ) elif trend >= 0.1 : return _ ( u'rising slowly' ) elif trend < - 6.0 : return _ ( u'falli...
Convert pressure trend to a string as used by the UK met office .
36,386
def winddir_text ( pts ) : "Convert wind direction from 0..15 to compass point text" global _winddir_text_array if pts is None : return None if not isinstance ( pts , int ) : pts = int ( pts + 0.5 ) % 16 if not _winddir_text_array : _ = pywws . localisation . translation . ugettext _winddir_text_array = ( _ ( u'N' ) , ...
Convert wind direction from 0 .. 15 to compass point text
36,387
def wind_bft ( ms ) : "Convert wind from metres per second to Beaufort scale" if ms is None : return None for bft in range ( len ( _bft_threshold ) ) : if ms < _bft_threshold [ bft ] : return bft return len ( _bft_threshold )
Convert wind from metres per second to Beaufort scale
36,388
def cadhumidex ( temp , humidity ) : "Calculate Humidity Index as per Canadian Weather Standards" if temp is None or humidity is None : return None saturation_pressure = ( 6.112 * ( 10.0 ** ( 7.5 * temp / ( 237.7 + temp ) ) ) * float ( humidity ) / 100.0 ) return temp + ( 0.555 * ( saturation_pressure - 10.0 ) )
Calculate Humidity Index as per Canadian Weather Standards
36,389
def usaheatindex ( temp , humidity , dew = None ) : if temp is None or humidity is None : return None if dew is None : dew = dew_point ( temp , humidity ) if temp < 26.7 or humidity < 40 or dew < 12.0 : return temp T = ( temp * 1.8 ) + 32.0 R = humidity c_1 = - 42.379 c_2 = 2.04901523 c_3 = 10.14333127 c_4 = - 0.224755...
Calculate Heat Index as per USA National Weather Service Standards
36,390
def load_user_envs ( self ) : installed_packages = self . _list_packages ( ) gym_package = 'gym ({})' . format ( installed_packages [ 'gym' ] ) if 'gym' in installed_packages else 'gym' core_specs = registry . all ( ) for spec in core_specs : spec . source = 'OpenAI Gym Core Package' spec . package = gym_package if not...
Loads downloaded user envs from filesystem cache on import gym
36,391
def make ( self ) : if self . _entry_point is None : raise error . Error ( 'Attempting to make deprecated env {}. (HINT: is there a newer registered version of this env?)' . format ( self . id ) ) cls = load ( self . _entry_point ) env = cls ( ** self . _kwargs ) env . spec = self env = env . build ( extra_wrappers = s...
Instantiates an instance of the environment with appropriate kwargs
36,392
def _record_last_active ( self , host ) : if host in self . hosts : self . hosts = [ host ] + [ h for h in self . hosts if h != host ] self . _last_time_recorded_active = time . time ( )
Put host first in our host list so we try it first next time
36,393
def _request ( self , method , path , op , expected_status = httplib . OK , ** kwargs ) : hosts , path = self . _parse_path ( path ) _transform_user_name_key ( kwargs ) kwargs . setdefault ( 'user.name' , self . user_name ) formatted_args = ' ' . join ( '{}={}' . format ( * t ) for t in kwargs . items ( ) ) _logger . i...
Make a WebHDFS request against the NameNodes
36,394
def create ( self , path , data , ** kwargs ) : metadata_response = self . _put ( path , 'CREATE' , expected_status = httplib . TEMPORARY_REDIRECT , ** kwargs ) assert not metadata_response . content data_response = self . _requests_session . put ( metadata_response . headers [ 'location' ] , data = data , ** self . _r...
Create a file at the given path .
36,395
def append ( self , path , data , ** kwargs ) : metadata_response = self . _post ( path , 'APPEND' , expected_status = httplib . TEMPORARY_REDIRECT , ** kwargs ) data_response = self . _requests_session . post ( metadata_response . headers [ 'location' ] , data = data , ** self . _requests_kwargs ) _check_response ( da...
Append to the given file .
36,396
def concat ( self , target , sources , ** kwargs ) : if isinstance ( sources , basestring ) : raise ValueError ( "sources should be a list" ) if any ( ',' in s for s in sources ) : raise NotImplementedError ( "WebHDFS does not support commas in concat" ) response = self . _post ( target , 'CONCAT' , sources = ',' . joi...
Concat existing files together .
36,397
def open ( self , path , ** kwargs ) : metadata_response = self . _get ( path , 'OPEN' , expected_status = httplib . TEMPORARY_REDIRECT , ** kwargs ) data_response = self . _requests_session . get ( metadata_response . headers [ 'location' ] , stream = True , ** self . _requests_kwargs ) _check_response ( data_response...
Return a file - like object for reading the given HDFS path .
36,398
def create_symlink ( self , link , destination , ** kwargs ) : response = self . _put ( link , 'CREATESYMLINK' , destination = destination , ** kwargs ) assert not response . content
Create a symbolic link at link pointing to destination .
36,399
def rename ( self , path , destination , ** kwargs ) : return _json ( self . _put ( path , 'RENAME' , destination = destination , ** kwargs ) ) [ 'boolean' ]
Renames Path src to Path dst .