idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
33,000
def assert_records_equal_nonvolatile ( first , second , volatile_fields , indent = 0 ) : if isinstance ( first , dict ) and isinstance ( second , dict ) : if set ( first ) != set ( second ) : logging . error ( '%sMismatching keys:' , ' ' * indent ) logging . error ( '%s %s' , ' ' * indent , list ( first . keys ( ) ) )...
Compare two test_record tuples ignoring any volatile fields .
33,001
def convert_to_base_types ( obj , ignore_keys = tuple ( ) , tuple_type = tuple , json_safe = True ) : assert not isinstance ( ignore_keys , six . string_types ) , 'Pass a real iterable!' if hasattr ( obj , 'as_base_types' ) : return obj . as_base_types ( ) if hasattr ( obj , '_asdict' ) : obj = obj . _asdict ( ) elif i...
Recursively convert objects into base types .
33,002
def total_size ( obj ) : seen = set ( ) def sizeof ( current_obj ) : try : return _sizeof ( current_obj ) except Exception : return struct . calcsize ( 'P' ) def _sizeof ( current_obj ) : if id ( current_obj ) in seen : return struct . calcsize ( 'P' ) seen . add ( id ( current_obj ) ) size = sys . getsizeof ( current_...
Returns the approximate total memory footprint an object .
33,003
def open_output_file ( self , test_record ) : record_dict = data . convert_to_base_types ( test_record , ignore_keys = ( 'code_info' , 'phases' , 'log_records' ) ) pattern = self . filename_pattern if isinstance ( pattern , six . string_types ) or callable ( pattern ) : output_file = self . open_file ( util . format_st...
Open file based on pattern .
33,004
def mutable_record_transform ( cls ) : if not ( len ( cls . bases ) > 0 and isinstance ( cls . bases [ 0 ] , astroid . Call ) and cls . bases [ 0 ] . func . as_string ( ) == 'mutablerecords.Record' ) : return try : if len ( cls . bases [ 0 ] . args ) >= 2 : for a in cls . bases [ 0 ] . args [ 1 ] . elts : cls . locals ...
Transform mutable records usage by updating locals .
33,005
def _log_every_n_to_logger ( n , logger , level , message , * args ) : logger = logger or logging . getLogger ( ) def _gen ( ) : while True : for _ in range ( n ) : yield False logger . log ( level , message , * args ) yield True gen = _gen ( ) return lambda : six . next ( gen )
Logs the given message every n calls to a logger .
33,006
def log_every_n ( n , level , message , * args ) : return _log_every_n_to_logger ( n , None , level , message , * args )
Logs a message every n calls . See _log_every_n_to_logger .
33,007
def partial_format ( target , ** kwargs ) : output = target [ : ] for tag , var in re . findall ( r'(\{(.*?)\})' , output ) : root = var . split ( '.' ) [ 0 ] root = root . split ( '[' ) [ 0 ] if root in kwargs : output = output . replace ( tag , tag . format ( ** { root : kwargs [ root ] } ) ) return output
Formats a string without requiring all values to be present .
33,008
def asdict_with_event ( self ) : event = threading . Event ( ) with self . _lock : self . _update_events . add ( event ) return self . _asdict ( ) , event
Get a dict representation of this object and an update event .
33,009
def notify_update ( self ) : with self . _lock : for event in self . _update_events : event . set ( ) self . _update_events . clear ( )
Notify any update events that there was an update .
33,010
def bind_port ( requested_port ) : sockets = tornado . netutil . bind_sockets ( requested_port ) if requested_port != 0 : return sockets , requested_port for s in sockets : host , port = s . getsockname ( ) [ : 2 ] if host == '0.0.0.0' : return sockets , port raise RuntimeError ( 'Could not determine the bound port.' )
Bind sockets to an available port returning sockets and the bound port .
33,011
def loop_until_timeout_or_valid ( timeout_s , function , validation_fn , sleep_s = 1 ) : if timeout_s is None or not hasattr ( timeout_s , 'has_expired' ) : timeout_s = PolledTimeout ( timeout_s ) while True : result = function ( ) if validation_fn ( result ) or timeout_s . has_expired ( ) : return result time . sleep ...
Loops until the specified function returns valid or a timeout is reached .
33,012
def loop_until_timeout_or_true ( timeout_s , function , sleep_s = 1 ) : return loop_until_timeout_or_valid ( timeout_s , function , lambda x : x , sleep_s )
Loops until the specified function returns True or a timeout is reached .
33,013
def loop_until_timeout_or_not_none ( timeout_s , function , sleep_s = 1 ) : return loop_until_timeout_or_valid ( timeout_s , function , lambda x : x is not None , sleep_s )
Loops until the specified function returns non - None or until a timeout .
33,014
def loop_until_true_else_raise ( timeout_s , function , invert = False , message = None , sleep_s = 1 ) : def validate ( x ) : return bool ( x ) != invert result = loop_until_timeout_or_valid ( timeout_s , function , validate , sleep_s = 1 ) if validate ( result ) : return result if message is not None : raise RuntimeE...
Repeatedly call the given function until truthy or raise on a timeout .
33,015
def execute_forever ( method , interval_s ) : interval = Interval ( method ) interval . start ( interval_s ) return interval
Executes a method forever at the specified interval .
33,016
def execute_until_false ( method , interval_s ) : interval = Interval ( method , stop_if_false = True ) interval . start ( interval_s ) return interval
Executes a method forever until the method returns a false value .
33,017
def retry_until_true_or_limit_reached ( method , limit , sleep_s = 1 , catch_exceptions = ( ) ) : return retry_until_valid_or_limit_reached ( method , limit , lambda x : x , sleep_s , catch_exceptions )
Executes a method until the retry limit is hit or True is returned .
33,018
def retry_until_not_none_or_limit_reached ( method , limit , sleep_s = 1 , catch_exceptions = ( ) ) : return retry_until_valid_or_limit_reached ( method , limit , lambda x : x is not None , sleep_s , catch_exceptions )
Executes a method until the retry limit is hit or not None is returned .
33,019
def retry_until_valid_or_limit_reached ( method , limit , validation_fn , sleep_s = 1 , catch_exceptions = ( ) ) : assert limit > 0 , 'Limit must be greater than 0' def _execute_method ( helper ) : try : return method ( ) except catch_exceptions : if not helper . remaining : raise return None helper = RetryHelper ( lim...
Executes a method until the retry limit or validation_fn returns True .
33,020
def take_at_least_n_seconds ( time_s ) : timeout = PolledTimeout ( time_s ) yield while not timeout . has_expired ( ) : time . sleep ( timeout . remaining )
A context manager which ensures it takes at least time_s to execute .
33,021
def take_at_most_n_seconds ( time_s , func , * args , ** kwargs ) : thread = threading . Thread ( target = func , args = args , kwargs = kwargs ) thread . start ( ) thread . join ( time_s ) if thread . is_alive ( ) : return False return True
A function that returns whether a function call took less than time_s .
33,022
def execute_after_delay ( time_s , func , * args , ** kwargs ) : timeout = PolledTimeout . from_seconds ( time_s ) def target ( ) : time . sleep ( timeout . remaining ) try : func ( * args , ** kwargs ) except Exception : _LOG . exception ( 'Error executing %s after %s expires.' , func , timeout ) if timeout . remainin...
A function that executes the given function after a delay .
33,023
def from_millis ( cls , timeout_ms ) : if hasattr ( timeout_ms , 'has_expired' ) : return timeout_ms if timeout_ms is None : return cls ( None ) return cls ( timeout_ms / 1000.0 )
Create a new PolledTimeout if needed .
33,024
def start ( self , interval_s ) : if self . running : return False self . stopped . clear ( ) def _execute ( ) : if not self . method ( ) and self . stop_if_false : return while not self . stopped . wait ( interval_s ) : if not self . method ( ) and self . stop_if_false : return self . thread = threading . Thread ( tar...
Starts executing the method at the specified interval .
33,025
def stop ( self , timeout_s = None ) : self . stopped . set ( ) if self . thread : self . thread . join ( timeout_s ) return not self . thread . isAlive ( ) else : return True
Stops the interval .
33,026
def join ( self , timeout_s = None ) : if not self . thread : return False self . thread . join ( timeout_s ) return self . running
Joins blocking until the interval ends or until timeout is reached .
33,027
def transform_declare ( node ) : global CURRENT_ROOT if not ( isinstance ( node . func , astroid . Attribute ) and isinstance ( node . func . expr , astroid . Name ) and node . func . expr . name == 'conf' and node . func . attrname == 'declare' ) : return conf_key_name = None if node . args : conf_key_name = node . ar...
Transform conf . declare calls by stashing the declared names .
33,028
def transform_conf_module ( cls ) : global CONF_NODE if cls . name == 'openhtf.conf' : cls . _locals . update ( cls . locals [ 'Configuration' ] [ 0 ] . locals ) CONF_NODE = cls CONF_LOCALS . update ( cls . locals )
Transform usages of the conf module by updating locals .
33,029
def register ( linter ) : MANAGER . register_transform ( astroid . Call , transform_declare ) MANAGER . register_transform ( astroid . Module , transform_conf_module )
Register all transforms with the linter .
33,030
def run ( self ) : if platform . system ( ) == 'Windows' : response = input ( '' . join ( ( self . _message , os . linesep , PROMPT ) ) ) self . _answered = True self . _callback ( response ) return console_output . cli_print ( self . _message , color = self . _color , end = os . linesep , logger = None ) console_outpu...
Main logic for this thread to execute .
33,031
def _asdict ( self ) : with self . _cond : if self . _prompt is None : return return { 'id' : self . _prompt . id , 'message' : self . _prompt . message , 'text-input' : self . _prompt . text_input }
Return a dictionary representation of the current prompt .
33,032
def remove_prompt ( self ) : with self . _cond : self . _prompt = None if self . _console_prompt : self . _console_prompt . Stop ( ) self . _console_prompt = None self . notify_update ( )
Remove the prompt .
33,033
def prompt ( self , message , text_input = False , timeout_s = None , cli_color = '' ) : self . start_prompt ( message , text_input , cli_color ) return self . wait_for_prompt ( timeout_s )
Display a prompt and wait for a response .
33,034
def start_prompt ( self , message , text_input = False , cli_color = '' ) : with self . _cond : if self . _prompt : raise MultiplePromptsError prompt_id = uuid . uuid4 ( ) . hex _LOG . debug ( 'Displaying prompt (%s): "%s"%s' , prompt_id , message , ', Expects text input.' if text_input else '' ) self . _response = Non...
Display a prompt .
33,035
def wait_for_prompt ( self , timeout_s = None ) : with self . _cond : if self . _prompt : if timeout_s is None : self . _cond . wait ( 3600 * 24 * 365 ) else : self . _cond . wait ( timeout_s ) if self . _response is None : raise PromptUnansweredError return self . _response
Wait for the user to respond to the current prompt .
33,036
def respond ( self , prompt_id , response ) : _LOG . debug ( 'Responding to prompt (%s): "%s"' , prompt_id , response ) with self . _cond : if not ( self . _prompt and self . _prompt . id == prompt_id ) : return False self . _response = response self . last_response = ( prompt_id , response ) self . remove_prompt ( ) s...
Respond to the prompt with the given ID .
33,037
def is_terminal ( self ) : return ( self . raised_exception or self . is_timeout or self . phase_result == openhtf . PhaseResult . STOP )
True if this result will stop the test .
33,038
def _thread_proc ( self ) : phase_return = self . _phase_desc ( self . _test_state ) if phase_return is None : phase_return = openhtf . PhaseResult . CONTINUE self . _phase_execution_outcome = PhaseExecutionOutcome ( phase_return )
Execute the encompassed phase and save the result .
33,039
def join_or_die ( self ) : if self . _phase_desc . options . timeout_s is not None : self . join ( self . _phase_desc . options . timeout_s ) else : self . join ( DEFAULT_PHASE_TIMEOUT_S ) if isinstance ( self . _phase_execution_outcome , PhaseExecutionOutcome ) : return self . _phase_execution_outcome if self . is_ali...
Wait for thread to finish returning a PhaseExecutionOutcome instance .
33,040
def execute_phase ( self , phase ) : repeat_count = 1 repeat_limit = phase . options . repeat_limit or sys . maxsize while not self . _stopping . is_set ( ) : is_last_repeat = repeat_count >= repeat_limit phase_execution_outcome = self . _execute_phase_once ( phase , is_last_repeat ) if phase_execution_outcome . is_rep...
Executes a phase or skips it yielding PhaseExecutionOutcome instances .
33,041
def _execute_phase_once ( self , phase_desc , is_last_repeat ) : if phase_desc . options . run_if and not phase_desc . options . run_if ( ) : _LOG . debug ( 'Phase %s skipped due to run_if returning falsey.' , phase_desc . name ) return PhaseExecutionOutcome ( openhtf . PhaseResult . SKIP ) override_result = None with ...
Executes the given phase returning a PhaseExecutionOutcome .
33,042
def stop ( self , timeout_s = None ) : self . _stopping . set ( ) with self . _current_phase_thread_lock : phase_thread = self . _current_phase_thread if not phase_thread : return if phase_thread . is_alive ( ) : phase_thread . kill ( ) _LOG . debug ( 'Waiting for cancelled phase to exit: %s' , phase_thread ) timeout =...
Stops execution of the current phase if any .
33,043
def load_code_info ( phases_or_groups ) : if isinstance ( phases_or_groups , PhaseGroup ) : return phases_or_groups . load_code_info ( ) ret = [ ] for phase in phases_or_groups : if isinstance ( phase , PhaseGroup ) : ret . append ( phase . load_code_info ( ) ) else : ret . append ( mutablerecords . CopyRecord ( phase ...
Recursively load code info for a PhaseGroup or list of phases or groups .
33,044
def flatten_phases_and_groups ( phases_or_groups ) : if isinstance ( phases_or_groups , PhaseGroup ) : phases_or_groups = [ phases_or_groups ] ret = [ ] for phase in phases_or_groups : if isinstance ( phase , PhaseGroup ) : ret . append ( phase . flatten ( ) ) elif isinstance ( phase , collections . Iterable ) : ret . ...
Recursively flatten nested lists for the list of phases or groups .
33,045
def optionally_with_args ( phase , ** kwargs ) : if isinstance ( phase , PhaseGroup ) : return phase . with_args ( ** kwargs ) if isinstance ( phase , collections . Iterable ) : return [ optionally_with_args ( p , ** kwargs ) for p in phase ] if not isinstance ( phase , phase_descriptor . PhaseDescriptor ) : phase = ph...
Apply only the args that the phase knows .
33,046
def optionally_with_plugs ( phase , ** subplugs ) : if isinstance ( phase , PhaseGroup ) : return phase . with_plugs ( ** subplugs ) if isinstance ( phase , collections . Iterable ) : return [ optionally_with_plugs ( p , ** subplugs ) for p in phase ] if not isinstance ( phase , phase_descriptor . PhaseDescriptor ) : p...
Apply only the with_plugs that the phase knows .
33,047
def convert_if_not ( cls , phases_or_groups ) : if isinstance ( phases_or_groups , PhaseGroup ) : return mutablerecords . CopyRecord ( phases_or_groups ) flattened = flatten_phases_and_groups ( phases_or_groups ) return cls ( main = flattened )
Convert list of phases or groups into a new PhaseGroup if not already .
33,048
def with_context ( cls , setup_phases , teardown_phases ) : setup = flatten_phases_and_groups ( setup_phases ) teardown = flatten_phases_and_groups ( teardown_phases ) def _context_wrapper ( * phases ) : return cls ( setup = setup , main = flatten_phases_and_groups ( phases ) , teardown = teardown ) return _context_wra...
Create PhaseGroup creator function with setup and teardown phases .
33,049
def combine ( self , other , name = None ) : return PhaseGroup ( setup = self . setup + other . setup , main = self . main + other . main , teardown = self . teardown + other . teardown , name = name )
Combine with another PhaseGroup and return the result .
33,050
def wrap ( self , main_phases , name = None ) : new_main = list ( self . main ) if isinstance ( main_phases , collections . Iterable ) : new_main . extend ( main_phases ) else : new_main . append ( main_phases ) return PhaseGroup ( setup = self . setup , main = new_main , teardown = self . teardown , name = name )
Returns PhaseGroup with additional main phases .
33,051
def flatten ( self ) : return PhaseGroup ( setup = flatten_phases_and_groups ( self . setup ) , main = flatten_phases_and_groups ( self . main ) , teardown = flatten_phases_and_groups ( self . teardown ) , name = self . name )
Internally flatten out nested iterables .
33,052
def load_code_info ( self ) : return PhaseGroup ( setup = load_code_info ( self . setup ) , main = load_code_info ( self . main ) , teardown = load_code_info ( self . teardown ) , name = self . name )
Load coded info for all contained phases .
33,053
def publish ( cls , message , client_filter = None ) : with cls . _lock : for client in cls . subscribers : if ( not client_filter ) or client_filter ( client ) : client . send ( message )
Publish messages to subscribers .
33,054
def run ( self ) : self . count += 1 print ( 'FailTwicePlug: Run number %s' % ( self . count ) ) if self . count < 3 : raise RuntimeError ( 'Fails a couple times' ) return True
Increments counter and raises an exception for first two runs .
33,055
def format_strings ( self , ** kwargs ) : return mutablerecords . CopyRecord ( self , name = util . format_string ( self . name , kwargs ) )
String substitution of name .
33,056
def wrap_or_copy ( cls , func , ** options ) : if isinstance ( func , openhtf . PhaseGroup ) : raise PhaseWrapError ( 'Cannot wrap PhaseGroup <%s> as a phase.' % ( func . name or 'Unnamed' ) ) if isinstance ( func , cls ) : retval = mutablerecords . CopyRecord ( func ) else : retval = cls ( func ) retval . options . up...
Return a new PhaseDescriptor from the given function or instance .
33,057
def with_known_args ( self , ** kwargs ) : argspec = inspect . getargspec ( self . func ) stored = { } for key , arg in six . iteritems ( kwargs ) : if key in argspec . args or argspec . keywords : stored [ key ] = arg if stored : return self . with_args ( ** stored ) return self
Send only known keyword - arguments to the phase when called .
33,058
def with_args ( self , ** kwargs ) : new_info = mutablerecords . CopyRecord ( self ) new_info . options = new_info . options . format_strings ( ** kwargs ) new_info . extra_kwargs . update ( kwargs ) new_info . measurements = [ m . with_args ( ** kwargs ) for m in self . measurements ] return new_info
Send these keyword - arguments to the phase when called .
33,059
def _apply_with_plugs ( self , subplugs , error_on_unknown ) : plugs_by_name = { plug . name : plug for plug in self . plugs } new_plugs = dict ( plugs_by_name ) for name , sub_class in six . iteritems ( subplugs ) : original_plug = plugs_by_name . get ( name ) accept_substitute = True if original_plug is None : if not...
Substitute plugs for placeholders for this phase .
33,060
def requires_open_handle ( method ) : @ functools . wraps ( method ) def wrapper_requiring_open_handle ( self , * args , ** kwargs ) : if self . is_closed ( ) : raise usb_exceptions . HandleClosedError ( ) return method ( self , * args , ** kwargs ) return wrapper_requiring_open_handle
Decorator to ensure a handle is open for certain methods .
33,061
def _dotify ( cls , data ) : return '' . join ( char if char in cls . PRINTABLE_DATA else '.' for char in data )
Add dots .
33,062
def write ( self , data , dummy = None ) : assert not self . closed if self . expected_write_data is None : return expected_data = self . expected_write_data . pop ( 0 ) if expected_data != data : raise ValueError ( 'Expected %s, got %s (%s)' % ( self . _dotify ( expected_data ) , binascii . hexlify ( data ) , self . _...
Stub Write method .
33,063
def read ( self , length , dummy = None ) : assert not self . closed data = self . expected_read_data . pop ( 0 ) if length < len ( data ) : raise ValueError ( 'Overflow packet length. Read %d bytes, got %d bytes: %s' , length , len ( data ) , self . _dotify ( data ) ) return data
Stub Read method .
33,064
def get_usb_serial ( self , port_num ) : port = self . port_map [ str ( port_num ) ] arg = '' . join ( [ 'DEVICE INFO,' , self . _addr , '.' , port ] ) cmd = ( [ 'esuit64' , '-t' , arg ] ) info = subprocess . check_output ( cmd , stderr = subprocess . STDOUT ) serial = None if "SERIAL" in info : serial_info = info . sp...
Get the device serial number
33,065
def open_usb_handle ( self , port_num ) : serial = self . get_usb_serial ( port_num ) return local_usb . LibUsbHandle . open ( serial_number = serial )
open usb port
33,066
def _printed_len ( some_string ) : return len ( [ x for x in ANSI_ESC_RE . sub ( '' , some_string ) if x in string . printable ] )
Compute the visible length of the string when printed .
33,067
def banner_print ( msg , color = '' , width = 60 , file = sys . stdout , logger = _LOG ) : if logger : logger . debug ( ANSI_ESC_RE . sub ( '' , msg ) ) if CLI_QUIET : return lpad = int ( math . ceil ( ( width - _printed_len ( msg ) - 2 ) / 2.0 ) ) * '=' rpad = int ( math . floor ( ( width - _printed_len ( msg ) - 2 ) ...
Print the message as a banner with a fixed width .
33,068
def bracket_print ( msg , color = '' , width = 8 , file = sys . stdout ) : if CLI_QUIET : return lpad = int ( math . ceil ( ( width - 2 - _printed_len ( msg ) ) / 2.0 ) ) * ' ' rpad = int ( math . floor ( ( width - 2 - _printed_len ( msg ) ) / 2.0 ) ) * ' ' file . write ( '[{lpad}{bright}{color}{msg}{reset}{rpad}]' . f...
Prints the message in brackets in the specified color and end the line .
33,069
def cli_print ( msg , color = '' , end = None , file = sys . stdout , logger = _LOG ) : if logger : logger . debug ( '-> {}' . format ( msg ) ) if CLI_QUIET : return if end is None : end = _linesep_for_file ( file ) file . write ( '{color}{msg}{reset}{end}' . format ( color = color , msg = msg , reset = colorama . Styl...
Print the message to file and also log it .
33,070
def error_print ( msg , color = colorama . Fore . RED , file = sys . stderr ) : if CLI_QUIET : return file . write ( '{sep}{bright}{color}Error: {normal}{msg}{sep}{reset}' . format ( sep = _linesep_for_file ( file ) , bright = colorama . Style . BRIGHT , color = color , normal = colorama . Style . NORMAL , msg = msg , ...
Print the error message to the file in the specified color .
33,071
def action_result_context ( action_text , width = 60 , status_width = 8 , succeed_text = 'OK' , fail_text = 'FAIL' , unknown_text = '????' , file = sys . stdout , logger = _LOG ) : if logger : logger . debug ( 'Action - %s' , action_text ) if not CLI_QUIET : file . write ( '' . join ( ( action_text , '\r' ) ) ) file . ...
A contextmanager that prints actions and results to the CLI .
33,072
def reraise ( exc_type , message = None , * args , ** kwargs ) : last_lineno = inspect . currentframe ( ) . f_back . f_lineno line_msg = 'line %s: ' % last_lineno if message : line_msg += str ( message ) raise exc_type ( line_msg , * args , ** kwargs ) . raise_with_traceback ( sys . exc_info ( ) [ 2 ] )
reraises an exception for exception translation .
33,073
def plot1D_mat ( a , b , M , title = '' ) : na , nb = M . shape gs = gridspec . GridSpec ( 3 , 3 ) xa = np . arange ( na ) xb = np . arange ( nb ) ax1 = pl . subplot ( gs [ 0 , 1 : ] ) pl . plot ( xb , b , 'r' , label = 'Target distribution' ) pl . yticks ( ( ) ) pl . title ( title ) ax2 = pl . subplot ( gs [ 1 : , 0 ]...
Plot matrix M with the source and target 1D distribution
33,074
def plot2D_samples_mat ( xs , xt , G , thr = 1e-8 , ** kwargs ) : if ( 'color' not in kwargs ) and ( 'c' not in kwargs ) : kwargs [ 'color' ] = 'k' mx = G . max ( ) for i in range ( xs . shape [ 0 ] ) : for j in range ( xt . shape [ 0 ] ) : if G [ i , j ] / mx > thr : pl . plot ( [ xs [ i , 0 ] , xt [ j , 0 ] ] , [ xs ...
Plot matrix M in 2D with lines using alpha values
33,075
def sinkhorn_lpl1_mm ( a , labels_a , b , M , reg , eta = 0.1 , numItermax = 10 , numInnerItermax = 200 , stopInnerThr = 1e-9 , verbose = False , log = False , to_numpy = True ) : a , labels_a , b , M = utils . to_gpu ( a , labels_a , b , M ) p = 0.5 epsilon = 1e-3 indices_labels = [ ] labels_a2 = cp . asnumpy ( labels...
Solve the entropic regularization optimal transport problem with nonconvex group lasso regularization on GPU
33,076
def get_2D_samples_gauss ( n , m , sigma , random_state = None ) : return make_2D_samples_gauss ( n , m , sigma , random_state = None )
Deprecated see make_2D_samples_gauss
33,077
def get_data_classif ( dataset , n , nz = .5 , theta = 0 , random_state = None , ** kwargs ) : return make_data_classif ( dataset , n , nz = .5 , theta = 0 , random_state = None , ** kwargs )
Deprecated see make_data_classif
33,078
def sinkhorn ( a , b , M , reg , method = 'sinkhorn' , numItermax = 1000 , stopThr = 1e-9 , verbose = False , log = False , ** kwargs ) : u if method . lower ( ) == 'sinkhorn' : def sink ( ) : return sinkhorn_knopp ( a , b , M , reg , numItermax = numItermax , stopThr = stopThr , verbose = verbose , log = log , ** kwar...
u Solve the entropic regularization optimal transport problem and return the OT matrix
33,079
def sinkhorn2 ( a , b , M , reg , method = 'sinkhorn' , numItermax = 1000 , stopThr = 1e-9 , verbose = False , log = False , ** kwargs ) : u if method . lower ( ) == 'sinkhorn' : def sink ( ) : return sinkhorn_knopp ( a , b , M , reg , numItermax = numItermax , stopThr = stopThr , verbose = verbose , log = log , ** kwa...
u Solve the entropic regularization optimal transport problem and return the loss
33,080
def geometricBar ( weights , alldistribT ) : assert ( len ( weights ) == alldistribT . shape [ 1 ] ) return np . exp ( np . dot ( np . log ( alldistribT ) , weights . T ) )
return the weighted geometric mean of distributions
33,081
def geometricMean ( alldistribT ) : return np . exp ( np . mean ( np . log ( alldistribT ) , axis = 1 ) )
return the geometric mean of distributions
33,082
def projR ( gamma , p ) : return np . multiply ( gamma . T , p / np . maximum ( np . sum ( gamma , axis = 1 ) , 1e-10 ) ) . T
return the KL projection on the row constrints
33,083
def projC ( gamma , q ) : return np . multiply ( gamma , q / np . maximum ( np . sum ( gamma , axis = 0 ) , 1e-10 ) )
return the KL projection on the column constrints
33,084
def barycenter ( A , M , reg , weights = None , numItermax = 1000 , stopThr = 1e-4 , verbose = False , log = False ) : if weights is None : weights = np . ones ( A . shape [ 1 ] ) / A . shape [ 1 ] else : assert ( len ( weights ) == A . shape [ 1 ] ) if log : log = { 'err' : [ ] } K = np . exp ( - M / reg ) cpt = 0 err...
Compute the entropic regularized wasserstein barycenter of distributions A
33,085
def convolutional_barycenter2d ( A , reg , weights = None , numItermax = 10000 , stopThr = 1e-9 , stabThr = 1e-30 , verbose = False , log = False ) : if weights is None : weights = np . ones ( A . shape [ 0 ] ) / A . shape [ 0 ] else : assert ( len ( weights ) == A . shape [ 0 ] ) if log : log = { 'err' : [ ] } b = np ...
Compute the entropic regularized wasserstein barycenter of distributions A where A is a collection of 2D images .
33,086
def unmix ( a , D , M , M0 , h0 , reg , reg0 , alpha , numItermax = 1000 , stopThr = 1e-3 , verbose = False , log = False ) : K = np . exp ( - M / reg ) K0 = np . exp ( - M0 / reg0 ) old = h0 err = 1 cpt = 0 if log : log = { 'err' : [ ] } while ( err > stopThr and cpt < numItermax ) : K = projC ( K , a ) K0 = projC ( K...
Compute the unmixing of an observation with a given dictionary using Wasserstein distance
33,087
def empirical_sinkhorn ( X_s , X_t , reg , a = None , b = None , metric = 'sqeuclidean' , numIterMax = 10000 , stopThr = 1e-9 , verbose = False , log = False , ** kwargs ) : if a is None : a = unif ( np . shape ( X_s ) [ 0 ] ) if b is None : b = unif ( np . shape ( X_t ) [ 0 ] ) M = dist ( X_s , X_t , metric = metric )...
Solve the entropic regularization optimal transport problem and return the OT matrix from empirical data
33,088
def empirical_sinkhorn2 ( X_s , X_t , reg , a = None , b = None , metric = 'sqeuclidean' , numIterMax = 10000 , stopThr = 1e-9 , verbose = False , log = False , ** kwargs ) : if a is None : a = unif ( np . shape ( X_s ) [ 0 ] ) if b is None : b = unif ( np . shape ( X_t ) [ 0 ] ) M = dist ( X_s , X_t , metric = metric ...
Solve the entropic regularization optimal transport problem from empirical data and return the OT loss
33,089
def empirical_sinkhorn_divergence ( X_s , X_t , reg , a = None , b = None , metric = 'sqeuclidean' , numIterMax = 10000 , stopThr = 1e-9 , verbose = False , log = False , ** kwargs ) : if log : sinkhorn_loss_ab , log_ab = empirical_sinkhorn2 ( X_s , X_t , reg , a , b , metric = metric , numIterMax = numIterMax , stopTh...
Compute the sinkhorn divergence loss from empirical data
33,090
def emd ( a , b , M , numItermax = 100000 , log = False ) : a = np . asarray ( a , dtype = np . float64 ) b = np . asarray ( b , dtype = np . float64 ) M = np . asarray ( M , dtype = np . float64 ) if len ( a ) == 0 : a = np . ones ( ( M . shape [ 0 ] , ) , dtype = np . float64 ) / M . shape [ 0 ] if len ( b ) == 0 : b...
Solves the Earth Movers distance problem and returns the OT matrix
33,091
def emd2 ( a , b , M , processes = multiprocessing . cpu_count ( ) , numItermax = 100000 , log = False , return_matrix = False ) : a = np . asarray ( a , dtype = np . float64 ) b = np . asarray ( b , dtype = np . float64 ) M = np . asarray ( M , dtype = np . float64 ) if len ( a ) == 0 : a = np . ones ( ( M . shape [ 0...
Solves the Earth Movers distance problem and returns the loss
33,092
def sinkhorn_l1l2_gl ( a , labels_a , b , M , reg , eta = 0.1 , numItermax = 10 , numInnerItermax = 200 , stopInnerThr = 1e-9 , verbose = False , log = False ) : lstlab = np . unique ( labels_a ) def f ( G ) : res = 0 for i in range ( G . shape [ 1 ] ) : for lab in lstlab : temp = G [ labels_a == lab , i ] res += np . ...
Solve the entropic regularization optimal transport problem with group lasso regularization
33,093
def OT_mapping_linear ( xs , xt , reg = 1e-6 , ws = None , wt = None , bias = True , log = False ) : d = xs . shape [ 1 ] if bias : mxs = xs . mean ( 0 , keepdims = True ) mxt = xt . mean ( 0 , keepdims = True ) xs = xs - mxs xt = xt - mxt else : mxs = np . zeros ( ( 1 , d ) ) mxt = np . zeros ( ( 1 , d ) ) if ws is No...
return OT linear operator between samples
33,094
def euclidean_distances ( a , b , squared = False , to_numpy = True ) : a , b = to_gpu ( a , b ) a2 = np . sum ( np . square ( a ) , 1 ) b2 = np . sum ( np . square ( b ) , 1 ) c = - 2 * np . dot ( a , b . T ) c += a2 [ : , None ] c += b2 [ None , : ] if not squared : np . sqrt ( c , out = c ) if to_numpy : return to_n...
Compute the pairwise euclidean distance between matrices a and b .
33,095
def dist ( x1 , x2 = None , metric = 'sqeuclidean' , to_numpy = True ) : if x2 is None : x2 = x1 if metric == "sqeuclidean" : return euclidean_distances ( x1 , x2 , squared = True , to_numpy = to_numpy ) elif metric == "euclidean" : return euclidean_distances ( x1 , x2 , squared = False , to_numpy = to_numpy ) else : r...
Compute distance between samples in x1 and x2 on gpu
33,096
def to_gpu ( * args ) : if len ( args ) > 1 : return ( cp . asarray ( x ) for x in args ) else : return cp . asarray ( args [ 0 ] )
Upload numpy arrays to GPU and return them
33,097
def to_np ( * args ) : if len ( args ) > 1 : return ( cp . asnumpy ( x ) for x in args ) else : return cp . asnumpy ( args [ 0 ] )
convert GPU arras to numpy and return them
33,098
def scipy_sparse_to_spmatrix ( A ) : coo = A . tocoo ( ) SP = spmatrix ( coo . data . tolist ( ) , coo . row . tolist ( ) , coo . col . tolist ( ) , size = A . shape ) return SP
Efficient conversion from scipy sparse matrix to cvxopt sparse matrix
33,099
def line_search_armijo ( f , xk , pk , gfk , old_fval , args = ( ) , c1 = 1e-4 , alpha0 = 0.99 ) : xk = np . atleast_1d ( xk ) fc = [ 0 ] def phi ( alpha1 ) : fc [ 0 ] += 1 return f ( xk + alpha1 * pk , * args ) if old_fval is None : phi0 = phi ( 0. ) else : phi0 = old_fval derphi0 = np . sum ( pk * gfk ) alpha , phi1 ...
Armijo linesearch function that works with matrices