idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
231,700
def OnDialectChoice ( self , event ) : dialect_name = event . GetString ( ) value = list ( self . choices [ 'dialects' ] ) . index ( dialect_name ) if dialect_name == 'sniffer' : if self . csvfilepath is None : event . Skip ( ) return None dialect , self . has_header = sniff ( self . csvfilepath ) elif dialect_name == ...
Updates all param widgets confirming to the selcted dialect
231,701
def OnWidget ( self , event ) : self . choice_dialects . SetValue ( len ( self . choices [ 'dialects' ] ) - 1 ) event . Skip ( )
Update the dialect widget to user
231,702
def get_dialect ( self ) : parameters = { } for parameter in self . csv_params [ 2 : ] : pname , ptype , plabel , phelp = parameter widget = self . _widget_from_p ( pname , ptype ) if ptype is types . StringType or ptype is types . UnicodeType : parameters [ pname ] = str ( widget . GetValue ( ) ) elif ptype is types ....
Returns a new dialect that implements the current selection
231,703
def OnMouse ( self , event ) : self . SetGridCursor ( event . Row , event . Col ) self . EnableCellEditControl ( True ) event . Skip ( )
Reduces clicks to enter an edit control
231,704
def OnGridEditorCreated ( self , event ) : editor = event . GetControl ( ) editor . Bind ( wx . EVT_KILL_FOCUS , self . OnGridEditorClosed ) event . Skip ( )
Used to capture Editor close events
231,705
def OnGridEditorClosed ( self , event ) : try : dialect , self . has_header = self . parent . csvwidgets . get_dialect ( ) except TypeError : event . Skip ( ) return 0 self . fill_cells ( dialect , self . has_header , choices = False )
Event handler for end of output type choice
231,706
def get_digest_keys ( self ) : digest_keys = [ ] for col in xrange ( self . GetNumberCols ( ) ) : digest_key = self . GetCellValue ( self . has_header , col ) if digest_key == "" : digest_key = self . digest_types . keys ( ) [ 0 ] digest_keys . append ( digest_key ) return digest_keys
Returns a list of the type choices
231,707
def OnButtonApply ( self , event ) : try : dialect , self . has_header = self . csvwidgets . get_dialect ( ) except TypeError : event . Skip ( ) return 0 self . preview_textctrl . fill ( data = self . data , dialect = dialect ) event . Skip ( )
Updates the preview_textctrl
231,708
def _set_properties ( self ) : self . codetext_ctrl . SetToolTipString ( _ ( "Enter python code here." ) ) self . apply_button . SetToolTipString ( _ ( "Apply changes to current macro" ) ) self . splitter . SetBackgroundStyle ( wx . BG_STYLE_COLOUR ) self . result_ctrl . SetMinSize ( ( 10 , 10 ) )
Setup title size and tooltips
231,709
def OnApply ( self , event ) : try : ast . parse ( self . macros ) except : s = StringIO ( ) e = exc_info ( ) usr_tb = get_user_codeframe ( e [ 2 ] ) or None print_exception ( e [ 0 ] , e [ 1 ] , usr_tb , None , s ) post_command_event ( self . parent , self . MacroErrorMsg , err = s . getvalue ( ) ) success = False els...
Event handler for Apply button
231,710
def update_result_ctrl ( self , event ) : if not self : return printLen = 0 self . result_ctrl . SetValue ( '' ) if hasattr ( event , 'msg' ) : self . result_ctrl . AppendText ( event . msg ) printLen = len ( event . msg ) if hasattr ( event , 'err' ) : errLen = len ( event . err ) errStyle = wx . TextAttr ( wx . RED )...
Update event result following execution by main window
231,711
def _ondim ( self , dimension , valuestring ) : try : self . dimensions [ dimension ] = int ( valuestring ) except ValueError : self . dimensions [ dimension ] = 1 self . textctrls [ dimension ] . SetValue ( str ( 1 ) ) if self . dimensions [ dimension ] < 1 : self . dimensions [ dimension ] = 1 self . textctrls [ dime...
Converts valuestring to int and assigns result to self . dim
231,712
def OnOk ( self , event ) : key_strings = [ self . row_textctrl . GetValue ( ) , self . col_textctrl . GetValue ( ) , self . tab_textctrl . GetValue ( ) ] key = [ ] for key_string in key_strings : try : key . append ( int ( key_string ) ) except ValueError : key . append ( 0 ) post_command_event ( self . parent , self ...
Posts a command event that makes the grid show the entered cell
231,713
def _set_properties ( self ) : self . SetTitle ( _ ( "About pyspread" ) ) label = _ ( "pyspread {version}\nCopyright Martin Manns" ) label = label . format ( version = VERSION ) self . about_label . SetLabel ( label )
Setup title and label
231,714
def get_max_dim ( self , obj ) : try : iter ( obj ) except TypeError : return 0 try : for o in obj : iter ( o ) break except TypeError : return 1 return 2
Returns maximum dimensionality over which obj is iterable < = 2
231,715
def alter ( self , operation , timeout = None , metadata = None , credentials = None ) : return self . stub . Alter ( operation , timeout = timeout , metadata = metadata , credentials = credentials )
Runs alter operation .
231,716
def query ( self , req , timeout = None , metadata = None , credentials = None ) : return self . stub . Query ( req , timeout = timeout , metadata = metadata , credentials = credentials )
Runs query operation .
231,717
def mutate ( self , mutation , timeout = None , metadata = None , credentials = None ) : return self . stub . Mutate ( mutation , timeout = timeout , metadata = metadata , credentials = credentials )
Runs mutate operation .
231,718
def commit_or_abort ( self , ctx , timeout = None , metadata = None , credentials = None ) : return self . stub . CommitOrAbort ( ctx , timeout = timeout , metadata = metadata , credentials = credentials )
Runs commit or abort operation .
231,719
def check_version ( self , check , timeout = None , metadata = None , credentials = None ) : return self . stub . CheckVersion ( check , timeout = timeout , metadata = metadata , credentials = credentials )
Returns the version of the Dgraph instance .
231,720
def alter ( self , operation , timeout = None , metadata = None , credentials = None ) : new_metadata = self . add_login_metadata ( metadata ) try : return self . any_client ( ) . alter ( operation , timeout = timeout , metadata = new_metadata , credentials = credentials ) except Exception as error : if util . is_jwt_e...
Runs a modification via this client .
231,721
def txn ( self , read_only = False , best_effort = False ) : return txn . Txn ( self , read_only = read_only , best_effort = best_effort )
Creates a transaction .
231,722
def query ( self , query , variables = None , timeout = None , metadata = None , credentials = None ) : new_metadata = self . _dg . add_login_metadata ( metadata ) req = self . _common_query ( query , variables = variables ) try : res = self . _dc . query ( req , timeout = timeout , metadata = new_metadata , credential...
Adds a query operation to the transaction .
231,723
def mutate ( self , mutation = None , set_obj = None , del_obj = None , set_nquads = None , del_nquads = None , commit_now = None , ignore_index_conflict = None , timeout = None , metadata = None , credentials = None ) : mutation = self . _common_mutate ( mutation = mutation , set_obj = set_obj , del_obj = del_obj , se...
Adds a mutate operation to the transaction .
231,724
def commit ( self , timeout = None , metadata = None , credentials = None ) : if not self . _common_commit ( ) : return new_metadata = self . _dg . add_login_metadata ( metadata ) try : self . _dc . commit_or_abort ( self . _ctx , timeout = timeout , metadata = new_metadata , credentials = credentials ) except Exceptio...
Commits the transaction .
231,725
def discard ( self , timeout = None , metadata = None , credentials = None ) : if not self . _common_discard ( ) : return new_metadata = self . _dg . add_login_metadata ( metadata ) try : self . _dc . commit_or_abort ( self . _ctx , timeout = timeout , metadata = new_metadata , credentials = credentials ) except Except...
Discards the transaction .
231,726
def merge_context ( self , src = None ) : if src is None : return if self . _ctx . start_ts == 0 : self . _ctx . start_ts = src . start_ts elif self . _ctx . start_ts != src . start_ts : raise Exception ( 'StartTs mismatch' ) self . _ctx . keys . extend ( src . keys ) self . _ctx . preds . extend ( src . preds )
Merges context from this instance with src .
231,727
def generate_token ( self , * args , ** kwargs ) : length = random . randint ( self . min_length , self . max_length ) return binascii . hexlify ( os . urandom ( self . max_length ) ) . decode ( ) [ 0 : length ]
generates a pseudo random code using os . urandom and binascii . hexlify
231,728
def get_text ( self , node ) : try : return node . children [ 0 ] . content or "" except ( AttributeError , IndexError ) : return node . content or ""
Try to emit whatever text is in the node .
231,729
def emit_children ( self , node ) : return "" . join ( [ self . emit_node ( child ) for child in node . children ] )
Emit all the children of a node .
231,730
def emit_node ( self , node ) : emit = getattr ( self , "%s_emit" % node . kind , self . default_emit ) return emit ( node )
Emit a single node .
231,731
def ajax_preview ( request , ** kwargs ) : data = { "html" : render_to_string ( "pinax/blog/_preview.html" , { "content" : parse ( request . POST . get ( "markup" ) ) } ) } return JsonResponse ( data )
Currently only supports markdown
231,732
def set_system_lock ( cls , redis , name , timeout ) : pipeline = redis . pipeline ( ) pipeline . zadd ( name , SYSTEM_LOCK_ID , time . time ( ) + timeout ) pipeline . expire ( name , timeout + 10 ) pipeline . execute ( )
Set system lock for the semaphore .
231,733
def acquire ( self ) : acquired , locks = self . _semaphore ( keys = [ self . name ] , args = [ self . lock_id , self . max_locks , self . timeout , time . time ( ) ] ) acquired = True if acquired == 1 else False return acquired , locks
Obtain a semaphore lock .
231,734
def renew ( self , new_timeout ) : if self . local . token is None : raise LockError ( "Cannot extend an unlocked lock" ) if self . timeout is None : raise LockError ( "Cannot extend a lock with no timeout" ) return self . do_renew ( new_timeout )
Sets a new timeout for an already acquired lock .
231,735
def task ( self , _fn = None , queue = None , hard_timeout = None , unique = None , lock = None , lock_key = None , retry = None , retry_on = None , retry_method = None , schedule = None , batch = False , max_queue_size = None ) : def _delay ( func ) : def _delay_inner ( * args , ** kwargs ) : return self . delay ( fun...
Function decorator that defines the behavior of the function when it is used as a task . To use the default behavior tasks don t need to be decorated .
231,736
def run_worker ( self , queues = None , module = None , exclude_queues = None , max_workers_per_queue = None , store_tracebacks = None ) : try : module_names = module or '' for module_name in module_names . split ( ',' ) : module_name = module_name . strip ( ) if module_name : importlib . import_module ( module_name ) ...
Main worker entry point method .
231,737
def delay ( self , func , args = None , kwargs = None , queue = None , hard_timeout = None , unique = None , lock = None , lock_key = None , when = None , retry = None , retry_on = None , retry_method = None , max_queue_size = None ) : task = Task ( self , func , args = args , kwargs = kwargs , queue = queue , hard_tim...
Queues a task . See README . rst for an explanation of the options .
231,738
def get_queue_sizes ( self , queue ) : states = [ QUEUED , SCHEDULED , ACTIVE ] pipeline = self . connection . pipeline ( ) for state in states : pipeline . zcard ( self . _key ( state , queue ) ) results = pipeline . execute ( ) return dict ( zip ( states , results ) )
Get the queue s number of tasks in each state .
231,739
def get_queue_system_lock ( self , queue ) : key = self . _key ( LOCK_REDIS_KEY , queue ) return Semaphore . get_system_lock ( self . connection , key )
Get system lock timeout
231,740
def set_queue_system_lock ( self , queue , timeout ) : key = self . _key ( LOCK_REDIS_KEY , queue ) Semaphore . set_system_lock ( self . connection , key , timeout )
Set system lock on a queue .
231,741
def _install_signal_handlers ( self ) : def request_stop ( signum , frame ) : self . _stop_requested = True self . log . info ( 'stop requested, waiting for task to finish' ) signal . signal ( signal . SIGINT , request_stop ) signal . signal ( signal . SIGTERM , request_stop )
Sets up signal handlers for safely stopping the worker .
231,742
def _uninstall_signal_handlers ( self ) : signal . signal ( signal . SIGINT , signal . SIG_DFL ) signal . signal ( signal . SIGTERM , signal . SIG_DFL )
Restores default signal handlers .
231,743
def _filter_queues ( self , queues ) : def match ( queue ) : for part in reversed_dotted_parts ( queue ) : if part in self . exclude_queues : return False if part in self . only_queues : return True return not self . only_queues return [ q for q in queues if match ( q ) ]
Applies the queue filter to the given list of queues and returns the queues that match . Note that a queue name matches any subqueues starting with the name followed by a date . For example foo will match both foo and foo . bar .
231,744
def _worker_queue_scheduled_tasks ( self ) : queues = set ( self . _filter_queues ( self . connection . smembers ( self . _key ( SCHEDULED ) ) ) ) now = time . time ( ) for queue in queues : result = self . scripts . zpoppush ( self . _key ( SCHEDULED , queue ) , self . _key ( QUEUED , queue ) , self . config [ 'SCHEDU...
Helper method that takes due tasks from the SCHEDULED queue and puts them in the QUEUED queue for execution . This should be called periodically .
231,745
def _wait_for_new_tasks ( self , timeout = 0 , batch_timeout = 0 ) : new_queue_found = False start_time = batch_exit = time . time ( ) while True : if batch_exit > start_time : pubsub_sleep = batch_exit - time . time ( ) else : pubsub_sleep = start_time + timeout - time . time ( ) message = self . _pubsub . get_message...
Check activity channel and wait as necessary .
231,746
def _execute_forked ( self , tasks , log ) : success = False execution = { } assert len ( tasks ) task_func = tasks [ 0 ] . serialized_func assert all ( [ task_func == task . serialized_func for task in tasks [ 1 : ] ] ) execution [ 'time_started' ] = time . time ( ) exc = None exc_info = None try : func = tasks [ 0 ] ...
Executes the tasks in the forked process . Multiple tasks can be passed for batch processing . However they must all use the same function and will share the execution entry .
231,747
def _get_queue_batch_size ( self , queue ) : batch_queues = self . config [ 'BATCH_QUEUES' ] batch_size = 1 for part in dotted_parts ( queue ) : if part in batch_queues : batch_size = batch_queues [ part ] return batch_size
Get queue batch size .
231,748
def _get_queue_lock ( self , queue , log ) : max_workers = self . max_workers_per_queue for part in dotted_parts ( queue ) : if part in self . single_worker_queues : log . debug ( 'single worker queue' ) max_workers = 1 break if max_workers : queue_lock = Semaphore ( self . connection , self . _key ( LOCK_REDIS_KEY , q...
Get queue lock for max worker queues .
231,749
def _heartbeat ( self , queue , task_ids ) : now = time . time ( ) self . connection . zadd ( self . _key ( ACTIVE , queue ) , ** { task_id : now for task_id in task_ids } )
Updates the heartbeat for the given task IDs to prevent them from timing out and being requeued .
231,750
def _execute ( self , queue , tasks , log , locks , queue_lock , all_task_ids ) : assert len ( tasks ) task_func = tasks [ 0 ] . serialized_func assert all ( [ task_func == task . serialized_func for task in tasks [ 1 : ] ] ) if task_func in self . tiger . periodic_task_funcs : tasks [ 0 ] . _queue_for_next_period ( ) ...
Executes the given tasks . Returns a boolean indicating whether the tasks were executed successfully .
231,751
def _process_queue_message ( self , message_queue , new_queue_found , batch_exit , start_time , timeout , batch_timeout ) : for queue in self . _filter_queues ( [ message_queue ] ) : if queue not in self . _queue_set : if not new_queue_found : new_queue_found = True batch_exit = time . time ( ) + batch_timeout if batch...
Process a queue message from activity channel .
231,752
def _process_queue_tasks ( self , queue , queue_lock , task_ids , now , log ) : processed_count = 0 serialized_tasks = self . connection . mget ( [ self . _key ( 'task' , task_id ) for task_id in task_ids ] ) tasks = [ ] for task_id , serialized_task in zip ( task_ids , serialized_tasks ) : if serialized_task : task_da...
Process tasks in queue .
231,753
def _process_from_queue ( self , queue ) : now = time . time ( ) log = self . log . bind ( queue = queue ) batch_size = self . _get_queue_batch_size ( queue ) queue_lock , failed_to_acquire = self . _get_queue_lock ( queue , log ) if failed_to_acquire : return [ ] , - 1 later = time . time ( ) + self . config [ 'LOCK_R...
Internal method to process a task batch from the given queue .
231,754
def _execute_task_group ( self , queue , tasks , all_task_ids , queue_lock ) : log = self . log . bind ( queue = queue ) locks = [ ] lock_ids = set ( ) ready_tasks = [ ] for task in tasks : if task . lock : if task . lock_key : kwargs = task . kwargs lock_id = gen_unique_id ( task . serialized_func , None , { key : kwa...
Executes the given tasks in the queue . Updates the heartbeat for task IDs passed in all_task_ids . This internal method is only meant to be called from within _process_from_queue .
231,755
def _finish_task_processing ( self , queue , task , success ) : log = self . log . bind ( queue = queue , task_id = task . id ) def _mark_done ( ) : task . _move ( from_state = ACTIVE ) log . info ( 'done' ) if success : _mark_done ( ) else : should_retry = False should_log_error = True execution = self . connection . ...
After a task is executed this method is called and ensures that the task gets properly removed from the ACTIVE queue and in case of an error retried or marked as failed .
231,756
def run ( self , once = False , force_once = False ) : self . log . info ( 'ready' , id = self . id , queues = sorted ( self . only_queues ) , exclude_queues = sorted ( self . exclude_queues ) , single_worker_queues = sorted ( self . single_worker_queues ) , max_workers = self . max_workers_per_queue ) if not self . sc...
Main loop of the worker .
231,757
def can_replicate_commands ( self ) : if not hasattr ( self , '_can_replicate_commands' ) : info = self . redis . info ( 'server' ) version_info = info [ 'redis_version' ] . split ( '.' ) major , minor = int ( version_info [ 0 ] ) , int ( version_info [ 1 ] ) result = major > 3 or major == 3 and minor >= 2 self . _can_...
Whether Redis supports single command replication .
231,758
def zpoppush ( self , source , destination , count , score , new_score , client = None , withscores = False , on_success = None , if_exists = None ) : if score is None : score = '+inf' if withscores : if on_success : raise NotImplementedError ( ) return self . _zpoppush_withscores ( keys = [ source , destination ] , ar...
Pops the first count members from the ZSET source and adds them to the ZSET destination with a score of new_score . If score is not None only members up to a score of score are used . Returns the members that were moved and if withscores is True their original scores .
231,759
def execute_pipeline ( self , pipeline , client = None ) : client = client or self . redis executing_pipeline = None try : stack = pipeline . command_stack script_args = [ int ( self . can_replicate_commands ) , len ( stack ) ] for args , options in stack : script_args += [ len ( args ) - 1 ] + list ( args ) if self . ...
Executes the given Redis pipeline as a Lua script . When an error occurs the transaction stops executing and an exception is raised . This differs from Redis transactions where execution continues after an error . On success a list of results is returned . The pipeline is cleared after execution and can no longer be re...
231,760
def gen_unique_id ( serialized_name , args , kwargs ) : return hashlib . sha256 ( json . dumps ( { 'func' : serialized_name , 'args' : args , 'kwargs' : kwargs , } , sort_keys = True ) . encode ( 'utf8' ) ) . hexdigest ( )
Generates and returns a hex - encoded 256 - bit ID for the given task name and args . Used to generate IDs for unique tasks or for task locks .
231,761
def serialize_func_name ( func ) : if func . __module__ == '__main__' : raise ValueError ( 'Functions from the __main__ module cannot be ' 'processed by workers.' ) try : func_name = func . __qualname__ except AttributeError : func_name = func . __name__ return ':' . join ( [ func . __module__ , func_name ] )
Returns the dotted serialized path to the passed function .
231,762
def dotted_parts ( s ) : idx = - 1 while s : idx = s . find ( '.' , idx + 1 ) if idx == - 1 : yield s break yield s [ : idx ]
For a string a . b . c yields a a . b a . b . c .
231,763
def reversed_dotted_parts ( s ) : idx = - 1 if s : yield s while s : idx = s . rfind ( '.' , 0 , idx ) if idx == - 1 : break yield s [ : idx ]
For a string a . b . c yields a . b . c a . b a .
231,764
def tasktiger_processor ( logger , method_name , event_dict ) : if g [ 'current_tasks' ] is not None and not g [ 'current_task_is_batch' ] : event_dict [ 'task_id' ] = g [ 'current_tasks' ] [ 0 ] . id return event_dict
TaskTiger structlog processor .
231,765
def should_retry_on ( self , exception_class , logger = None ) : for n in ( self . retry_on or [ ] ) : try : if issubclass ( exception_class , import_attribute ( n ) ) : return True except TaskImportError : if logger : logger . error ( 'should_retry_on could not import class' , exception_name = n ) return False
Whether this task should be retried when the given exception occurs .
231,766
def update_scheduled_time ( self , when ) : tiger = self . tiger ts = get_timestamp ( when ) assert ts pipeline = tiger . connection . pipeline ( ) key = tiger . _key ( SCHEDULED , self . queue ) tiger . scripts . zadd ( key , ts , self . id , mode = 'xx' , client = pipeline ) pipeline . zscore ( key , self . id ) _ , ...
Updates a scheduled task s date to the given date . If the task is not scheduled a TaskNotFound exception is raised .
231,767
def n_executions ( self ) : pipeline = self . tiger . connection . pipeline ( ) pipeline . exists ( self . tiger . _key ( 'task' , self . id ) ) pipeline . llen ( self . tiger . _key ( 'task' , self . id , 'executions' ) ) exists , n_executions = pipeline . execute ( ) if not exists : raise TaskNotFound ( 'Task {} not ...
Queries and returns the number of past task executions .
231,768
def set_input ( self , nr = 2 , qd = 1 , b = 0 ) : self . nr = nr self . qd = qd self . b = b
Set inputs after initialization
231,769
def generateNoise ( self ) : wfb = np . zeros ( self . nr * 2 ) wfb [ : self . nr ] = np . random . normal ( 0 , np . sqrt ( self . qd ) , self . nr ) mhb = - self . b / 2.0 hfb = np . zeros ( self . nr * 2 ) hfb = np . zeros ( self . nr * 2 ) hfb [ 0 ] = 1.0 indices = np . arange ( self . nr - 1 ) hfb [ 1 : self . nr ...
Generate noise time series based on input parameters
231,770
def adev ( self , tau0 , tau ) : prefactor = self . adev_from_qd ( tau0 = tau0 , tau = tau ) c = self . c_avar ( ) avar = pow ( prefactor , 2 ) * pow ( tau , c ) return np . sqrt ( avar )
return predicted ADEV of noise - type at given tau
231,771
def mdev ( self , tau0 , tau ) : prefactor = self . mdev_from_qd ( tau0 = tau0 , tau = tau ) c = self . c_mvar ( ) mvar = pow ( prefactor , 2 ) * pow ( tau , c ) return np . sqrt ( mvar )
return predicted MDEV of noise - type at given tau
231,772
def scipy_psd ( x , f_sample = 1.0 , nr_segments = 4 ) : f_axis , psd_of_x = scipy . signal . welch ( x , f_sample , nperseg = len ( x ) / nr_segments ) return f_axis , psd_of_x
PSD routine from scipy we can compare our own numpy result against this one
231,773
def iterpink ( depth = 20 ) : values = numpy . random . randn ( depth ) smooth = numpy . random . randn ( depth ) source = numpy . random . randn ( depth ) sumvals = values . sum ( ) i = 0 while True : yield sumvals + smooth [ i ] i += 1 if i == depth : i = 0 smooth = numpy . random . randn ( depth ) source = numpy . r...
Generate a sequence of samples of pink noise .
231,774
def plotline ( plt , alpha , taus , style , label = "" ) : y = [ pow ( tt , alpha ) for tt in taus ] plt . loglog ( taus , y , style , label = label )
plot a line with the slope alpha
231,775
def b1_noise_id ( x , af , rate ) : ( taus , devs , errs , ns ) = at . adev ( x , taus = [ af * rate ] , data_type = "phase" , rate = rate ) oadev_x = devs [ 0 ] y = np . diff ( x ) y_cut = np . array ( y [ : len ( y ) - ( len ( y ) % af ) ] ) assert len ( y_cut ) % af == 0 y_shaped = y_cut . reshape ( ( int ( len ( y_...
B1 ratio for noise identification ratio of Standard Variace to AVAR
231,776
def plot ( self , atDataset , errorbars = False , grid = False ) : if errorbars : self . ax . errorbar ( atDataset . out [ "taus" ] , atDataset . out [ "stat" ] , yerr = atDataset . out [ "stat_err" ] , ) else : self . ax . plot ( atDataset . out [ "taus" ] , atDataset . out [ "stat" ] , ) self . ax . set_xlabel ( "Tau...
use matplotlib methods for plotting
231,777
def greenhall_table2 ( alpha , d ) : row_idx = int ( - alpha + 2 ) assert ( row_idx in [ 0 , 1 , 2 , 3 , 4 , 5 ] ) col_idx = int ( d - 1 ) table2 = [ [ ( 3.0 / 2.0 , 1.0 / 2.0 ) , ( 35.0 / 18.0 , 1.0 ) , ( 231.0 / 100.0 , 3.0 / 2.0 ) ] , [ ( 78.6 , 25.2 ) , ( 790.0 , 410.0 ) , ( 9950.0 , 6520.0 ) ] , [ ( 2.0 / 3.0 , 1....
Table 2 from Greenhall 2004
231,778
def greenhall_table1 ( alpha , d ) : row_idx = int ( - alpha + 2 ) col_idx = int ( d - 1 ) table1 = [ [ ( 2.0 / 3.0 , 1.0 / 3.0 ) , ( 7.0 / 9.0 , 1.0 / 2.0 ) , ( 22.0 / 25.0 , 2.0 / 3.0 ) ] , [ ( 0.840 , 0.345 ) , ( 0.997 , 0.616 ) , ( 1.141 , 0.843 ) ] , [ ( 1.079 , 0.368 ) , ( 1.033 , 0.607 ) , ( 1.184 , 0.848 ) ] , ...
Table 1 from Greenhall 2004
231,779
def edf_mtotdev ( N , m , alpha ) : assert ( alpha in [ 2 , 1 , 0 , - 1 , - 2 ] ) NIST_SP1065_table8 = [ ( 1.90 , 2.1 ) , ( 1.20 , 1.40 ) , ( 1.10 , 1.2 ) , ( 0.85 , 0.50 ) , ( 0.75 , 0.31 ) ] ( b , c ) = NIST_SP1065_table8 [ abs ( alpha - 2 ) ] edf = b * ( float ( N ) / float ( m ) ) - c print ( "mtotdev b,c= " , ( b ...
Equivalent degrees of freedom for Modified Total Deviation NIST SP1065 page 41 Table 8
231,780
def edf_simple ( N , m , alpha ) : N = float ( N ) m = float ( m ) if alpha in [ 2 , 1 , 0 , - 1 , - 2 ] : if alpha == + 2 : edf = ( N + 1 ) * ( N - 2 * m ) / ( 2 * ( N - m ) ) if alpha == 0 : edf = ( ( ( 3 * ( N - 1 ) / ( 2 * m ) ) - ( 2 * ( N - 2 ) / N ) ) * ( ( 4 * pow ( m , 2 ) ) / ( ( 4 * pow ( m , 2 ) ) + 5 ) ) )...
Equivalent degrees of freedom . Simple approximate formulae .
231,781
def example1 ( ) : N = 1000 f = 1 y = np . random . randn ( 1 , N ) [ 0 , : ] x = [ xx for xx in np . linspace ( 1 , len ( y ) , len ( y ) ) ] x_ax , y_ax , ( err_l , err_h ) , ns = allan . gradev ( y , data_type = 'phase' , rate = f , taus = x ) plt . errorbar ( x_ax , y_ax , yerr = [ err_l , err_h ] , label = 'GRADEV...
Compute the GRADEV of a white phase noise . Compares two different scenarios . 1 ) The original data and 2 ) ADEV estimate with gap robust ADEV .
231,782
def example2 ( ) : N = 1000 f = 1 s = 1 + 5 / N * np . arange ( 0 , N ) y = s * np . random . randn ( 1 , N ) [ 0 , : ] x = [ xx for xx in np . linspace ( 1 , len ( y ) , len ( y ) ) ] x_ax , y_ax , ( err_l , err_h ) , ns = allan . gradev ( y , data_type = 'phase' , rate = f , taus = x ) plt . loglog ( x_ax , y_ax , 'b...
Compute the GRADEV of a nonstationary white phase noise .
231,783
def tdev ( data , rate = 1.0 , data_type = "phase" , taus = None ) : phase = input_to_phase ( data , rate , data_type ) ( taus , md , mde , ns ) = mdev ( phase , rate = rate , taus = taus ) td = taus * md / np . sqrt ( 3.0 ) tde = td / np . sqrt ( ns ) return taus , td , tde , ns
Time deviation . Based on modified Allan variance .
231,784
def mdev ( data , rate = 1.0 , data_type = "phase" , taus = None ) : phase = input_to_phase ( data , rate , data_type ) ( phase , ms , taus_used ) = tau_generator ( phase , rate , taus = taus ) data , taus = np . array ( phase ) , np . array ( taus ) md = np . zeros_like ( ms ) mderr = np . zeros_like ( ms ) ns = np . ...
Modified Allan deviation . Used to distinguish between White and Flicker Phase Modulation .
231,785
def adev ( data , rate = 1.0 , data_type = "phase" , taus = None ) : phase = input_to_phase ( data , rate , data_type ) ( phase , m , taus_used ) = tau_generator ( phase , rate , taus ) ad = np . zeros_like ( taus_used ) ade = np . zeros_like ( taus_used ) adn = np . zeros_like ( taus_used ) for idx , mj in enumerate (...
Allan deviation . Classic - use only if required - relatively poor confidence .
231,786
def ohdev ( data , rate = 1.0 , data_type = "phase" , taus = None ) : phase = input_to_phase ( data , rate , data_type ) ( phase , m , taus_used ) = tau_generator ( phase , rate , taus ) hdevs = np . zeros_like ( taus_used ) hdeverrs = np . zeros_like ( taus_used ) ns = np . zeros_like ( taus_used ) for idx , mj in enu...
Overlapping Hadamard deviation . Better confidence than normal Hadamard .
231,787
def calc_hdev_phase ( phase , rate , mj , stride ) : tau0 = 1.0 / float ( rate ) mj = int ( mj ) stride = int ( stride ) d3 = phase [ 3 * mj : : stride ] d2 = phase [ 2 * mj : : stride ] d1 = phase [ 1 * mj : : stride ] d0 = phase [ : : stride ] n = min ( len ( d0 ) , len ( d1 ) , len ( d2 ) , len ( d3 ) ) v_arr = d3 [...
main calculation fungtion for HDEV and OHDEV
231,788
def totdev ( data , rate = 1.0 , data_type = "phase" , taus = None ) : phase = input_to_phase ( data , rate , data_type ) ( phase , m , taus_used ) = tau_generator ( phase , rate , taus ) N = len ( phase ) x1 = 2.0 * phase [ 0 ] * np . ones ( ( N - 2 , ) ) x1 = x1 - phase [ 1 : - 1 ] x1 = x1 [ : : - 1 ] x2 = 2.0 * phas...
Total deviation . Better confidence at long averages for Allan .
231,789
def mtotdev ( data , rate = 1.0 , data_type = "phase" , taus = None ) : phase = input_to_phase ( data , rate , data_type ) ( phase , ms , taus_used ) = tau_generator ( phase , rate , taus , maximum_m = float ( len ( phase ) ) / 3.0 ) devs = np . zeros_like ( taus_used ) deverrs = np . zeros_like ( taus_used ) ns = np ....
PRELIMINARY - REQUIRES FURTHER TESTING . Modified Total deviation . Better confidence at long averages for modified Allan
231,790
def htotdev ( data , rate = 1.0 , data_type = "phase" , taus = None ) : if data_type == "phase" : phase = data freq = phase2frequency ( phase , rate ) elif data_type == "freq" : phase = frequency2phase ( data , rate ) freq = data else : raise Exception ( "unknown data_type: " + data_type ) rate = float ( rate ) ( freq ...
PRELIMINARY - REQUIRES FURTHER TESTING . Hadamard Total deviation . Better confidence at long averages for Hadamard deviation
231,791
def theo1 ( data , rate = 1.0 , data_type = "phase" , taus = None ) : phase = input_to_phase ( data , rate , data_type ) tau0 = 1.0 / rate ( phase , ms , taus_used ) = tau_generator ( phase , rate , taus , even = True ) devs = np . zeros_like ( taus_used ) deverrs = np . zeros_like ( taus_used ) ns = np . zeros_like ( ...
PRELIMINARY - REQUIRES FURTHER TESTING . Theo1 is a two - sample variance with improved confidence and extended averaging factor range .
231,792
def tierms ( data , rate = 1.0 , data_type = "phase" , taus = None ) : phase = input_to_phase ( data , rate , data_type ) ( data , m , taus_used ) = tau_generator ( phase , rate , taus ) count = len ( phase ) devs = np . zeros_like ( taus_used ) deverrs = np . zeros_like ( taus_used ) ns = np . zeros_like ( taus_used )...
Time Interval Error RMS .
231,793
def mtie ( data , rate = 1.0 , data_type = "phase" , taus = None ) : phase = input_to_phase ( data , rate , data_type ) ( phase , m , taus_used ) = tau_generator ( phase , rate , taus ) devs = np . zeros_like ( taus_used ) deverrs = np . zeros_like ( taus_used ) ns = np . zeros_like ( taus_used ) for idx , mj in enumer...
Maximum Time Interval Error .
231,794
def mtie_phase_fast ( phase , rate = 1.0 , data_type = "phase" , taus = None ) : rate = float ( rate ) phase = np . asarray ( phase ) k_max = int ( np . floor ( np . log2 ( len ( phase ) ) ) ) phase = phase [ 0 : pow ( 2 , k_max ) ] assert len ( phase ) == pow ( 2 , k_max ) taus = [ pow ( 2 , k ) for k in range ( k_max...
fast binary decomposition algorithm for MTIE
231,795
def gradev ( data , rate = 1.0 , data_type = "phase" , taus = None , ci = 0.9 , noisetype = 'wp' ) : if ( data_type == "freq" ) : print ( "Warning : phase data is preferred as input to gradev()" ) phase = input_to_phase ( data , rate , data_type ) ( data , m , taus_used ) = tau_generator ( phase , rate , taus ) ad = np...
gap resistant overlapping Allan deviation
231,796
def input_to_phase ( data , rate , data_type ) : if data_type == "phase" : return data elif data_type == "freq" : return frequency2phase ( data , rate ) else : raise Exception ( "unknown data_type: " + data_type )
Take either phase or frequency as input and return phase
231,797
def trim_data ( x ) : first = 0 while np . isnan ( x [ first ] ) : first += 1 last = len ( x ) while np . isnan ( x [ last - 1 ] ) : last -= 1 return x [ first : last ]
Trim leading and trailing NaNs from dataset This is done by browsing the array from each end and store the index of the first non - NaN in each case the return the appropriate slice of the array
231,798
def three_cornered_hat_phase ( phasedata_ab , phasedata_bc , phasedata_ca , rate , taus , function ) : ( tau_ab , dev_ab , err_ab , ns_ab ) = function ( phasedata_ab , data_type = 'phase' , rate = rate , taus = taus ) ( tau_bc , dev_bc , err_bc , ns_bc ) = function ( phasedata_bc , data_type = 'phase' , rate = rate , t...
Three Cornered Hat Method
231,799
def frequency2phase ( freqdata , rate ) : dt = 1.0 / float ( rate ) freqdata = trim_data ( freqdata ) phasedata = np . cumsum ( freqdata ) * dt phasedata = np . insert ( phasedata , 0 , 0 ) return phasedata
integrate fractional frequency data and output phase data