idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
56,100
def quasi_newton_uniform_blocks ( points , cells , * args , ** kwargs ) : def get_new_points ( mesh ) : x = mesh . node_coords . copy ( ) x += update ( mesh ) x [ ghosted_mesh . is_ghost_point ] = ghosted_mesh . reflect_ghost ( x [ ghosted_mesh . mirrors ] ) return x ghosted_mesh = GhostedMesh ( points , cells ) runner ( get_new_points , ghosted_mesh , * args , ** kwargs , update_topology = lambda mesh : ghosted_mesh . update_topology ( ) , ) mesh = ghosted_mesh . get_unghosted_mesh ( ) return mesh . node_coords , mesh . cells [ "nodes" ]
Lloyd s algorithm can be though of a diagonal - only Hessian ; this method incorporates the diagonal blocks too .
56,101
def new ( filename : str , * , file_attrs : Optional [ Dict [ str , str ] ] = None ) -> LoomConnection : if filename . startswith ( "~/" ) : filename = os . path . expanduser ( filename ) if file_attrs is None : file_attrs = { } f = h5py . File ( name = filename , mode = 'w' ) f . create_group ( '/layers' ) f . create_group ( '/row_attrs' ) f . create_group ( '/col_attrs' ) f . create_group ( '/row_graphs' ) f . create_group ( '/col_graphs' ) f . flush ( ) f . close ( ) ds = connect ( filename , validate = False ) for vals in file_attrs : ds . attrs [ vals ] = file_attrs [ vals ] currentTime = time . localtime ( time . time ( ) ) ds . attrs [ 'CreationDate' ] = timestamp ( ) ds . attrs [ "LOOM_SPEC_VERSION" ] = loompy . loom_spec_version return ds
Create an empty Loom file and return it as a context manager .
56,102
def create ( filename : str , layers : Union [ np . ndarray , Dict [ str , np . ndarray ] , loompy . LayerManager ] , row_attrs : Union [ loompy . AttributeManager , Dict [ str , np . ndarray ] ] , col_attrs : Union [ loompy . AttributeManager , Dict [ str , np . ndarray ] ] , * , file_attrs : Dict [ str , str ] = None ) -> None : if isinstance ( row_attrs , loompy . AttributeManager ) : row_attrs = { k : v [ : ] for k , v in row_attrs . items ( ) } if isinstance ( col_attrs , loompy . AttributeManager ) : col_attrs = { k : v [ : ] for k , v in col_attrs . items ( ) } if isinstance ( layers , np . ndarray ) or scipy . sparse . issparse ( layers ) : layers = { "" : layers } elif isinstance ( layers , loompy . LayerManager ) : layers = { k : v [ : , : ] for k , v in layers . items ( ) } if "" not in layers : raise ValueError ( "Data for default layer must be provided" ) shape = layers [ "" ] . shape if shape [ 0 ] == 0 or shape [ 1 ] == 0 : raise ValueError ( "Main matrix cannot be empty" ) for name , layer in layers . items ( ) : if layer . shape != shape : raise ValueError ( f"Layer '{name}' is not the same shape as the main matrix" ) for name , ra in row_attrs . items ( ) : if ra . shape [ 0 ] != shape [ 0 ] : raise ValueError ( f"Row attribute '{name}' is not the same length ({ra.shape[0]}) as number of rows in main matrix ({shape[0]})" ) for name , ca in col_attrs . items ( ) : if ca . shape [ 0 ] != shape [ 1 ] : raise ValueError ( f"Column attribute '{name}' is not the same length ({ca.shape[0]}) as number of columns in main matrix ({shape[1]})" ) try : with new ( filename , file_attrs = file_attrs ) as ds : for key , vals in layers . items ( ) : ds . layer [ key ] = vals for key , vals in row_attrs . items ( ) : ds . ra [ key ] = vals for key , vals in col_attrs . items ( ) : ds . ca [ key ] = vals except ValueError as ve : if os . path . exists ( filename ) : os . remove ( filename ) raise ve
Create a new Loom file from the given data .
56,103
def connect ( filename : str , mode : str = 'r+' , * , validate : bool = True , spec_version : str = "2.0.1" ) -> LoomConnection : return LoomConnection ( filename , mode , validate = validate , spec_version = spec_version )
Establish a connection to a . loom file .
56,104
def last_modified ( self ) -> str : if "last_modified" in self . attrs : return self . attrs [ "last_modified" ] elif self . mode == "r+" : self . attrs [ "last_modified" ] = timestamp ( ) return self . attrs [ "last_modified" ] return timestamp ( )
Return an ISO8601 timestamp indicating when the file was last modified
56,105
def get_changes_since ( self , timestamp : str ) -> Dict [ str , List ] : rg = [ ] cg = [ ] ra = [ ] ca = [ ] layers = [ ] if self . last_modified ( ) > timestamp : if self . row_graphs . last_modified ( ) > timestamp : for name in self . row_graphs . keys ( ) : if self . row_graphs . last_modified ( name ) > timestamp : rg . append ( name ) if self . col_graphs . last_modified ( ) > timestamp : for name in self . col_graphs . keys ( ) : if self . col_graphs . last_modified ( name ) > timestamp : cg . append ( name ) if self . ra . last_modified ( ) > timestamp : for name in self . ra . keys ( ) : if self . ra . last_modified ( name ) > timestamp : ra . append ( name ) if self . ca . last_modified ( ) > timestamp : for name in self . ca . keys ( ) : if self . ca . last_modified ( name ) > timestamp : ca . append ( name ) if self . layers . last_modified ( ) > timestamp : for name in self . layers . keys ( ) : if self . layers . last_modified ( name ) > timestamp : layers . append ( name ) return { "row_graphs" : rg , "col_graphs" : cg , "row_attrs" : ra , "col_attrs" : ca , "layers" : layers }
Get a summary of the parts of the file that changed since the given time
56,106
def sparse ( self , rows : np . ndarray = None , cols : np . ndarray = None , layer : str = None ) -> scipy . sparse . coo_matrix : if layer is None : return self . layers [ "" ] . sparse ( rows = rows , cols = cols ) else : return self . layers [ layer ] . sparse ( rows = rows , cols = cols )
Return the main matrix or specified layer as a scipy . sparse . coo_matrix without loading dense matrix in RAM
56,107
def close ( self , suppress_warning : bool = False ) -> None : if self . _file is None : if not suppress_warning : logging . warn ( "Connection to %s is already closed" , self . filename ) else : self . _file . close ( ) self . _file = None self . layers = None self . ra = None self . row_attrs = None self . ca = None self . col_attrs = None self . row_graphs = None self . col_graphs = None self . shape = ( 0 , 0 ) self . _closed = True
Close the connection . After this the connection object becomes invalid . Warns user if called after closing .
56,108
def permute ( self , ordering : np . ndarray , axis : int ) -> None : if self . _file . __contains__ ( "tiles" ) : del self . _file [ 'tiles' ] ordering = list ( np . array ( ordering ) . flatten ( ) ) self . layers . _permute ( ordering , axis = axis ) if axis == 0 : self . row_attrs . _permute ( ordering ) self . row_graphs . _permute ( ordering ) if axis == 1 : self . col_attrs . _permute ( ordering ) self . col_graphs . _permute ( ordering )
Permute the dataset along the indicated axis .
56,109
def aggregate ( self , out_file : str = None , select : np . ndarray = None , group_by : Union [ str , np . ndarray ] = "Clusters" , aggr_by : str = "mean" , aggr_ca_by : Dict [ str , str ] = None ) -> np . ndarray : ca = { } if select is not None : raise ValueError ( "The 'select' argument is deprecated" ) if isinstance ( group_by , np . ndarray ) : labels = group_by else : labels = ( self . ca [ group_by ] ) . astype ( 'int' ) _ , zero_strt_sort_noholes_lbls = np . unique ( labels , return_inverse = True ) n_groups = len ( set ( labels ) ) if aggr_ca_by is not None : for key in self . ca . keys ( ) : if key not in aggr_ca_by : continue func = aggr_ca_by [ key ] if func == "tally" : for val in set ( self . ca [ key ] ) : if np . issubdtype ( type ( val ) , np . str_ ) : valnew = val . replace ( "/" , "-" ) valnew = valnew . replace ( "." , "_" ) ca [ key + "_" + str ( valnew ) ] = npg . aggregate ( zero_strt_sort_noholes_lbls , ( self . ca [ key ] == val ) . astype ( 'int' ) , func = "sum" , fill_value = 0 ) elif func == "mode" : def mode ( x ) : return scipy . stats . mode ( x ) [ 0 ] [ 0 ] ca [ key ] = npg . aggregate ( zero_strt_sort_noholes_lbls , self . ca [ key ] , func = mode , fill_value = 0 ) . astype ( 'str' ) elif func == "mean" : ca [ key ] = npg . aggregate ( zero_strt_sort_noholes_lbls , self . ca [ key ] , func = func , fill_value = 0 ) elif func == "first" : ca [ key ] = npg . aggregate ( zero_strt_sort_noholes_lbls , self . ca [ key ] , func = func , fill_value = self . ca [ key ] [ 0 ] ) m = np . empty ( ( self . shape [ 0 ] , n_groups ) ) for ( _ , selection , view ) in self . scan ( axis = 0 , layers = [ "" ] ) : vals_aggr = npg . aggregate ( zero_strt_sort_noholes_lbls , view [ : , : ] , func = aggr_by , axis = 1 , fill_value = 0 ) m [ selection , : ] = vals_aggr if out_file is not None : loompy . create ( out_file , m , self . ra , ca ) return m
Aggregate the Loom file by applying aggregation functions to the main matrix as well as to the column attributes
56,110
def get ( self , name : str , default : Any = None ) -> np . ndarray : if name in self : return self [ name ] else : return default
Return the value for a named attribute if it exists else default . If default is not given it defaults to None so that this method never raises a KeyError .
56,111
def cat_colors ( N : int = 1 , * , hue : str = None , luminosity : str = None , bgvalue : int = None , loop : bool = False , seed : str = "cat" ) -> Union [ List [ Any ] , colors . LinearSegmentedColormap ] : c : List [ str ] = [ ] if N <= 25 and hue is None and luminosity is None : c = _color_alphabet [ : N ] elif not loop : c = RandomColor ( seed = seed ) . generate ( count = N , hue = hue , luminosity = luminosity , format_ = "hex" ) else : n = N while n > 0 : c += _color_alphabet [ : n ] n -= 25 if bgvalue is not None : c [ bgvalue ] = "#aaaaaa" return colors . LinearSegmentedColormap . from_list ( "" , c , N )
Return a colormap suitable for N categorical values optimized to be both aesthetically pleasing and perceptually distinct .
56,112
def _renumber ( a : np . ndarray , keys : np . ndarray , values : np . ndarray ) -> np . ndarray : ordering = np . argsort ( keys ) keys = keys [ ordering ] values = keys [ ordering ] index = np . digitize ( a . ravel ( ) , keys , right = True ) return ( values [ index ] . reshape ( a . shape ) )
Renumber a by replacing any occurrence of keys by the corresponding values
56,113
def validate ( self , path : str , strictness : str = "speconly" ) -> bool : valid1 = True with h5py . File ( path , mode = "r" ) as f : valid1 = self . validate_spec ( f ) if not valid1 : self . errors . append ( "For help, see http://linnarssonlab.org/loompy/format/" ) valid2 = True if strictness == "conventions" : with loompy . connect ( path , mode = "r" ) as ds : valid2 = self . validate_conventions ( ds ) if not valid2 : self . errors . append ( "For help, see http://linnarssonlab.org/loompy/conventions/" ) return valid1 and valid2
Validate a file for conformance to the Loom specification
56,114
def _permute ( self , ordering : np . ndarray ) -> None : for key in self . keys ( ) : self [ key ] = self [ key ] [ ordering ]
Permute all the attributes in the collection
56,115
def get ( self , name : str , default : np . ndarray ) -> np . ndarray : if name in self : return self [ name ] else : if not isinstance ( default , np . ndarray ) : raise ValueError ( f"Default must be an np.ndarray with exactly {self.ds.shape[self.axis]} values" ) if default . shape [ 0 ] != self . ds . shape [ self . axis ] : raise ValueError ( f"Default must be an np.ndarray with exactly {self.ds.shape[self.axis]} values but {len(default)} were given" ) return default
Return the value for a named attribute if it exists else default . Default has to be a numpy array of correct size .
56,116
def normalize_attr_array ( a : Any ) -> np . ndarray : if type ( a ) is np . ndarray : return a elif type ( a ) is np . matrix : if a . shape [ 0 ] == 1 : return np . array ( a ) [ 0 , : ] elif a . shape [ 1 ] == 1 : return np . array ( a ) [ : , 0 ] else : raise ValueError ( "Attribute values must be 1-dimensional." ) elif type ( a ) is list or type ( a ) is tuple : return np . array ( a ) elif sparse . issparse ( a ) : return normalize_attr_array ( a . todense ( ) ) else : raise ValueError ( "Argument must be a list, tuple, numpy matrix, numpy ndarray or sparse matrix." )
Take all kinds of array - like inputs and normalize to a one - dimensional np . ndarray
56,117
def to_html ( ds : Any ) -> str : rm = min ( 10 , ds . shape [ 0 ] ) cm = min ( 10 , ds . shape [ 1 ] ) html = "<p>" if ds . attrs . __contains__ ( "title" ) : html += "<strong>" + ds . attrs [ "title" ] + "</strong> " html += f"{ds.shape[0]} rows, {ds.shape[1]} columns, {len(ds.layers)} layer{'s' if len(ds.layers) > 1 else ''}<br/>(showing up to 10x10)<br/>" html += ds . filename + "<br/>" for ( name , val ) in ds . attrs . items ( ) : html += f"name: <em>{val}</em><br/>" html += "<table>" for ca in ds . col_attrs . keys ( ) : html += "<tr>" for ra in ds . row_attrs . keys ( ) : html += "<td>&nbsp;</td>" html += "<td><strong>" + ca + "</strong></td>" for v in ds . col_attrs [ ca ] [ : cm ] : html += "<td>" + str ( v ) + "</td>" if ds . shape [ 1 ] > cm : html += "<td>...</td>" html += "</tr>" html += "<tr>" for ra in ds . row_attrs . keys ( ) : html += "<td><strong>" + ra + "</strong></td>" html += "<td>&nbsp;</td>" for v in range ( cm ) : html += "<td>&nbsp;</td>" if ds . shape [ 1 ] > cm : html += "<td>...</td>" html += "</tr>" for row in range ( rm ) : html += "<tr>" for ra in ds . row_attrs . keys ( ) : html += "<td>" + str ( ds . row_attrs [ ra ] [ row ] ) + "</td>" html += "<td>&nbsp;</td>" for v in ds [ row , : cm ] : html += "<td>" + str ( v ) + "</td>" if ds . shape [ 1 ] > cm : html += "<td>...</td>" html += "</tr>" if ds . shape [ 0 ] > rm : html += "<tr>" for v in range ( rm + 1 + len ( ds . row_attrs . keys ( ) ) ) : html += "<td>...</td>" if ds . shape [ 1 ] > cm : html += "<td>...</td>" html += "</tr>" html += "</table>" return html
Return an HTML representation of the loom file or view showing the upper - left 10x10 corner .
56,118
def permute ( self , ordering : np . ndarray , * , axis : int ) -> None : if axis not in ( 0 , 1 ) : raise ValueError ( "Axis must be 0 (rows) or 1 (columns)" ) for layer in self . layers . values ( ) : layer . _permute ( ordering , axis = axis ) if axis == 0 : if self . row_graphs is not None : for g in self . row_graphs . values ( ) : g . _permute ( ordering ) for a in self . row_attrs . values ( ) : a . _permute ( ordering ) elif axis == 1 : if self . col_graphs is not None : for g in self . col_graphs . values ( ) : g . _permute ( ordering ) for a in self . col_attrs . values ( ) : a . _permute ( ordering )
Permute the view by permuting its layers attributes and graphs
56,119
def permute ( self , ordering : np . ndarray , * , axis : int ) -> None : if axis == 0 : self . values = self . values [ ordering , : ] elif axis == 1 : self . values = self . values [ : , ordering ] else : raise ValueError ( "axis must be 0 or 1" )
Permute the layer along an axis
56,120
def _resize ( self , size : Tuple [ int , int ] , axis : int = None ) -> None : if self . name == "" : self . ds . _file [ '/matrix' ] . resize ( size , axis ) else : self . ds . _file [ '/layers/' + self . name ] . resize ( size , axis )
Resize the dataset or the specified axis .
56,121
def is_datafile_valid ( datafile ) : try : datafile_json = json . loads ( datafile ) except : return False try : jsonschema . Draft4Validator ( constants . JSON_SCHEMA ) . validate ( datafile_json ) except : return False return True
Given a datafile determine if it is valid or not .
56,122
def is_user_profile_valid ( user_profile ) : if not user_profile : return False if not type ( user_profile ) is dict : return False if UserProfile . USER_ID_KEY not in user_profile : return False if UserProfile . EXPERIMENT_BUCKET_MAP_KEY not in user_profile : return False experiment_bucket_map = user_profile . get ( UserProfile . EXPERIMENT_BUCKET_MAP_KEY ) if not type ( experiment_bucket_map ) is dict : return False for decision in experiment_bucket_map . values ( ) : if type ( decision ) is not dict or UserProfile . VARIATION_ID_KEY not in decision : return False return True
Determine if provided user profile is valid or not .
56,123
def is_attribute_valid ( attribute_key , attribute_value ) : if not isinstance ( attribute_key , string_types ) : return False if isinstance ( attribute_value , ( string_types , bool ) ) : return True if isinstance ( attribute_value , ( numbers . Integral , float ) ) : return is_finite_number ( attribute_value ) return False
Determine if given attribute is valid .
56,124
def is_finite_number ( value ) : if not isinstance ( value , ( numbers . Integral , float ) ) : return False if isinstance ( value , bool ) : return False if isinstance ( value , float ) : if math . isnan ( value ) or math . isinf ( value ) : return False if abs ( value ) > ( 2 ** 53 ) : return False return True
Validates if the given value is a number enforces absolute limit of 2^53 and restricts NAN INF - INF .
56,125
def are_values_same_type ( first_val , second_val ) : first_val_type = type ( first_val ) second_val_type = type ( second_val ) if isinstance ( first_val , string_types ) and isinstance ( second_val , string_types ) : return True if isinstance ( first_val , bool ) or isinstance ( second_val , bool ) : return first_val_type == second_val_type if isinstance ( first_val , ( numbers . Integral , float ) ) and isinstance ( second_val , ( numbers . Integral , float ) ) : return True return False
Method to verify that both values belong to same type . Float and integer are considered as same type .
56,126
def reset_logger ( name , level = None , handler = None ) : if level is None : level = logging . INFO logger = logging . getLogger ( name ) logger . setLevel ( level ) handler = handler or logging . StreamHandler ( ) handler . setFormatter ( logging . Formatter ( _DEFAULT_LOG_FORMAT ) ) logger . handlers = [ handler ] return logger
Make a standard python logger object with default formatter handler etc .
56,127
def adapt_logger ( logger ) : if isinstance ( logger , logging . Logger ) : return logger if isinstance ( logger , ( SimpleLogger , NoOpLogger ) ) : return logger . logger return logger
Adapt our custom logger . BaseLogger object into a standard logging . Logger object .
56,128
def get_variation_for_experiment ( self , experiment_id ) : return self . experiment_bucket_map . get ( experiment_id , { self . VARIATION_ID_KEY : None } ) . get ( self . VARIATION_ID_KEY )
Helper method to retrieve variation ID for given experiment .
56,129
def get_numeric_value ( event_tags , logger = None ) : logger_message_debug = None numeric_metric_value = None if event_tags is None : logger_message_debug = 'Event tags is undefined.' elif not isinstance ( event_tags , dict ) : logger_message_debug = 'Event tags is not a dictionary.' elif NUMERIC_METRIC_TYPE not in event_tags : logger_message_debug = 'The numeric metric key is not in event tags.' else : numeric_metric_value = event_tags [ NUMERIC_METRIC_TYPE ] try : if isinstance ( numeric_metric_value , ( numbers . Integral , float , str ) ) : cast_numeric_metric_value = float ( numeric_metric_value ) if not isinstance ( cast_numeric_metric_value , float ) or math . isnan ( cast_numeric_metric_value ) or math . isinf ( cast_numeric_metric_value ) : logger_message_debug = 'Provided numeric value {} is in an invalid format.' . format ( numeric_metric_value ) numeric_metric_value = None else : if isinstance ( numeric_metric_value , bool ) : logger_message_debug = 'Provided numeric value is a boolean, which is an invalid format.' numeric_metric_value = None else : numeric_metric_value = cast_numeric_metric_value else : logger_message_debug = 'Numeric metric value is not in integer, float, or string form.' numeric_metric_value = None except ValueError : logger_message_debug = 'Value error while casting numeric metric value to a float.' numeric_metric_value = None if logger and logger_message_debug : logger . log ( enums . LogLevels . DEBUG , logger_message_debug ) if numeric_metric_value is not None : if logger : logger . log ( enums . LogLevels . INFO , 'The numeric metric value {} will be sent to results.' . format ( numeric_metric_value ) ) else : if logger : logger . log ( enums . LogLevels . WARNING , 'The provided numeric metric value {} is in an invalid format and will not be sent to results.' . format ( numeric_metric_value ) ) return numeric_metric_value
A smart getter of the numeric value from the event tags .
56,130
def hash ( key , seed = 0x0 ) : key = bytearray ( xencode ( key ) ) def fmix ( h ) : h ^= h >> 16 h = ( h * 0x85ebca6b ) & 0xFFFFFFFF h ^= h >> 13 h = ( h * 0xc2b2ae35 ) & 0xFFFFFFFF h ^= h >> 16 return h length = len ( key ) nblocks = int ( length / 4 ) h1 = seed c1 = 0xcc9e2d51 c2 = 0x1b873593 for block_start in xrange ( 0 , nblocks * 4 , 4 ) : k1 = key [ block_start + 3 ] << 24 | key [ block_start + 2 ] << 16 | key [ block_start + 1 ] << 8 | key [ block_start + 0 ] k1 = ( c1 * k1 ) & 0xFFFFFFFF k1 = ( k1 << 15 | k1 >> 17 ) & 0xFFFFFFFF k1 = ( c2 * k1 ) & 0xFFFFFFFF h1 ^= k1 h1 = ( h1 << 13 | h1 >> 19 ) & 0xFFFFFFFF h1 = ( h1 * 5 + 0xe6546b64 ) & 0xFFFFFFFF tail_index = nblocks * 4 k1 = 0 tail_size = length & 3 if tail_size >= 3 : k1 ^= key [ tail_index + 2 ] << 16 if tail_size >= 2 : k1 ^= key [ tail_index + 1 ] << 8 if tail_size >= 1 : k1 ^= key [ tail_index + 0 ] if tail_size > 0 : k1 = ( k1 * c1 ) & 0xFFFFFFFF k1 = ( k1 << 15 | k1 >> 17 ) & 0xFFFFFFFF k1 = ( k1 * c2 ) & 0xFFFFFFFF h1 ^= k1 unsigned_val = fmix ( h1 ^ length ) if unsigned_val & 0x80000000 == 0 : return unsigned_val else : return - ( ( unsigned_val ^ 0xFFFFFFFF ) + 1 )
Implements 32bit murmur3 hash .
56,131
def hash64 ( key , seed = 0x0 , x64arch = True ) : hash_128 = hash128 ( key , seed , x64arch ) unsigned_val1 = hash_128 & 0xFFFFFFFFFFFFFFFF if unsigned_val1 & 0x8000000000000000 == 0 : signed_val1 = unsigned_val1 else : signed_val1 = - ( ( unsigned_val1 ^ 0xFFFFFFFFFFFFFFFF ) + 1 ) unsigned_val2 = ( hash_128 >> 64 ) & 0xFFFFFFFFFFFFFFFF if unsigned_val2 & 0x8000000000000000 == 0 : signed_val2 = unsigned_val2 else : signed_val2 = - ( ( unsigned_val2 ^ 0xFFFFFFFFFFFFFFFF ) + 1 ) return ( int ( signed_val1 ) , int ( signed_val2 ) )
Implements 64bit murmur3 hash . Returns a tuple .
56,132
def hash_bytes ( key , seed = 0x0 , x64arch = True ) : hash_128 = hash128 ( key , seed , x64arch ) bytestring = '' for i in xrange ( 0 , 16 , 1 ) : lsbyte = hash_128 & 0xFF bytestring = bytestring + str ( chr ( lsbyte ) ) hash_128 = hash_128 >> 8 return bytestring
Implements 128bit murmur3 hash . Returns a byte string .
56,133
def _generate_bucket_value ( self , bucketing_id ) : ratio = float ( self . _generate_unsigned_hash_code_32_bit ( bucketing_id ) ) / MAX_HASH_VALUE return math . floor ( ratio * MAX_TRAFFIC_VALUE )
Helper function to generate bucket value in half - closed interval [ 0 MAX_TRAFFIC_VALUE ) .
56,134
def find_bucket ( self , bucketing_id , parent_id , traffic_allocations ) : bucketing_key = BUCKETING_ID_TEMPLATE . format ( bucketing_id = bucketing_id , parent_id = parent_id ) bucketing_number = self . _generate_bucket_value ( bucketing_key ) self . config . logger . debug ( 'Assigned bucket %s to user with bucketing ID "%s".' % ( bucketing_number , bucketing_id ) ) for traffic_allocation in traffic_allocations : current_end_of_range = traffic_allocation . get ( 'endOfRange' ) if bucketing_number < current_end_of_range : return traffic_allocation . get ( 'entityId' ) return None
Determine entity based on bucket value and traffic allocations .
56,135
def bucket ( self , experiment , user_id , bucketing_id ) : if not experiment : return None if experiment . groupPolicy in GROUP_POLICIES : group = self . config . get_group ( experiment . groupId ) if not group : return None user_experiment_id = self . find_bucket ( bucketing_id , experiment . groupId , group . trafficAllocation ) if not user_experiment_id : self . config . logger . info ( 'User "%s" is in no experiment.' % user_id ) return None if user_experiment_id != experiment . id : self . config . logger . info ( 'User "%s" is not in experiment "%s" of group %s.' % ( user_id , experiment . key , experiment . groupId ) ) return None self . config . logger . info ( 'User "%s" is in experiment %s of group %s.' % ( user_id , experiment . key , experiment . groupId ) ) variation_id = self . find_bucket ( bucketing_id , experiment . id , experiment . trafficAllocation ) if variation_id : variation = self . config . get_variation_from_id ( experiment . key , variation_id ) self . config . logger . info ( 'User "%s" is in variation "%s" of experiment %s.' % ( user_id , variation . key , experiment . key ) ) return variation self . config . logger . info ( 'User "%s" is in no variation.' % user_id ) return None
For a given experiment and bucketing ID determines variation to be shown to user .
56,136
def _generate_key_map ( entity_list , key , entity_class ) : key_map = { } for obj in entity_list : key_map [ obj [ key ] ] = entity_class ( ** obj ) return key_map
Helper method to generate map from key to entity object for given list of dicts .
56,137
def _deserialize_audience ( audience_map ) : for audience in audience_map . values ( ) : condition_structure , condition_list = condition_helper . loads ( audience . conditions ) audience . __dict__ . update ( { 'conditionStructure' : condition_structure , 'conditionList' : condition_list } ) return audience_map
Helper method to de - serialize and populate audience map with the condition list and structure .
56,138
def get_typecast_value ( self , value , type ) : if type == entities . Variable . Type . BOOLEAN : return value == 'true' elif type == entities . Variable . Type . INTEGER : return int ( value ) elif type == entities . Variable . Type . DOUBLE : return float ( value ) else : return value
Helper method to determine actual value based on type of feature variable .
56,139
def get_experiment_from_key ( self , experiment_key ) : experiment = self . experiment_key_map . get ( experiment_key ) if experiment : return experiment self . logger . error ( 'Experiment key "%s" is not in datafile.' % experiment_key ) self . error_handler . handle_error ( exceptions . InvalidExperimentException ( enums . Errors . INVALID_EXPERIMENT_KEY_ERROR ) ) return None
Get experiment for the provided experiment key .
56,140
def get_experiment_from_id ( self , experiment_id ) : experiment = self . experiment_id_map . get ( experiment_id ) if experiment : return experiment self . logger . error ( 'Experiment ID "%s" is not in datafile.' % experiment_id ) self . error_handler . handle_error ( exceptions . InvalidExperimentException ( enums . Errors . INVALID_EXPERIMENT_KEY_ERROR ) ) return None
Get experiment for the provided experiment ID .
56,141
def get_group ( self , group_id ) : group = self . group_id_map . get ( group_id ) if group : return group self . logger . error ( 'Group ID "%s" is not in datafile.' % group_id ) self . error_handler . handle_error ( exceptions . InvalidGroupException ( enums . Errors . INVALID_GROUP_ID_ERROR ) ) return None
Get group for the provided group ID .
56,142
def get_audience ( self , audience_id ) : audience = self . audience_id_map . get ( audience_id ) if audience : return audience self . logger . error ( 'Audience ID "%s" is not in datafile.' % audience_id ) self . error_handler . handle_error ( exceptions . InvalidAudienceException ( ( enums . Errors . INVALID_AUDIENCE_ERROR ) ) )
Get audience object for the provided audience ID .
56,143
def get_variation_from_key ( self , experiment_key , variation_key ) : variation_map = self . variation_key_map . get ( experiment_key ) if variation_map : variation = variation_map . get ( variation_key ) if variation : return variation else : self . logger . error ( 'Variation key "%s" is not in datafile.' % variation_key ) self . error_handler . handle_error ( exceptions . InvalidVariationException ( enums . Errors . INVALID_VARIATION_ERROR ) ) return None self . logger . error ( 'Experiment key "%s" is not in datafile.' % experiment_key ) self . error_handler . handle_error ( exceptions . InvalidExperimentException ( enums . Errors . INVALID_EXPERIMENT_KEY_ERROR ) ) return None
Get variation given experiment and variation key .
56,144
def get_variation_from_id ( self , experiment_key , variation_id ) : variation_map = self . variation_id_map . get ( experiment_key ) if variation_map : variation = variation_map . get ( variation_id ) if variation : return variation else : self . logger . error ( 'Variation ID "%s" is not in datafile.' % variation_id ) self . error_handler . handle_error ( exceptions . InvalidVariationException ( enums . Errors . INVALID_VARIATION_ERROR ) ) return None self . logger . error ( 'Experiment key "%s" is not in datafile.' % experiment_key ) self . error_handler . handle_error ( exceptions . InvalidExperimentException ( enums . Errors . INVALID_EXPERIMENT_KEY_ERROR ) ) return None
Get variation given experiment and variation ID .
56,145
def get_event ( self , event_key ) : event = self . event_key_map . get ( event_key ) if event : return event self . logger . error ( 'Event "%s" is not in datafile.' % event_key ) self . error_handler . handle_error ( exceptions . InvalidEventException ( enums . Errors . INVALID_EVENT_KEY_ERROR ) ) return None
Get event for the provided event key .
56,146
def get_attribute_id ( self , attribute_key ) : attribute = self . attribute_key_map . get ( attribute_key ) has_reserved_prefix = attribute_key . startswith ( RESERVED_ATTRIBUTE_PREFIX ) if attribute : if has_reserved_prefix : self . logger . warning ( ( 'Attribute %s unexpectedly has reserved prefix %s; using attribute ID ' 'instead of reserved attribute name.' % ( attribute_key , RESERVED_ATTRIBUTE_PREFIX ) ) ) return attribute . id if has_reserved_prefix : return attribute_key self . logger . error ( 'Attribute "%s" is not in datafile.' % attribute_key ) self . error_handler . handle_error ( exceptions . InvalidAttributeException ( enums . Errors . INVALID_ATTRIBUTE_ERROR ) ) return None
Get attribute ID for the provided attribute key .
56,147
def get_feature_from_key ( self , feature_key ) : feature = self . feature_key_map . get ( feature_key ) if feature : return feature self . logger . error ( 'Feature "%s" is not in datafile.' % feature_key ) return None
Get feature for the provided feature key .
56,148
def get_rollout_from_id ( self , rollout_id ) : layer = self . rollout_id_map . get ( rollout_id ) if layer : return layer self . logger . error ( 'Rollout with ID "%s" is not in datafile.' % rollout_id ) return None
Get rollout for the provided ID .
56,149
def get_variable_value_for_variation ( self , variable , variation ) : if not variable or not variation : return None if variation . id not in self . variation_variable_usage_map : self . logger . error ( 'Variation with ID "%s" is not in the datafile.' % variation . id ) return None variable_usages = self . variation_variable_usage_map [ variation . id ] variable_usage = None if variable_usages : variable_usage = variable_usages . get ( variable . id ) if variable_usage : variable_value = variable_usage . value self . logger . info ( 'Value for variable "%s" for variation "%s" is "%s".' % ( variable . key , variation . key , variable_value ) ) else : variable_value = variable . defaultValue self . logger . info ( 'Variable "%s" is not used in variation "%s". Assigning default value "%s".' % ( variable . key , variation . key , variable_value ) ) return variable_value
Get the variable value for the given variation .
56,150
def get_variable_for_feature ( self , feature_key , variable_key ) : feature = self . feature_key_map . get ( feature_key ) if not feature : self . logger . error ( 'Feature with key "%s" not found in the datafile.' % feature_key ) return None if variable_key not in feature . variables : self . logger . error ( 'Variable with key "%s" not found in the datafile.' % variable_key ) return None return feature . variables . get ( variable_key )
Get the variable with the given variable key for the given feature .
56,151
def set_forced_variation ( self , experiment_key , user_id , variation_key ) : experiment = self . get_experiment_from_key ( experiment_key ) if not experiment : return False experiment_id = experiment . id if variation_key is None : if user_id in self . forced_variation_map : experiment_to_variation_map = self . forced_variation_map . get ( user_id ) if experiment_id in experiment_to_variation_map : del ( self . forced_variation_map [ user_id ] [ experiment_id ] ) self . logger . debug ( 'Variation mapped to experiment "%s" has been removed for user "%s".' % ( experiment_key , user_id ) ) else : self . logger . debug ( 'Nothing to remove. Variation mapped to experiment "%s" for user "%s" does not exist.' % ( experiment_key , user_id ) ) else : self . logger . debug ( 'Nothing to remove. User "%s" does not exist in the forced variation map.' % user_id ) return True if not validator . is_non_empty_string ( variation_key ) : self . logger . debug ( 'Variation key is invalid.' ) return False forced_variation = self . get_variation_from_key ( experiment_key , variation_key ) if not forced_variation : return False variation_id = forced_variation . id if user_id not in self . forced_variation_map : self . forced_variation_map [ user_id ] = { experiment_id : variation_id } else : self . forced_variation_map [ user_id ] [ experiment_id ] = variation_id self . logger . debug ( 'Set variation "%s" for experiment "%s" and user "%s" in the forced variation map.' % ( variation_id , experiment_id , user_id ) ) return True
Sets users to a map of experiments to forced variations .
56,152
def get_forced_variation ( self , experiment_key , user_id ) : if user_id not in self . forced_variation_map : self . logger . debug ( 'User "%s" is not in the forced variation map.' % user_id ) return None experiment = self . get_experiment_from_key ( experiment_key ) if not experiment : return None experiment_to_variation_map = self . forced_variation_map . get ( user_id ) if not experiment_to_variation_map : self . logger . debug ( 'No experiment "%s" mapped to user "%s" in the forced variation map.' % ( experiment_key , user_id ) ) return None variation_id = experiment_to_variation_map . get ( experiment . id ) if variation_id is None : self . logger . debug ( 'No variation mapped to experiment "%s" in the forced variation map.' % experiment_key ) return None variation = self . get_variation_from_id ( experiment_key , variation_id ) self . logger . debug ( 'Variation "%s" is mapped to experiment "%s" and user "%s" in the forced variation map' % ( variation . key , experiment_key , user_id ) ) return variation
Gets the forced variation key for the given user and experiment .
56,153
def dispatch_event ( event ) : try : if event . http_verb == enums . HTTPVerbs . GET : requests . get ( event . url , params = event . params , timeout = REQUEST_TIMEOUT ) . raise_for_status ( ) elif event . http_verb == enums . HTTPVerbs . POST : requests . post ( event . url , data = json . dumps ( event . params ) , headers = event . headers , timeout = REQUEST_TIMEOUT ) . raise_for_status ( ) except request_exception . RequestException as error : logging . error ( 'Dispatch event failed. Error: %s' % str ( error ) )
Dispatch the event being represented by the Event object .
56,154
def _validate_instantiation_options ( self , datafile , skip_json_validation ) : if not skip_json_validation and not validator . is_datafile_valid ( datafile ) : raise exceptions . InvalidInputException ( enums . Errors . INVALID_INPUT_ERROR . format ( 'datafile' ) ) if not validator . is_event_dispatcher_valid ( self . event_dispatcher ) : raise exceptions . InvalidInputException ( enums . Errors . INVALID_INPUT_ERROR . format ( 'event_dispatcher' ) ) if not validator . is_logger_valid ( self . logger ) : raise exceptions . InvalidInputException ( enums . Errors . INVALID_INPUT_ERROR . format ( 'logger' ) ) if not validator . is_error_handler_valid ( self . error_handler ) : raise exceptions . InvalidInputException ( enums . Errors . INVALID_INPUT_ERROR . format ( 'error_handler' ) )
Helper method to validate all instantiation parameters .
56,155
def _validate_user_inputs ( self , attributes = None , event_tags = None ) : if attributes and not validator . are_attributes_valid ( attributes ) : self . logger . error ( 'Provided attributes are in an invalid format.' ) self . error_handler . handle_error ( exceptions . InvalidAttributeException ( enums . Errors . INVALID_ATTRIBUTE_FORMAT ) ) return False if event_tags and not validator . are_event_tags_valid ( event_tags ) : self . logger . error ( 'Provided event tags are in an invalid format.' ) self . error_handler . handle_error ( exceptions . InvalidEventTagException ( enums . Errors . INVALID_EVENT_TAG_FORMAT ) ) return False return True
Helper method to validate user inputs .
56,156
def _send_impression_event ( self , experiment , variation , user_id , attributes ) : impression_event = self . event_builder . create_impression_event ( experiment , variation . id , user_id , attributes ) self . logger . debug ( 'Dispatching impression event to URL %s with params %s.' % ( impression_event . url , impression_event . params ) ) try : self . event_dispatcher . dispatch_event ( impression_event ) except : self . logger . exception ( 'Unable to dispatch impression event!' ) self . notification_center . send_notifications ( enums . NotificationTypes . ACTIVATE , experiment , user_id , attributes , variation , impression_event )
Helper method to send impression event .
56,157
def _get_feature_variable_for_type ( self , feature_key , variable_key , variable_type , user_id , attributes ) : if not validator . is_non_empty_string ( feature_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'feature_key' ) ) return None if not validator . is_non_empty_string ( variable_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'variable_key' ) ) return None if not isinstance ( user_id , string_types ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'user_id' ) ) return None if not self . _validate_user_inputs ( attributes ) : return None feature_flag = self . config . get_feature_from_key ( feature_key ) if not feature_flag : return None variable = self . config . get_variable_for_feature ( feature_key , variable_key ) if not variable : return None if variable . type != variable_type : self . logger . warning ( 'Requested variable type "%s", but variable is of type "%s". ' 'Use correct API to retrieve value. Returning None.' % ( variable_type , variable . type ) ) return None feature_enabled = False source_info = { } variable_value = variable . defaultValue decision = self . decision_service . get_variation_for_feature ( feature_flag , user_id , attributes ) if decision . variation : feature_enabled = decision . variation . featureEnabled if feature_enabled : variable_value = self . config . get_variable_value_for_variation ( variable , decision . variation ) self . logger . info ( 'Got variable value "%s" for variable "%s" of feature flag "%s".' % ( variable_value , variable_key , feature_key ) ) else : self . logger . info ( 'Feature "%s" for variation "%s" is not enabled. ' 'Returning the default variable value "%s".' % ( feature_key , decision . variation . key , variable_value ) ) else : self . logger . info ( 'User "%s" is not in any variation or rollout rule. ' 'Returning default value for variable "%s" of feature flag "%s".' % ( user_id , variable_key , feature_key ) ) if decision . source == enums . DecisionSources . FEATURE_TEST : source_info = { 'experiment_key' : decision . experiment . key , 'variation_key' : decision . variation . key } try : actual_value = self . config . get_typecast_value ( variable_value , variable_type ) except : self . logger . error ( 'Unable to cast value. Returning None.' ) actual_value = None self . notification_center . send_notifications ( enums . NotificationTypes . DECISION , enums . DecisionNotificationTypes . FEATURE_VARIABLE , user_id , attributes or { } , { 'feature_key' : feature_key , 'feature_enabled' : feature_enabled , 'source' : decision . source , 'variable_key' : variable_key , 'variable_value' : actual_value , 'variable_type' : variable_type , 'source_info' : source_info } ) return actual_value
Helper method to determine value for a certain variable attached to a feature flag based on type of variable .
56,158
def activate ( self , experiment_key , user_id , attributes = None ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'activate' ) ) return None if not validator . is_non_empty_string ( experiment_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'experiment_key' ) ) return None if not isinstance ( user_id , string_types ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'user_id' ) ) return None variation_key = self . get_variation ( experiment_key , user_id , attributes ) if not variation_key : self . logger . info ( 'Not activating user "%s".' % user_id ) return None experiment = self . config . get_experiment_from_key ( experiment_key ) variation = self . config . get_variation_from_key ( experiment_key , variation_key ) self . logger . info ( 'Activating user "%s" in experiment "%s".' % ( user_id , experiment . key ) ) self . _send_impression_event ( experiment , variation , user_id , attributes ) return variation . key
Buckets visitor and sends impression event to Optimizely .
56,159
def track ( self , event_key , user_id , attributes = None , event_tags = None ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'track' ) ) return if not validator . is_non_empty_string ( event_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'event_key' ) ) return if not isinstance ( user_id , string_types ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'user_id' ) ) return if not self . _validate_user_inputs ( attributes , event_tags ) : return event = self . config . get_event ( event_key ) if not event : self . logger . info ( 'Not tracking user "%s" for event "%s".' % ( user_id , event_key ) ) return conversion_event = self . event_builder . create_conversion_event ( event_key , user_id , attributes , event_tags ) self . logger . info ( 'Tracking event "%s" for user "%s".' % ( event_key , user_id ) ) self . logger . debug ( 'Dispatching conversion event to URL %s with params %s.' % ( conversion_event . url , conversion_event . params ) ) try : self . event_dispatcher . dispatch_event ( conversion_event ) except : self . logger . exception ( 'Unable to dispatch conversion event!' ) self . notification_center . send_notifications ( enums . NotificationTypes . TRACK , event_key , user_id , attributes , event_tags , conversion_event )
Send conversion event to Optimizely .
56,160
def get_variation ( self , experiment_key , user_id , attributes = None ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'get_variation' ) ) return None if not validator . is_non_empty_string ( experiment_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'experiment_key' ) ) return None if not isinstance ( user_id , string_types ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'user_id' ) ) return None experiment = self . config . get_experiment_from_key ( experiment_key ) variation_key = None if not experiment : self . logger . info ( 'Experiment key "%s" is invalid. Not activating user "%s".' % ( experiment_key , user_id ) ) return None if not self . _validate_user_inputs ( attributes ) : return None variation = self . decision_service . get_variation ( experiment , user_id , attributes ) if variation : variation_key = variation . key if self . config . is_feature_experiment ( experiment . id ) : decision_notification_type = enums . DecisionNotificationTypes . FEATURE_TEST else : decision_notification_type = enums . DecisionNotificationTypes . AB_TEST self . notification_center . send_notifications ( enums . NotificationTypes . DECISION , decision_notification_type , user_id , attributes or { } , { 'experiment_key' : experiment_key , 'variation_key' : variation_key } ) return variation_key
Gets variation where user will be bucketed .
56,161
def is_feature_enabled ( self , feature_key , user_id , attributes = None ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'is_feature_enabled' ) ) return False if not validator . is_non_empty_string ( feature_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'feature_key' ) ) return False if not isinstance ( user_id , string_types ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'user_id' ) ) return False if not self . _validate_user_inputs ( attributes ) : return False feature = self . config . get_feature_from_key ( feature_key ) if not feature : return False feature_enabled = False source_info = { } decision = self . decision_service . get_variation_for_feature ( feature , user_id , attributes ) is_source_experiment = decision . source == enums . DecisionSources . FEATURE_TEST if decision . variation : if decision . variation . featureEnabled is True : feature_enabled = True if is_source_experiment : source_info = { 'experiment_key' : decision . experiment . key , 'variation_key' : decision . variation . key } self . _send_impression_event ( decision . experiment , decision . variation , user_id , attributes ) if feature_enabled : self . logger . info ( 'Feature "%s" is enabled for user "%s".' % ( feature_key , user_id ) ) else : self . logger . info ( 'Feature "%s" is not enabled for user "%s".' % ( feature_key , user_id ) ) self . notification_center . send_notifications ( enums . NotificationTypes . DECISION , enums . DecisionNotificationTypes . FEATURE , user_id , attributes or { } , { 'feature_key' : feature_key , 'feature_enabled' : feature_enabled , 'source' : decision . source , 'source_info' : source_info } ) return feature_enabled
Returns true if the feature is enabled for the given user .
56,162
def get_enabled_features ( self , user_id , attributes = None ) : enabled_features = [ ] if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'get_enabled_features' ) ) return enabled_features if not isinstance ( user_id , string_types ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'user_id' ) ) return enabled_features if not self . _validate_user_inputs ( attributes ) : return enabled_features for feature in self . config . feature_key_map . values ( ) : if self . is_feature_enabled ( feature . key , user_id , attributes ) : enabled_features . append ( feature . key ) return enabled_features
Returns the list of features that are enabled for the user .
56,163
def get_feature_variable_boolean ( self , feature_key , variable_key , user_id , attributes = None ) : variable_type = entities . Variable . Type . BOOLEAN return self . _get_feature_variable_for_type ( feature_key , variable_key , variable_type , user_id , attributes )
Returns value for a certain boolean variable attached to a feature flag .
56,164
def get_feature_variable_double ( self , feature_key , variable_key , user_id , attributes = None ) : variable_type = entities . Variable . Type . DOUBLE return self . _get_feature_variable_for_type ( feature_key , variable_key , variable_type , user_id , attributes )
Returns value for a certain double variable attached to a feature flag .
56,165
def get_feature_variable_integer ( self , feature_key , variable_key , user_id , attributes = None ) : variable_type = entities . Variable . Type . INTEGER return self . _get_feature_variable_for_type ( feature_key , variable_key , variable_type , user_id , attributes )
Returns value for a certain integer variable attached to a feature flag .
56,166
def get_feature_variable_string ( self , feature_key , variable_key , user_id , attributes = None ) : variable_type = entities . Variable . Type . STRING return self . _get_feature_variable_for_type ( feature_key , variable_key , variable_type , user_id , attributes )
Returns value for a certain string variable attached to a feature .
56,167
def set_forced_variation ( self , experiment_key , user_id , variation_key ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'set_forced_variation' ) ) return False if not validator . is_non_empty_string ( experiment_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'experiment_key' ) ) return False if not isinstance ( user_id , string_types ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'user_id' ) ) return False return self . config . set_forced_variation ( experiment_key , user_id , variation_key )
Force a user into a variation for a given experiment .
56,168
def get_forced_variation ( self , experiment_key , user_id ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'get_forced_variation' ) ) return None if not validator . is_non_empty_string ( experiment_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'experiment_key' ) ) return None if not isinstance ( user_id , string_types ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'user_id' ) ) return None forced_variation = self . config . get_forced_variation ( experiment_key , user_id ) return forced_variation . key if forced_variation else None
Gets the forced variation for a given user and experiment .
56,169
def is_user_in_experiment ( config , experiment , attributes , logger ) : audience_conditions = experiment . getAudienceConditionsOrIds ( ) logger . debug ( audience_logs . EVALUATING_AUDIENCES_COMBINED . format ( experiment . key , json . dumps ( audience_conditions ) ) ) if audience_conditions is None or audience_conditions == [ ] : logger . info ( audience_logs . AUDIENCE_EVALUATION_RESULT_COMBINED . format ( experiment . key , 'TRUE' ) ) return True if attributes is None : attributes = { } def evaluate_custom_attr ( audienceId , index ) : audience = config . get_audience ( audienceId ) custom_attr_condition_evaluator = condition_helper . CustomAttributeConditionEvaluator ( audience . conditionList , attributes , logger ) return custom_attr_condition_evaluator . evaluate ( index ) def evaluate_audience ( audienceId ) : audience = config . get_audience ( audienceId ) if audience is None : return None logger . debug ( audience_logs . EVALUATING_AUDIENCE . format ( audienceId , audience . conditions ) ) result = condition_tree_evaluator . evaluate ( audience . conditionStructure , lambda index : evaluate_custom_attr ( audienceId , index ) ) result_str = str ( result ) . upper ( ) if result is not None else 'UNKNOWN' logger . info ( audience_logs . AUDIENCE_EVALUATION_RESULT . format ( audienceId , result_str ) ) return result eval_result = condition_tree_evaluator . evaluate ( audience_conditions , evaluate_audience ) eval_result = eval_result or False logger . info ( audience_logs . AUDIENCE_EVALUATION_RESULT_COMBINED . format ( experiment . key , str ( eval_result ) . upper ( ) ) ) return eval_result
Determine for given experiment if user satisfies the audiences for the experiment .
56,170
def _get_common_params ( self , user_id , attributes ) : commonParams = { } commonParams [ self . EventParams . PROJECT_ID ] = self . _get_project_id ( ) commonParams [ self . EventParams . ACCOUNT_ID ] = self . _get_account_id ( ) visitor = { } visitor [ self . EventParams . END_USER_ID ] = user_id visitor [ self . EventParams . SNAPSHOTS ] = [ ] commonParams [ self . EventParams . USERS ] = [ ] commonParams [ self . EventParams . USERS ] . append ( visitor ) commonParams [ self . EventParams . USERS ] [ 0 ] [ self . EventParams . ATTRIBUTES ] = self . _get_attributes ( attributes ) commonParams [ self . EventParams . SOURCE_SDK_TYPE ] = 'python-sdk' commonParams [ self . EventParams . ENRICH_DECISIONS ] = True commonParams [ self . EventParams . SOURCE_SDK_VERSION ] = version . __version__ commonParams [ self . EventParams . ANONYMIZE_IP ] = self . _get_anonymize_ip ( ) commonParams [ self . EventParams . REVISION ] = self . _get_revision ( ) return commonParams
Get params which are used same in both conversion and impression events .
56,171
def _get_required_params_for_impression ( self , experiment , variation_id ) : snapshot = { } snapshot [ self . EventParams . DECISIONS ] = [ { self . EventParams . EXPERIMENT_ID : experiment . id , self . EventParams . VARIATION_ID : variation_id , self . EventParams . CAMPAIGN_ID : experiment . layerId } ] snapshot [ self . EventParams . EVENTS ] = [ { self . EventParams . EVENT_ID : experiment . layerId , self . EventParams . TIME : self . _get_time ( ) , self . EventParams . KEY : 'campaign_activated' , self . EventParams . UUID : str ( uuid . uuid4 ( ) ) } ] return snapshot
Get parameters that are required for the impression event to register .
56,172
def _get_required_params_for_conversion ( self , event_key , event_tags ) : snapshot = { } event_dict = { self . EventParams . EVENT_ID : self . config . get_event ( event_key ) . id , self . EventParams . TIME : self . _get_time ( ) , self . EventParams . KEY : event_key , self . EventParams . UUID : str ( uuid . uuid4 ( ) ) } if event_tags : revenue_value = event_tag_utils . get_revenue_value ( event_tags ) if revenue_value is not None : event_dict [ event_tag_utils . REVENUE_METRIC_TYPE ] = revenue_value numeric_value = event_tag_utils . get_numeric_value ( event_tags , self . config . logger ) if numeric_value is not None : event_dict [ event_tag_utils . NUMERIC_METRIC_TYPE ] = numeric_value if len ( event_tags ) > 0 : event_dict [ self . EventParams . TAGS ] = event_tags snapshot [ self . EventParams . EVENTS ] = [ event_dict ] return snapshot
Get parameters that are required for the conversion event to register .
56,173
def create_impression_event ( self , experiment , variation_id , user_id , attributes ) : params = self . _get_common_params ( user_id , attributes ) impression_params = self . _get_required_params_for_impression ( experiment , variation_id ) params [ self . EventParams . USERS ] [ 0 ] [ self . EventParams . SNAPSHOTS ] . append ( impression_params ) return Event ( self . EVENTS_URL , params , http_verb = self . HTTP_VERB , headers = self . HTTP_HEADERS )
Create impression Event to be sent to the logging endpoint .
56,174
def create_conversion_event ( self , event_key , user_id , attributes , event_tags ) : params = self . _get_common_params ( user_id , attributes ) conversion_params = self . _get_required_params_for_conversion ( event_key , event_tags ) params [ self . EventParams . USERS ] [ 0 ] [ self . EventParams . SNAPSHOTS ] . append ( conversion_params ) return Event ( self . EVENTS_URL , params , http_verb = self . HTTP_VERB , headers = self . HTTP_HEADERS )
Create conversion Event to be sent to the logging endpoint .
56,175
def _audience_condition_deserializer ( obj_dict ) : return [ obj_dict . get ( 'name' ) , obj_dict . get ( 'value' ) , obj_dict . get ( 'type' ) , obj_dict . get ( 'match' ) ]
Deserializer defining how dict objects need to be decoded for audience conditions .
56,176
def _get_condition_json ( self , index ) : condition = self . condition_data [ index ] condition_log = { 'name' : condition [ 0 ] , 'value' : condition [ 1 ] , 'type' : condition [ 2 ] , 'match' : condition [ 3 ] } return json . dumps ( condition_log )
Method to generate json for logging audience condition .
56,177
def is_value_type_valid_for_exact_conditions ( self , value ) : if isinstance ( value , string_types ) or isinstance ( value , ( numbers . Integral , float ) ) : return True return False
Method to validate if the value is valid for exact match type evaluation .
56,178
def exists_evaluator ( self , index ) : attr_name = self . condition_data [ index ] [ 0 ] return self . attributes . get ( attr_name ) is not None
Evaluate the given exists match condition for the user attributes .
56,179
def greater_than_evaluator ( self , index ) : condition_name = self . condition_data [ index ] [ 0 ] condition_value = self . condition_data [ index ] [ 1 ] user_value = self . attributes . get ( condition_name ) if not validator . is_finite_number ( condition_value ) : self . logger . warning ( audience_logs . UNKNOWN_CONDITION_VALUE . format ( self . _get_condition_json ( index ) ) ) return None if not self . is_value_a_number ( user_value ) : self . logger . warning ( audience_logs . UNEXPECTED_TYPE . format ( self . _get_condition_json ( index ) , type ( user_value ) , condition_name ) ) return None if not validator . is_finite_number ( user_value ) : self . logger . warning ( audience_logs . INFINITE_ATTRIBUTE_VALUE . format ( self . _get_condition_json ( index ) , condition_name ) ) return None return user_value > condition_value
Evaluate the given greater than match condition for the user attributes .
56,180
def substring_evaluator ( self , index ) : condition_name = self . condition_data [ index ] [ 0 ] condition_value = self . condition_data [ index ] [ 1 ] user_value = self . attributes . get ( condition_name ) if not isinstance ( condition_value , string_types ) : self . logger . warning ( audience_logs . UNKNOWN_CONDITION_VALUE . format ( self . _get_condition_json ( index ) , ) ) return None if not isinstance ( user_value , string_types ) : self . logger . warning ( audience_logs . UNEXPECTED_TYPE . format ( self . _get_condition_json ( index ) , type ( user_value ) , condition_name ) ) return None return condition_value in user_value
Evaluate the given substring match condition for the given user attributes .
56,181
def evaluate ( self , index ) : if self . condition_data [ index ] [ 2 ] != self . CUSTOM_ATTRIBUTE_CONDITION_TYPE : self . logger . warning ( audience_logs . UNKNOWN_CONDITION_TYPE . format ( self . _get_condition_json ( index ) ) ) return None condition_match = self . condition_data [ index ] [ 3 ] if condition_match is None : condition_match = ConditionMatchTypes . EXACT if condition_match not in self . EVALUATORS_BY_MATCH_TYPE : self . logger . warning ( audience_logs . UNKNOWN_MATCH_TYPE . format ( self . _get_condition_json ( index ) ) ) return None if condition_match != ConditionMatchTypes . EXISTS : attribute_key = self . condition_data [ index ] [ 0 ] if attribute_key not in self . attributes : self . logger . debug ( audience_logs . MISSING_ATTRIBUTE_VALUE . format ( self . _get_condition_json ( index ) , attribute_key ) ) return None if self . attributes . get ( attribute_key ) is None : self . logger . debug ( audience_logs . NULL_ATTRIBUTE_VALUE . format ( self . _get_condition_json ( index ) , attribute_key ) ) return None return self . EVALUATORS_BY_MATCH_TYPE [ condition_match ] ( self , index )
Given a custom attribute audience condition and user attributes evaluate the condition against the attributes .
56,182
def object_hook ( self , object_dict ) : instance = self . decoder ( object_dict ) self . condition_list . append ( instance ) self . index += 1 return self . index
Hook which when passed into a json . JSONDecoder will replace each dict in a json string with its index and convert the dict to an object as defined by the passed in condition_decoder . The newly created condition object is appended to the conditions_list .
56,183
def _get_bucketing_id ( self , user_id , attributes ) : attributes = attributes or { } bucketing_id = attributes . get ( enums . ControlAttributes . BUCKETING_ID ) if bucketing_id is not None : if isinstance ( bucketing_id , string_types ) : return bucketing_id self . logger . warning ( 'Bucketing ID attribute is not a string. Defaulted to user_id.' ) return user_id
Helper method to determine bucketing ID for the user .
56,184
def get_forced_variation ( self , experiment , user_id ) : forced_variations = experiment . forcedVariations if forced_variations and user_id in forced_variations : variation_key = forced_variations . get ( user_id ) variation = self . config . get_variation_from_key ( experiment . key , variation_key ) if variation : self . logger . info ( 'User "%s" is forced in variation "%s".' % ( user_id , variation_key ) ) return variation return None
Determine if a user is forced into a variation for the given experiment and return that variation .
56,185
def get_stored_variation ( self , experiment , user_profile ) : user_id = user_profile . user_id variation_id = user_profile . get_variation_for_experiment ( experiment . id ) if variation_id : variation = self . config . get_variation_from_id ( experiment . key , variation_id ) if variation : self . logger . info ( 'Found a stored decision. User "%s" is in variation "%s" of experiment "%s".' % ( user_id , variation . key , experiment . key ) ) return variation return None
Determine if the user has a stored variation available for the given experiment and return that .
56,186
def get_variation ( self , experiment , user_id , attributes , ignore_user_profile = False ) : if not experiment_helper . is_experiment_running ( experiment ) : self . logger . info ( 'Experiment "%s" is not running.' % experiment . key ) return None variation = self . config . get_forced_variation ( experiment . key , user_id ) if variation : return variation variation = self . get_forced_variation ( experiment , user_id ) if variation : return variation user_profile = UserProfile ( user_id ) if not ignore_user_profile and self . user_profile_service : try : retrieved_profile = self . user_profile_service . lookup ( user_id ) except : self . logger . exception ( 'Unable to retrieve user profile for user "%s" as lookup failed.' % user_id ) retrieved_profile = None if validator . is_user_profile_valid ( retrieved_profile ) : user_profile = UserProfile ( ** retrieved_profile ) variation = self . get_stored_variation ( experiment , user_profile ) if variation : return variation else : self . logger . warning ( 'User profile has invalid format.' ) if not audience_helper . is_user_in_experiment ( self . config , experiment , attributes , self . logger ) : self . logger . info ( 'User "%s" does not meet conditions to be in experiment "%s".' % ( user_id , experiment . key ) ) return None bucketing_id = self . _get_bucketing_id ( user_id , attributes ) variation = self . bucketer . bucket ( experiment , user_id , bucketing_id ) if variation : if not ignore_user_profile and self . user_profile_service : try : user_profile . save_variation_for_experiment ( experiment . id , variation . id ) self . user_profile_service . save ( user_profile . __dict__ ) except : self . logger . exception ( 'Unable to save user profile for user "%s".' % user_id ) return variation return None
Top - level function to help determine variation user should be put in .
56,187
def get_experiment_in_group ( self , group , bucketing_id ) : experiment_id = self . bucketer . find_bucket ( bucketing_id , group . id , group . trafficAllocation ) if experiment_id : experiment = self . config . get_experiment_from_id ( experiment_id ) if experiment : self . logger . info ( 'User with bucketing ID "%s" is in experiment %s of group %s.' % ( bucketing_id , experiment . key , group . id ) ) return experiment self . logger . info ( 'User with bucketing ID "%s" is not in any experiments of group %s.' % ( bucketing_id , group . id ) ) return None
Determine which experiment in the group the user is bucketed into .
56,188
def add_notification_listener ( self , notification_type , notification_callback ) : if notification_type not in self . notifications : self . notifications [ notification_type ] = [ ( self . notification_id , notification_callback ) ] else : if reduce ( lambda a , b : a + 1 , filter ( lambda tup : tup [ 1 ] == notification_callback , self . notifications [ notification_type ] ) , 0 ) > 0 : return - 1 self . notifications [ notification_type ] . append ( ( self . notification_id , notification_callback ) ) ret_val = self . notification_id self . notification_id += 1 return ret_val
Add a notification callback to the notification center .
56,189
def remove_notification_listener ( self , notification_id ) : for v in self . notifications . values ( ) : toRemove = list ( filter ( lambda tup : tup [ 0 ] == notification_id , v ) ) if len ( toRemove ) > 0 : v . remove ( toRemove [ 0 ] ) return True return False
Remove a previously added notification callback .
56,190
def send_notifications ( self , notification_type , * args ) : if notification_type in self . notifications : for notification_id , callback in self . notifications [ notification_type ] : try : callback ( * args ) except : self . logger . exception ( 'Problem calling notify callback!' )
Fires off the notification for the specific event . Uses var args to pass in a arbitrary list of parameter according to which notification type was fired .
56,191
def and_evaluator ( conditions , leaf_evaluator ) : saw_null_result = False for condition in conditions : result = evaluate ( condition , leaf_evaluator ) if result is False : return False if result is None : saw_null_result = True return None if saw_null_result else True
Evaluates a list of conditions as if the evaluator had been applied to each entry and the results AND - ed together .
56,192
def not_evaluator ( conditions , leaf_evaluator ) : if not len ( conditions ) > 0 : return None result = evaluate ( conditions [ 0 ] , leaf_evaluator ) return None if result is None else not result
Evaluates a list of conditions as if the evaluator had been applied to a single entry and NOT was applied to the result .
56,193
def evaluate ( conditions , leaf_evaluator ) : if isinstance ( conditions , list ) : if conditions [ 0 ] in list ( EVALUATORS_BY_OPERATOR_TYPE . keys ( ) ) : return EVALUATORS_BY_OPERATOR_TYPE [ conditions [ 0 ] ] ( conditions [ 1 : ] , leaf_evaluator ) else : return EVALUATORS_BY_OPERATOR_TYPE [ ConditionOperatorTypes . OR ] ( conditions , leaf_evaluator ) leaf_condition = conditions return leaf_evaluator ( leaf_condition )
Top level method to evaluate conditions .
56,194
def data_objet_class ( data_mode = 'value' , time_mode = 'framewise' ) : classes_table = { ( 'value' , 'global' ) : GlobalValueObject , ( 'value' , 'event' ) : EventValueObject , ( 'value' , 'segment' ) : SegmentValueObject , ( 'value' , 'framewise' ) : FrameValueObject , ( 'label' , 'global' ) : GlobalLabelObject , ( 'label' , 'event' ) : EventLabelObject , ( 'label' , 'segment' ) : SegmentLabelObject , ( 'label' , 'framewise' ) : FrameLabelObject } try : return classes_table [ ( data_mode , time_mode ) ] except KeyError as e : raise ValueError ( 'Wrong arguments' )
Factory function for Analyzer result
56,195
def JSON_NumpyArrayEncoder ( obj ) : if isinstance ( obj , np . ndarray ) : return { 'numpyArray' : obj . tolist ( ) , 'dtype' : obj . dtype . __str__ ( ) } elif isinstance ( obj , np . generic ) : return np . asscalar ( obj ) else : print type ( obj ) raise TypeError ( repr ( obj ) + " is not JSON serializable" )
Define Specialize JSON encoder for numpy array
56,196
def render ( self ) : fig , ax = plt . subplots ( ) self . data_object . _render_plot ( ax ) return fig
Render a matplotlib figure from the analyzer result
56,197
def new_result ( self , data_mode = 'value' , time_mode = 'framewise' ) : from datetime import datetime result = AnalyzerResult ( data_mode = data_mode , time_mode = time_mode ) result . id_metadata . date = datetime . now ( ) . replace ( microsecond = 0 ) . isoformat ( ' ' ) result . id_metadata . version = timeside . core . __version__ result . id_metadata . author = 'TimeSide' result . id_metadata . id = self . id ( ) result . id_metadata . name = self . name ( ) result . id_metadata . description = self . description ( ) result . id_metadata . unit = self . unit ( ) result . id_metadata . proc_uuid = self . uuid ( ) result . audio_metadata . uri = self . mediainfo ( ) [ 'uri' ] result . audio_metadata . sha1 = self . mediainfo ( ) [ 'sha1' ] result . audio_metadata . start = self . mediainfo ( ) [ 'start' ] result . audio_metadata . duration = self . mediainfo ( ) [ 'duration' ] result . audio_metadata . is_segment = self . mediainfo ( ) [ 'is_segment' ] result . audio_metadata . channels = self . channels ( ) result . parameters = Parameters ( self . get_parameters ( ) ) if time_mode == 'framewise' : result . data_object . frame_metadata . samplerate = self . result_samplerate result . data_object . frame_metadata . blocksize = self . result_blocksize result . data_object . frame_metadata . stepsize = self . result_stepsize return result
Create a new result
56,198
def downmix_to_mono ( process_func ) : import functools @ functools . wraps ( process_func ) def wrapper ( analyzer , frames , eod ) : if frames . ndim > 1 : downmix_frames = frames . mean ( axis = - 1 ) else : downmix_frames = frames process_func ( analyzer , downmix_frames , eod ) return frames , eod return wrapper
Pre - processing decorator that downmixes frames from multi - channel to mono
56,199
def frames_adapter ( process_func ) : import functools import numpy as np class framesBuffer ( object ) : def __init__ ( self , blocksize , stepsize ) : self . blocksize = blocksize self . stepsize = stepsize self . buffer = None def frames ( self , frames , eod ) : if self . buffer is not None : stack = np . concatenate ( [ self . buffer , frames ] ) else : stack = frames . copy ( ) stack_length = len ( stack ) nb_frames = ( stack_length - self . blocksize + self . stepsize ) // self . stepsize nb_frames = max ( nb_frames , 0 ) frames_length = nb_frames * self . stepsize + self . blocksize - self . stepsize last_block_size = stack_length - frames_length if eod : pad_shape = tuple ( self . blocksize - last_block_size if i == 0 else x for i , x in enumerate ( frames . shape ) ) stack = np . concatenate ( [ stack , np . zeros ( pad_shape , dtype = frames . dtype ) ] ) nb_frames += 1 self . buffer = stack [ nb_frames * self . stepsize : ] eod_list = np . repeat ( False , nb_frames ) if eod and len ( eod_list ) : eod_list [ - 1 ] = eod for index , eod in zip ( xrange ( 0 , nb_frames * self . stepsize , self . stepsize ) , eod_list ) : yield ( stack [ index : index + self . blocksize ] , eod ) aubio_analyzers = [ 'aubio_melenergy' , 'aubio_mfcc' , 'aubio_pitch' , 'aubio_specdesc' , 'aubio_temporal' ] @ functools . wraps ( process_func ) def wrapper ( analyzer , frames , eod ) : if not hasattr ( analyzer , 'frames_buffer' ) : if analyzer . id ( ) in aubio_analyzers : analyzer . frames_buffer = framesBuffer ( analyzer . input_stepsize , analyzer . input_stepsize ) else : analyzer . frames_buffer = framesBuffer ( analyzer . input_blocksize , analyzer . input_stepsize ) for adapted_frames , adapted_eod in analyzer . frames_buffer . frames ( frames , eod ) : process_func ( analyzer , adapted_frames , adapted_eod ) return frames , eod return wrapper
Pre - processing decorator that adapt frames to match input_blocksize and input_stepsize of the decorated analyzer