idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
9,900
def _gather_field_values ( item , * , fields = None , field_map = FIELD_MAP , normalize_values = False , normalize_func = normalize_value ) : it = get_item_tags ( item ) if fields is None : fields = list ( it . keys ( ) ) normalize = normalize_func if normalize_values else lambda x : str ( x ) field_values = [ ] for field in fields : field_values . append ( normalize ( list_to_single_value ( get_field ( it , field , field_map = field_map ) ) ) ) return tuple ( field_values )
Create a tuple of normalized metadata field values .
143
9
9,901
def find_existing_items ( src , dst , * , fields = None , field_map = None , normalize_values = False , normalize_func = normalize_value ) : if field_map is None : field_map = FIELD_MAP dst_keys = { _gather_field_values ( dst_item , fields = fields , field_map = field_map , normalize_values = normalize_values , normalize_func = normalize_func ) for dst_item in dst } for src_item in src : if _gather_field_values ( src_item , fields = fields , field_map = field_map , normalize_values = normalize_values , normalize_func = normalize_func ) in dst_keys : yield src_item
Find items from an item collection that are in another item collection .
173
13
9,902
def monitor ( self , message , * args , * * kws ) : if self . isEnabledFor ( MON ) : # Yes, logger takes its '*args' as 'args'. self . _log ( MON , message , args , * * kws )
Define a monitoring logger that will be added to Logger
55
12
9,903
def monitor ( msg , * args , * * kwargs ) : if len ( logging . root . handlers ) == 0 : logging . basicConfig ( ) logging . root . monitor ( msg , * args , * * kwargs )
Log a message with severity MON on the root logger .
50
11
9,904
def format ( self , record ) : try : n = record . n except AttributeError : n = 'default' try : message = record . message except AttributeError : message = record . msg senml = OrderedDict ( uid = "hyperstream" , bt = datetime . utcfromtimestamp ( record . created ) . isoformat ( ) [ : - 3 ] + 'Z' , e = [ OrderedDict ( n = n , v = message ) ] ) formatted_json = json . dumps ( senml ) return formatted_json
The formatting function
122
3
9,905
def teardown ( self ) : with self . _teardown_lock : if not self . _teardown_called : self . _teardown_called = True if len ( self . _acquiring_session_ids ) > 0 : logger . info ( f"Destroying all sessions that have not acquired keys: {self._acquiring_session_ids}..." ) for session_id in self . _acquiring_session_ids : try : self . consul_client . session . destroy ( session_id = session_id ) logger . debug ( f"Destroyed: {session_id}" ) except requests . exceptions . ConnectionError as e : logger . debug ( f"Exception: {e}" ) logger . warning ( f"Could not connect to Consul to clean up session {session_id}" ) atexit . unregister ( self . teardown )
Tears down the instance removing any remaining sessions that this instance has created .
190
15
9,906
def we_are_in_lyon ( ) : import socket try : hostname = socket . gethostname ( ) ip = socket . gethostbyname ( hostname ) except socket . gaierror : return False return ip . startswith ( "134.158." )
Check if we are on a Lyon machine
60
8
9,907
def read_csv ( text , sep = "\t" ) : import pandas as pd # no top level load to make a faster import of db return pd . read_csv ( StringIO ( text ) , sep = "\t" )
Create a DataFrame from CSV text
52
7
9,908
def add_datetime ( dataframe , timestamp_key = 'UNIXTIME' ) : def convert_data ( timestamp ) : return datetime . fromtimestamp ( float ( timestamp ) / 1e3 , UTC_TZ ) try : log . debug ( "Adding DATETIME column to the data" ) converted = dataframe [ timestamp_key ] . apply ( convert_data ) dataframe [ 'DATETIME' ] = converted except KeyError : log . warning ( "Could not add DATETIME column" )
Add an additional DATETIME column with standar datetime format .
115
15
9,909
def show_ahrs_calibration ( clb_upi , version = '3' ) : db = DBManager ( ) ahrs_upi = clbupi2ahrsupi ( clb_upi ) print ( "AHRS UPI: {}" . format ( ahrs_upi ) ) content = db . _get_content ( "show_product_test.htm?upi={0}&" "testtype=AHRS-CALIBRATION-v{1}&n=1&out=xml" . format ( ahrs_upi , version ) ) . replace ( '\n' , '' ) import xml . etree . ElementTree as ET try : root = ET . parse ( io . StringIO ( content ) ) . getroot ( ) except ET . ParseError : print ( "No calibration data found" ) else : for child in root : print ( "{}: {}" . format ( child . tag , child . text ) ) names = [ c . text for c in root . findall ( ".//Name" ) ] values = [ [ i . text for i in c ] for c in root . findall ( ".//Values" ) ] for name , value in zip ( names , values ) : print ( "{}: {}" . format ( name , value ) )
Show AHRS calibration data for given clb_upi .
288
13
9,910
def _datalog ( self , parameter , run , maxrun , det_id ) : values = { 'parameter_name' : parameter , 'minrun' : run , 'maxrun' : maxrun , 'detid' : det_id , } data = urlencode ( values ) content = self . _get_content ( 'streamds/datalognumbers.txt?' + data ) if content . startswith ( 'ERROR' ) : log . error ( content ) return None try : dataframe = read_csv ( content ) except ValueError : log . warning ( "Empty dataset" ) # ...probably. Waiting for more info return make_empty_dataset ( ) else : add_datetime ( dataframe ) try : self . _add_converted_units ( dataframe , parameter ) except KeyError : log . warning ( "Could not add converted units for {0}" . format ( parameter ) ) return dataframe
Extract data from database
204
5
9,911
def _add_converted_units ( self , dataframe , parameter , key = 'VALUE' ) : convert_unit = self . parameters . get_converter ( parameter ) try : log . debug ( "Adding unit converted DATA_VALUE to the data" ) dataframe [ key ] = dataframe [ 'DATA_VALUE' ] . apply ( convert_unit ) except KeyError : log . warning ( "Missing 'VALUE': no unit conversion." ) else : dataframe . unit = self . parameters . unit ( parameter )
Add an additional DATA_VALUE column with converted VALUEs
112
12
9,912
def to_det_id ( self , det_id_or_det_oid ) : try : int ( det_id_or_det_oid ) except ValueError : return self . get_det_id ( det_id_or_det_oid ) else : return det_id_or_det_oid
Convert det ID or OID to det ID
69
10
9,913
def to_det_oid ( self , det_id_or_det_oid ) : try : int ( det_id_or_det_oid ) except ValueError : return det_id_or_det_oid else : return self . get_det_oid ( det_id_or_det_oid )
Convert det OID or ID to det OID
69
11
9,914
def _load_parameters ( self ) : parameters = self . _get_json ( 'allparam/s' ) data = { } for parameter in parameters : # There is a case-chaos in the DB data [ parameter [ 'Name' ] . lower ( ) ] = parameter self . _parameters = ParametersContainer ( data )
Retrieve a list of available parameters from the database
72
10
9,915
def trigger_setup ( self , runsetup_oid ) : r = self . _get_content ( "jsonds/rslite/s?rs_oid={}&upifilter=1.1.2.2.3/*" . format ( runsetup_oid ) ) data = json . loads ( r ) [ 'Data' ] if not data : log . error ( "Empty dataset." ) return raw_setup = data [ 0 ] det_id = raw_setup [ 'DetID' ] name = raw_setup [ 'Name' ] description = raw_setup [ 'Desc' ] _optical_df = raw_setup [ 'ConfGroups' ] [ 0 ] optical_df = { 'Name' : _optical_df [ 'Name' ] , 'Desc' : _optical_df [ 'Desc' ] } for param in _optical_df [ 'Params' ] : pname = self . parameters . oid2name ( param [ 'OID' ] ) . replace ( 'DAQ_' , '' ) try : dtype = float if '.' in param [ 'Val' ] else int val = dtype ( param [ 'Val' ] ) except ValueError : val = param [ 'Val' ] optical_df [ pname ] = val _acoustic_df = raw_setup [ 'ConfGroups' ] [ 1 ] acoustic_df = { 'Name' : _acoustic_df [ 'Name' ] , 'Desc' : _acoustic_df [ 'Desc' ] } for param in _acoustic_df [ 'Params' ] : pname = self . parameters . oid2name ( param [ 'OID' ] ) . replace ( 'DAQ_' , '' ) try : dtype = float if '.' in param [ 'Val' ] else int val = dtype ( param [ 'Val' ] ) except ValueError : val = param [ 'Val' ] acoustic_df [ pname ] = val return TriggerSetup ( runsetup_oid , name , det_id , description , optical_df , acoustic_df )
Retrieve the trigger setup for a given runsetup OID
455
12
9,916
def detx ( self , det_id , t0set = None , calibration = None ) : url = 'detx/{0}?' . format ( det_id ) # '?' since it's ignored if no args if t0set is not None : url += '&t0set=' + t0set if calibration is not None : url += '&calibrid=' + calibration detx = self . _get_content ( url ) return detx
Retrieve the detector file for given detector id
99
9
9,917
def _get_json ( self , url ) : content = self . _get_content ( 'jsonds/' + url ) try : json_content = json . loads ( content . decode ( ) ) except AttributeError : json_content = json . loads ( content ) if json_content [ 'Comment' ] : log . warning ( json_content [ 'Comment' ] ) if json_content [ 'Result' ] != 'OK' : raise ValueError ( 'Error while retrieving the parameter list.' ) return json_content [ 'Data' ]
Get JSON - type content
118
5
9,918
def _get_content ( self , url ) : target_url = self . _db_url + '/' + unquote ( url ) # .encode('utf-8')) log . debug ( "Opening '{0}'" . format ( target_url ) ) try : f = self . opener . open ( target_url ) except HTTPError as e : log . error ( "HTTP error, your session may be expired." ) log . error ( e ) if input ( "Request new permanent session and retry? (y/n)" ) in 'yY' : self . request_permanent_session ( ) return self . _get_content ( url ) else : return None log . debug ( "Accessing '{0}'" . format ( target_url ) ) try : content = f . read ( ) except IncompleteRead as icread : log . critical ( "Incomplete data received from the DB, " + "the data could be corrupted." ) content = icread . partial log . debug ( "Got {0} bytes of data." . format ( len ( content ) ) ) return content . decode ( 'utf-8' )
Get HTML content
247
3
9,919
def opener ( self ) : if self . _opener is None : log . debug ( "Creating connection handler" ) opener = build_opener ( ) if self . _cookies : log . debug ( "Appending cookies" ) else : log . debug ( "No cookies to append" ) for cookie in self . _cookies : cookie_str = cookie . name + '=' + cookie . value opener . addheaders . append ( ( 'Cookie' , cookie_str ) ) self . _opener = opener else : log . debug ( "Reusing connection manager" ) return self . _opener
A reusable connection manager
130
4
9,920
def request_sid_cookie ( self , username , password ) : log . debug ( "Requesting SID cookie" ) target_url = self . _login_url + '?usr={0}&pwd={1}&persist=y' . format ( username , password ) cookie = urlopen ( target_url ) . read ( ) return cookie
Request cookie for permanent session token .
77
7
9,921
def restore_session ( self , cookie ) : log . debug ( "Restoring session from cookie: {}" . format ( cookie ) ) opener = build_opener ( ) opener . addheaders . append ( ( 'Cookie' , cookie ) ) self . _opener = opener
Establish databse connection using permanent session cookie
60
10
9,922
def login ( self , username , password ) : log . debug ( "Logging in to the DB" ) opener = self . _build_opener ( ) values = { 'usr' : username , 'pwd' : password } req = self . _make_request ( self . _login_url , values ) try : log . debug ( "Sending login request" ) f = opener . open ( req ) except URLError as e : log . error ( "Failed to connect to the database -> probably down!" ) log . error ( "Error from database server:\n {0}" . format ( e ) ) return False html = f . read ( ) failed_auth_message = 'Bad username or password' if failed_auth_message in str ( html ) : log . error ( failed_auth_message ) return False return True
Login to the database and store cookies for upcoming requests .
181
11
9,923
def _update_streams ( self ) : content = self . _db . _get_content ( "streamds" ) self . _stream_df = read_csv ( content ) . sort_values ( "STREAM" ) self . _streams = None for stream in self . streams : setattr ( self , stream , self . __getattr__ ( stream ) )
Update the list of available straems
81
7
9,924
def streams ( self ) : if self . _streams is None : self . _streams = list ( self . _stream_df [ "STREAM" ] . values ) return self . _streams
A list of available streams
44
5
9,925
def help ( self , stream ) : if stream not in self . streams : log . error ( "Stream '{}' not found in the database." . format ( stream ) ) params = self . _stream_df [ self . _stream_df [ 'STREAM' ] == stream ] . values [ 0 ] self . _print_stream_parameters ( params )
Show the help for a given stream .
79
8
9,926
def _print_stream_parameters ( self , values ) : cprint ( "{0}" . format ( * values ) , "magenta" , attrs = [ "bold" ] ) print ( "{4}" . format ( * values ) ) cprint ( " available formats: {1}" . format ( * values ) , "blue" ) cprint ( " mandatory selectors: {2}" . format ( * values ) , "red" ) cprint ( " optional selectors: {3}" . format ( * values ) , "green" ) print ( )
Print a coloured help for a given tuple of stream parameters .
121
12
9,927
def get ( self , stream , fmt = 'txt' , * * kwargs ) : sel = '' . join ( [ "&{0}={1}" . format ( k , v ) for ( k , v ) in kwargs . items ( ) ] ) url = "streamds/{0}.{1}?{2}" . format ( stream , fmt , sel [ 1 : ] ) data = self . _db . _get_content ( url ) if not data : log . error ( "No data found at URL '%s'." % url ) return if ( data . startswith ( "ERROR" ) ) : log . error ( data ) return if fmt == "txt" : return read_csv ( data ) return data
Get the data for a given stream manually
162
8
9,928
def get_parameter ( self , parameter ) : parameter = self . _get_parameter_name ( parameter ) return self . _parameters [ parameter ]
Return a dict for given parameter
34
6
9,929
def get_converter ( self , parameter ) : if parameter not in self . _converters : param = self . get_parameter ( parameter ) try : scale = float ( param [ 'Scale' ] ) except KeyError : scale = 1 def convert ( value ) : # easy_scale = float(param['EasyScale']) # easy_scale_multiplier = float(param['EasyScaleMultiplier']) return value * scale return convert
Generate unit conversion function for given parameter
98
8
9,930
def unit ( self , parameter ) : parameter = self . _get_parameter_name ( parameter ) . lower ( ) return self . _parameters [ parameter ] [ 'Unit' ]
Get the unit for given parameter
40
6
9,931
def oid2name ( self , oid ) : if not self . _oid_lookup : for name , data in self . _parameters . items ( ) : self . _oid_lookup [ data [ 'OID' ] ] = data [ 'Name' ] return self . _oid_lookup [ oid ]
Look up the parameter name for a given OID
72
10
9,932
def via_dom_id ( self , dom_id , det_id ) : try : return DOM . from_json ( [ d for d in self . _json if d [ "DOMId" ] == dom_id and d [ "DetOID" ] == det_id ] [ 0 ] ) except IndexError : log . critical ( "No DOM found for DOM ID '{0}'" . format ( dom_id ) )
Return DOM for given dom_id
94
7
9,933
def via_clb_upi ( self , clb_upi , det_id ) : try : return DOM . from_json ( [ d for d in self . _json if d [ "CLBUPI" ] == clb_upi and d [ "DetOID" ] == det_id ] [ 0 ] ) except IndexError : log . critical ( "No DOM found for CLB UPI '{0}'" . format ( clb_upi ) )
return DOM for given CLB UPI
106
8
9,934
def upi ( self ) : parameter = 'UPI' if parameter not in self . _by : self . _populate ( by = parameter ) return self . _by [ parameter ]
A dict of CLBs with UPI as key
40
10
9,935
def dom_id ( self ) : parameter = 'DOMID' if parameter not in self . _by : self . _populate ( by = parameter ) return self . _by [ parameter ]
A dict of CLBs with DOM ID as key
41
10
9,936
def base ( self , du ) : parameter = 'base' if parameter not in self . _by : self . _by [ parameter ] = { } for clb in self . upi . values ( ) : if clb . floor == 0 : self . _by [ parameter ] [ clb . du ] = clb return self . _by [ parameter ] [ du ]
Return the base CLB for a given DU
80
9
9,937
def get_results ( self , stream , time_interval ) : query = stream . stream_id . as_raw ( ) query [ 'datetime' ] = { '$gt' : time_interval . start , '$lte' : time_interval . end } with switch_db ( StreamInstanceModel , 'hyperstream' ) : for instance in StreamInstanceModel . objects ( __raw__ = query ) : yield StreamInstance ( timestamp = instance . datetime , value = instance . value )
Get the results for a given stream
110
7
9,938
def seek_to_packet ( self , index ) : pointer_position = self . packet_positions [ index ] self . blob_file . seek ( pointer_position , 0 )
Move file pointer to the packet with given index .
40
10
9,939
def next_blob ( self ) : try : length = struct . unpack ( '<i' , self . blob_file . read ( 4 ) ) [ 0 ] except struct . error : raise StopIteration header = CLBHeader ( file_obj = self . blob_file ) blob = { 'CLBHeader' : header } remaining_length = length - header . size pmt_data = [ ] pmt_raw_data = self . blob_file . read ( remaining_length ) pmt_raw_data_io = BytesIO ( pmt_raw_data ) for _ in range ( int ( remaining_length / 6 ) ) : channel_id , time , tot = struct . unpack ( '>cic' , pmt_raw_data_io . read ( 6 ) ) pmt_data . append ( PMTData ( ord ( channel_id ) , time , ord ( tot ) ) ) blob [ 'PMTData' ] = pmt_data blob [ 'PMTRawData' ] = pmt_raw_data return blob
Generate next blob in file
233
6
9,940
def getKendallTauScore ( myResponse , otherResponse ) : # variables kt = 0 list1 = myResponse . values ( ) list2 = otherResponse . values ( ) if len ( list1 ) <= 1 : return kt # runs through list1 for itr1 in range ( 0 , len ( list1 ) - 1 ) : # runs through list2 for itr2 in range ( itr1 + 1 , len ( list2 ) ) : # checks if there is a discrepancy. If so, adds if ( ( list1 [ itr1 ] > list1 [ itr2 ] and list2 [ itr1 ] < list2 [ itr2 ] ) or ( list1 [ itr1 ] < list1 [ itr2 ] and list2 [ itr1 ] > list2 [ itr2 ] ) ) : kt += 1 # normalizes between 0 and 1 kt = ( kt * 2 ) / ( len ( list1 ) * ( len ( list1 ) - 1 ) ) # returns found value return kt
Returns the Kendall Tau Score
228
5
9,941
def getCandScoresMap ( self , profile ) : # Currently, we expect the profile to contain complete ordering over candidates. elecType = profile . getElecType ( ) if elecType != "soc" and elecType != "toc" : print ( "ERROR: unsupported election type" ) exit ( ) # Initialize our dictionary so that all candidates have a score of zero. candScoresMap = dict ( ) for cand in profile . candMap . keys ( ) : candScoresMap [ cand ] = 0.0 rankMaps = profile . getRankMaps ( ) rankMapCounts = profile . getPreferenceCounts ( ) scoringVector = self . getScoringVector ( profile ) # Go through the rankMaps of the profile and increment each candidates score appropriately. for i in range ( 0 , len ( rankMaps ) ) : rankMap = rankMaps [ i ] rankMapCount = rankMapCounts [ i ] for cand in rankMap . keys ( ) : candScoresMap [ cand ] += scoringVector [ rankMap [ cand ] - 1 ] * rankMapCount # print("candScoresMap=", candScoresMap) return candScoresMap
Returns a dictonary that associates the integer representation of each candidate with the score they recieved in the profile .
251
23
9,942
def getMov ( self , profile ) : # from . import mov import mov return mov . MoVScoring ( profile , self . getScoringVector ( profile ) )
Returns an integer that is equal to the margin of victory of the election profile .
37
16
9,943
def getCandScoresMap ( self , profile ) : # Currently, we expect the profile to contain complete ordering over candidates. elecType = profile . getElecType ( ) if elecType != "soc" and elecType != "toc" : print ( "ERROR: unsupported profile type" ) exit ( ) bucklinScores = dict ( ) rankMaps = profile . getRankMaps ( ) preferenceCounts = profile . getPreferenceCounts ( ) for cand in profile . candMap . keys ( ) : # We keep track of the number of times a candidate is ranked in the first t positions. numTimesRanked = 0 # We increase t in increments of 1 until we find t such that the candidate is ranked in the # first t positions in at least half the votes. for t in range ( 1 , profile . numCands + 1 ) : for i in range ( 0 , len ( rankMaps ) ) : if ( rankMaps [ i ] [ cand ] == t ) : numTimesRanked += preferenceCounts [ i ] if numTimesRanked >= math . ceil ( float ( profile . numVoters ) / 2 ) : bucklinScores [ cand ] = t break return bucklinScores
Returns a dictionary that associates integer representations of each candidate with their Bucklin score .
257
16
9,944
def getCandScoresMap ( self , profile ) : # Currently, we expect the profile to contain complete ordering over candidates. Ties are # allowed however. elecType = profile . getElecType ( ) if elecType != "soc" and elecType != "toc" : print ( "ERROR: unsupported election type" ) exit ( ) wmg = profile . getWmg ( ) # Initialize the maximin score for each candidate as infinity. maximinScores = dict ( ) for cand in wmg . keys ( ) : maximinScores [ cand ] = float ( "inf" ) # For each pair of candidates, calculate the number of times each beats the other. for cand1 , cand2 in itertools . combinations ( wmg . keys ( ) , 2 ) : if cand2 in wmg [ cand1 ] . keys ( ) : maximinScores [ cand1 ] = min ( maximinScores [ cand1 ] , wmg [ cand1 ] [ cand2 ] ) maximinScores [ cand2 ] = min ( maximinScores [ cand2 ] , wmg [ cand2 ] [ cand1 ] ) return maximinScores
Returns a dictionary that associates integer representations of each candidate with their maximin score .
252
16
9,945
def computeStrongestPaths ( self , profile , pairwisePreferences ) : cands = profile . candMap . keys ( ) numCands = len ( cands ) # Initialize the two-dimensional dictionary that will hold our strongest paths. strongestPaths = dict ( ) for cand in cands : strongestPaths [ cand ] = dict ( ) for i in range ( 1 , numCands + 1 ) : for j in range ( 1 , numCands + 1 ) : if ( i == j ) : continue if pairwisePreferences [ i ] [ j ] > pairwisePreferences [ j ] [ i ] : strongestPaths [ i ] [ j ] = pairwisePreferences [ i ] [ j ] else : strongestPaths [ i ] [ j ] = 0 for i in range ( 1 , numCands + 1 ) : for j in range ( 1 , numCands + 1 ) : if ( i == j ) : continue for k in range ( 1 , numCands + 1 ) : if ( i == k or j == k ) : continue strongestPaths [ j ] [ k ] = max ( strongestPaths [ j ] [ k ] , min ( strongestPaths [ j ] [ i ] , strongestPaths [ i ] [ k ] ) ) return strongestPaths
Returns a two - dimensional dictionary that associates every pair of candidates cand1 and cand2 with the strongest path from cand1 to cand2 .
278
28
9,946
def computePairwisePreferences ( self , profile ) : cands = profile . candMap . keys ( ) # Initialize the two-dimensional dictionary that will hold our pairwise preferences. pairwisePreferences = dict ( ) for cand in cands : pairwisePreferences [ cand ] = dict ( ) for cand1 in cands : for cand2 in cands : if cand1 != cand2 : pairwisePreferences [ cand1 ] [ cand2 ] = 0 for preference in profile . preferences : wmgMap = preference . wmgMap for cand1 , cand2 in itertools . combinations ( cands , 2 ) : # If either candidate was unranked, we assume that they are lower ranked than all # ranked candidates. if cand1 not in wmgMap . keys ( ) : if cand2 in wmgMap . keys ( ) : pairwisePreferences [ cand2 ] [ cand1 ] += 1 * preference . count elif cand2 not in wmgMap . keys ( ) : if cand1 in wmgMap . keys ( ) : pairwisePreferences [ cand1 ] [ cand2 ] += 1 * preference . count elif wmgMap [ cand1 ] [ cand2 ] == 1 : pairwisePreferences [ cand1 ] [ cand2 ] += 1 * preference . count elif wmgMap [ cand1 ] [ cand2 ] == - 1 : pairwisePreferences [ cand2 ] [ cand1 ] += 1 * preference . count return pairwisePreferences
Returns a two - dimensional dictionary that associates every pair of candidates cand1 and cand2 with number of voters who prefer cand1 to cand2 .
317
29
9,947
def getCandScoresMap ( self , profile ) : cands = profile . candMap . keys ( ) pairwisePreferences = self . computePairwisePreferences ( profile ) strongestPaths = self . computeStrongestPaths ( profile , pairwisePreferences ) # For each candidate, determine how many times p[E,X] >= p[X,E] using a variant of the # Floyd-Warshall algorithm. betterCount = dict ( ) for cand in cands : betterCount [ cand ] = 0 for cand1 in cands : for cand2 in cands : if cand1 == cand2 : continue if strongestPaths [ cand1 ] [ cand2 ] >= strongestPaths [ cand2 ] [ cand1 ] : betterCount [ cand1 ] += 1 return betterCount
Returns a dictionary that associates integer representations of each candidate with the number of other candidates for which her strongest path to the other candidate is greater than the other candidate s stronget path to her .
170
38
9,948
def STVsocwinners ( self , profile ) : ordering = profile . getOrderVectors ( ) prefcounts = profile . getPreferenceCounts ( ) m = profile . numCands if min ( ordering [ 0 ] ) == 0 : startstate = set ( range ( m ) ) else : startstate = set ( range ( 1 , m + 1 ) ) ordering , startstate = self . preprocessing ( ordering , prefcounts , m , startstate ) m_star = len ( startstate ) known_winners = set ( ) # ----------Some statistics-------------- hashtable2 = set ( ) # push the node of start state into the priority queue root = Node ( value = startstate ) stackNode = [ ] stackNode . append ( root ) while stackNode : # ------------pop the current node----------------- node = stackNode . pop ( ) # ------------------------------------------------- state = node . value . copy ( ) # use heuristic to delete all the candidates which satisfy the following condition # goal state 1: if the state set contains only 1 candidate, then stop if len ( state ) == 1 and list ( state ) [ 0 ] not in known_winners : known_winners . add ( list ( state ) [ 0 ] ) continue # goal state 2 (pruning): if the state set is subset of the known_winners set, then stop if state <= known_winners : continue # ----------Compute plurality score for the current remaining candidates-------------- plural_score = self . get_plurality_scores3 ( prefcounts , ordering , state , m_star ) minscore = min ( plural_score . values ( ) ) for to_be_deleted in state : if plural_score [ to_be_deleted ] == minscore : child_state = state . copy ( ) child_state . remove ( to_be_deleted ) tpc = tuple ( sorted ( child_state ) ) if tpc in hashtable2 : continue else : hashtable2 . add ( tpc ) child_node = Node ( value = child_state ) stackNode . append ( child_node ) return sorted ( known_winners )
Returns an integer list that represents all possible winners of a profile under STV rule .
461
17
9,949
def baldwinsoc_winners ( self , profile ) : ordering = profile . getOrderVectors ( ) m = profile . numCands prefcounts = profile . getPreferenceCounts ( ) if min ( ordering [ 0 ] ) == 0 : startstate = set ( range ( m ) ) else : startstate = set ( range ( 1 , m + 1 ) ) wmg = self . getWmg2 ( prefcounts , ordering , startstate , normalize = False ) known_winners = set ( ) # ----------Some statistics-------------- hashtable2 = set ( ) # push the node of start state into the priority queue root = Node ( value = startstate ) stackNode = [ ] stackNode . append ( root ) while stackNode : # ------------pop the current node----------------- node = stackNode . pop ( ) # ------------------------------------------------- state = node . value . copy ( ) # goal state 1: if the state set contains only 1 candidate, then stop if len ( state ) == 1 and list ( state ) [ 0 ] not in known_winners : known_winners . add ( list ( state ) [ 0 ] ) continue # goal state 2 (pruning): if the state set is subset of the known_winners set, then stop if state <= known_winners : continue # ----------Compute plurality score for the current remaining candidates-------------- plural_score = dict ( ) for cand in state : plural_score [ cand ] = 0 for cand1 , cand2 in itertools . permutations ( state , 2 ) : plural_score [ cand1 ] += wmg [ cand1 ] [ cand2 ] # if current state satisfies one of the 3 goal state, continue to the next loop # After using heuristics, generate children and push them into priority queue # frontier = [val for val in known_winners if val in state] + list(set(state) - set(known_winners)) minscore = min ( plural_score . values ( ) ) for to_be_deleted in state : if plural_score [ to_be_deleted ] == minscore : child_state = state . copy ( ) child_state . remove ( to_be_deleted ) tpc = tuple ( sorted ( child_state ) ) if tpc in hashtable2 : continue else : hashtable2 . add ( tpc ) child_node = Node ( value = child_state ) stackNode . append ( child_node ) return sorted ( known_winners )
Returns an integer list that represents all possible winners of a profile under baldwin rule .
536
17
9,950
def getWmg2 ( self , prefcounts , ordering , state , normalize = False ) : # Initialize a new dictionary for our final weighted majority graph. wmgMap = dict ( ) for cand in state : wmgMap [ cand ] = dict ( ) for cand1 , cand2 in itertools . combinations ( state , 2 ) : wmgMap [ cand1 ] [ cand2 ] = 0 wmgMap [ cand2 ] [ cand1 ] = 0 # Go through the wmgMaps and increment the value of each edge in our final graph with the # edges in each of the wmgMaps. We take into account the number of times that the vote # occured. for i in range ( 0 , len ( prefcounts ) ) : for cand1 , cand2 in itertools . combinations ( ordering [ i ] , 2 ) : # -------------------------- wmgMap [ cand1 ] [ cand2 ] += prefcounts [ i ] # By default, we assume that the weighted majority graph should not be normalized. If # desired, we normalize by dividing each edge by the value of the largest edge. if normalize == True : maxEdge = float ( '-inf' ) for cand in wmgMap . keys ( ) : maxEdge = max ( maxEdge , max ( wmgMap [ cand ] . values ( ) ) ) for cand1 in wmgMap . keys ( ) : for cand2 in wmgMap [ cand1 ] . keys ( ) : wmgMap [ cand1 ] [ cand2 ] = float ( wmgMap [ cand1 ] [ cand2 ] ) / maxEdge return wmgMap
Generate a weighted majority graph that represents the whole profile . The function will return a two - dimensional dictionary that associates integer representations of each pair of candidates cand1 and cand2 with the number of times cand1 is ranked above cand2 minus the number of times cand2 is ranked above cand1 .
349
60
9,951
def PluRunOff_single_winner ( self , profile ) : # Currently, we expect the profile to contain complete ordering over candidates. Ties are # allowed however. elecType = profile . getElecType ( ) if elecType != "soc" and elecType != "toc" and elecType != "csv" : print ( "ERROR: unsupported election type" ) exit ( ) # Initialization prefcounts = profile . getPreferenceCounts ( ) len_prefcounts = len ( prefcounts ) rankmaps = profile . getRankMaps ( ) ranking = MechanismPlurality ( ) . getRanking ( profile ) # 1st round: find the top 2 candidates in plurality scores # Compute the 1st-place candidate in plurality scores # print(ranking) max_cand = ranking [ 0 ] [ 0 ] [ 0 ] # Compute the 2nd-place candidate in plurality scores # Automatically using tie-breaking rule--numerically increasing order if len ( ranking [ 0 ] [ 0 ] ) > 1 : second_max_cand = ranking [ 0 ] [ 0 ] [ 1 ] else : second_max_cand = ranking [ 0 ] [ 1 ] [ 0 ] top_2 = [ max_cand , second_max_cand ] # 2nd round: find the candidate with maximum plurality score dict_top2 = { max_cand : 0 , second_max_cand : 0 } for i in range ( len_prefcounts ) : vote_top2 = { key : value for key , value in rankmaps [ i ] . items ( ) if key in top_2 } top_position = min ( vote_top2 . values ( ) ) keys = [ x for x in vote_top2 . keys ( ) if vote_top2 [ x ] == top_position ] for key in keys : dict_top2 [ key ] += prefcounts [ i ] # print(dict_top2) winner = max ( dict_top2 . items ( ) , key = lambda x : x [ 1 ] ) [ 0 ] return winner
Returns a number that associates the winner of a profile under Plurality with Runoff rule .
447
19
9,952
def PluRunOff_cowinners ( self , profile ) : # Currently, we expect the profile to contain complete ordering over candidates. Ties are # allowed however. elecType = profile . getElecType ( ) if elecType != "soc" and elecType != "toc" and elecType != "csv" : print ( "ERROR: unsupported election type" ) exit ( ) # Initialization prefcounts = profile . getPreferenceCounts ( ) len_prefcounts = len ( prefcounts ) rankmaps = profile . getRankMaps ( ) ranking = MechanismPlurality ( ) . getRanking ( profile ) known_winners = set ( ) # 1st round: find the top 2 candidates in plurality scores top_2_combinations = [ ] if len ( ranking [ 0 ] [ 0 ] ) > 1 : for cand1 , cand2 in itertools . combinations ( ranking [ 0 ] [ 0 ] , 2 ) : top_2_combinations . append ( [ cand1 , cand2 ] ) else : max_cand = ranking [ 0 ] [ 0 ] [ 0 ] if len ( ranking [ 0 ] [ 1 ] ) > 1 : for second_max_cand in ranking [ 0 ] [ 1 ] : top_2_combinations . append ( [ max_cand , second_max_cand ] ) else : second_max_cand = ranking [ 0 ] [ 1 ] [ 0 ] top_2_combinations . append ( [ max_cand , second_max_cand ] ) # 2nd round: find the candidate with maximum plurality score for top_2 in top_2_combinations : dict_top2 = { top_2 [ 0 ] : 0 , top_2 [ 1 ] : 0 } for i in range ( len_prefcounts ) : vote_top2 = { key : value for key , value in rankmaps [ i ] . items ( ) if key in top_2 } top_position = min ( vote_top2 . values ( ) ) keys = [ x for x in vote_top2 . keys ( ) if vote_top2 [ x ] == top_position ] for key in keys : dict_top2 [ key ] += prefcounts [ i ] max_value = max ( dict_top2 . values ( ) ) winners = [ y for y in dict_top2 . keys ( ) if dict_top2 [ y ] == max_value ] known_winners = known_winners | set ( winners ) return sorted ( known_winners )
Returns a list that associates all the winners of a profile under Plurality with Runoff rule .
549
20
9,953
def SNTV_winners ( self , profile , K ) : # Currently, we expect the profile to contain complete ordering over candidates. Ties are # allowed however. elecType = profile . getElecType ( ) if elecType != "soc" and elecType != "toc" and elecType != "csv" : print ( "ERROR: unsupported election type" ) exit ( ) m = profile . numCands candScoresMap = MechanismPlurality ( ) . getCandScoresMap ( profile ) if K >= m : return list ( candScoresMap . keys ( ) ) # print(candScoresMap) sorted_items = sorted ( candScoresMap . items ( ) , key = lambda x : x [ 1 ] , reverse = True ) sorted_dict = { key : value for key , value in sorted_items } winners = list ( sorted_dict . keys ( ) ) [ 0 : K ] return winners
Returns a list that associates all the winners of a profile under Single non - transferable vote rule .
203
20
9,954
def Borda_mean_winners ( self , profile ) : n_candidates = profile . numCands prefcounts = profile . getPreferenceCounts ( ) len_prefcounts = len ( prefcounts ) rankmaps = profile . getRankMaps ( ) values = zeros ( [ len_prefcounts , n_candidates ] , dtype = int ) if min ( list ( rankmaps [ 0 ] . keys ( ) ) ) == 0 : delta = 0 else : delta = 1 for i in range ( len_prefcounts ) : for j in range ( delta , n_candidates + delta ) : values [ i ] [ j - delta ] = rankmaps [ i ] [ j ] # print("values=", values) mat0 = self . _build_mat ( values , n_candidates , prefcounts ) borda = [ 0 for i in range ( n_candidates ) ] for i in range ( n_candidates ) : borda [ i ] = sum ( [ mat0 [ i , j ] for j in range ( n_candidates ) ] ) borda_mean = mean ( borda ) bin_winners_list = [ int ( borda [ i ] >= borda_mean ) for i in range ( n_candidates ) ] return bin_winners_list
Returns a list that associates all the winners of a profile under The Borda - mean rule .
296
19
9,955
def apply_t0 ( self , hits ) : if HAVE_NUMBA : apply_t0_nb ( hits . time , hits . dom_id , hits . channel_id , self . _lookup_tables ) else : n = len ( hits ) cal = np . empty ( n ) lookup = self . _calib_by_dom_and_channel for i in range ( n ) : calib = lookup [ hits [ 'dom_id' ] [ i ] ] [ hits [ 'channel_id' ] [ i ] ] cal [ i ] = calib [ 6 ] hits . time += cal return hits
Apply only t0s
133
5
9,956
def _get_file_index_str ( self ) : file_index = str ( self . file_index ) if self . n_digits is not None : file_index = file_index . zfill ( self . n_digits ) return file_index
Create a string out of the current file_index
58
10
9,957
def prepare_blobs ( self ) : self . raw_header = self . extract_header ( ) if self . cache_enabled : self . _cache_offsets ( )
Populate the blobs
38
5
9,958
def extract_header ( self ) : self . log . info ( "Extracting the header" ) raw_header = self . raw_header = defaultdict ( list ) first_line = self . blob_file . readline ( ) first_line = try_decode_string ( first_line ) self . blob_file . seek ( 0 , 0 ) if not first_line . startswith ( str ( 'start_run' ) ) : self . log . warning ( "No header found." ) return raw_header for line in iter ( self . blob_file . readline , '' ) : line = try_decode_string ( line ) line = line . strip ( ) try : tag , value = str ( line ) . split ( ':' ) except ValueError : continue raw_header [ tag ] . append ( str ( value ) . split ( ) ) if line . startswith ( str ( 'end_event:' ) ) : self . _record_offset ( ) if self . _auto_parse and 'physics' in raw_header : parsers = [ p [ 0 ] . lower ( ) for p in raw_header [ 'physics' ] ] self . _register_parsers ( parsers ) return raw_header raise ValueError ( "Incomplete header, no 'end_event' tag found!" )
Create a dictionary with the EVT header information
290
9
9,959
def get_blob ( self , index ) : self . log . info ( "Retrieving blob #{}" . format ( index ) ) if index > len ( self . event_offsets ) - 1 : self . log . info ( "Index not in cache, caching offsets" ) self . _cache_offsets ( index , verbose = False ) self . blob_file . seek ( self . event_offsets [ index ] , 0 ) blob = self . _create_blob ( ) if blob is None : self . log . info ( "Empty blob created..." ) raise IndexError else : self . log . debug ( "Applying parsers..." ) for parser in self . parsers : parser ( blob ) self . log . debug ( "Returning the blob" ) return blob
Return a blob with the event at the given index
169
10
9,960
def process ( self , blob = None ) : try : blob = self . get_blob ( self . index ) except IndexError : self . log . info ( "Got an IndexError, trying the next file" ) if ( self . basename or self . filenames ) and self . file_index < self . index_stop : self . file_index += 1 self . log . info ( "Now at file_index={}" . format ( self . file_index ) ) self . _reset ( ) self . blob_file . close ( ) self . log . info ( "Resetting blob index to 0" ) self . index = 0 file_index = self . _get_file_index_str ( ) if self . filenames : self . filename = self . filenames [ self . file_index - 1 ] elif self . basename : self . filename = "{}{}{}.evt" . format ( self . basename , file_index , self . suffix ) self . log . info ( "Next filename: {}" . format ( self . filename ) ) self . print ( "Opening {0}" . format ( self . filename ) ) self . open_file ( self . filename ) self . prepare_blobs ( ) try : blob = self . get_blob ( self . index ) except IndexError : self . log . warning ( "No blob found in file {}" . format ( self . filename ) ) else : return blob self . log . info ( "No files left, terminating the pipeline" ) raise StopIteration self . index += 1 return blob
Pump the next blob to the modules
341
8
9,961
def _cache_offsets ( self , up_to_index = None , verbose = True ) : if not up_to_index : if verbose : self . print ( "Caching event file offsets, this may take a bit." ) self . blob_file . seek ( 0 , 0 ) self . event_offsets = [ ] if not self . raw_header : self . event_offsets . append ( 0 ) else : self . blob_file . seek ( self . event_offsets [ - 1 ] , 0 ) for line in iter ( self . blob_file . readline , '' ) : line = try_decode_string ( line ) if line . startswith ( 'end_event:' ) : self . _record_offset ( ) if len ( self . event_offsets ) % 100 == 0 : if verbose : print ( '.' , end = '' ) sys . stdout . flush ( ) if up_to_index and len ( self . event_offsets ) >= up_to_index + 1 : return self . event_offsets . pop ( ) # get rid of the last entry if not up_to_index : self . whole_file_cached = True self . print ( "\n{0} events indexed." . format ( len ( self . event_offsets ) ) )
Cache all event offsets .
289
5
9,962
def _record_offset ( self ) : offset = self . blob_file . tell ( ) self . event_offsets . append ( offset )
Stores the current file pointer position
31
7
9,963
def _create_blob ( self ) : blob = None for line in self . blob_file : line = try_decode_string ( line ) line = line . strip ( ) if line == '' : self . log . info ( "Ignoring empty line..." ) continue if line . startswith ( 'end_event:' ) and blob : blob [ 'raw_header' ] = self . raw_header return blob try : tag , values = line . split ( ':' ) except ValueError : self . log . warning ( "Ignoring corrupt line: {}" . format ( line ) ) continue try : values = tuple ( split ( values . strip ( ) , callback = float ) ) except ValueError : self . log . info ( "Empty value: {}" . format ( values ) ) if line . startswith ( 'start_event:' ) : blob = Blob ( ) blob [ tag ] = tuple ( int ( v ) for v in values ) continue if tag not in blob : blob [ tag ] = [ ] blob [ tag ] . append ( values )
Parse the next event from the current file position
229
10
9,964
def runserver ( project_name ) : DIR = os . listdir ( project_name ) if 'settings.py' not in DIR : raise NotImplementedError ( 'No file called: settings.py found in %s' % project_name ) CGI_BIN_FOLDER = os . path . join ( project_name , 'cgi' , 'cgi-bin' ) CGI_FOLDER = os . path . join ( project_name , 'cgi' ) if not os . path . exists ( CGI_BIN_FOLDER ) : os . makedirs ( CGI_BIN_FOLDER ) os . chdir ( CGI_FOLDER ) subprocess . Popen ( "python -m http.server --cgi 8000" )
Runs a python cgi server in a subprocess .
168
12
9,965
def getUtility ( self , decision , sample , aggregationMode = "avg" ) : utilities = self . getUtilities ( decision , sample ) if aggregationMode == "avg" : utility = numpy . mean ( utilities ) elif aggregationMode == "min" : utility = min ( utilities ) elif aggregationMode == "max" : utility = max ( utilities ) else : print ( "ERROR: aggregation mode not recognized" ) exit ( ) return utility
Get the utility of a given decision given a preference .
98
11
9,966
def getUtilities ( self , decision , orderVector ) : scoringVector = self . getScoringVector ( orderVector ) utilities = [ ] for alt in decision : altPosition = orderVector . index ( alt ) utility = float ( scoringVector [ altPosition ] ) if self . isLoss == True : utility = - 1 * utility utilities . append ( utility ) return utilities
Returns a floats that contains the utilities of every candidate in the decision .
79
14
9,967
def getUtilities ( self , decision , binaryRelations ) : m = len ( binaryRelations ) utilities = [ ] for cand in decision : tops = [ cand - 1 ] index = 0 while index < len ( tops ) : s = tops [ index ] for j in range ( m ) : if j == s : continue if binaryRelations [ j ] [ s ] > 0 : if j not in tops : tops . append ( j ) index += 1 if len ( tops ) <= self . k : if self . isLoss == False : utilities . append ( 1.0 ) elif self . isLoss == True : utilities . append ( - 1.0 ) else : utilities . append ( 0.0 ) return utilities
Returns a floats that contains the utilities of every candidate in the decision . This was adapted from code written by Lirong Xia .
152
26
9,968
def db_credentials ( self ) : try : username = self . config . get ( 'DB' , 'username' ) password = self . config . get ( 'DB' , 'password' ) except Error : username = input ( "Please enter your KM3NeT DB username: " ) password = getpass . getpass ( "Password: " ) return username , password
Return username and password for the KM3NeT WebDB .
81
13
9,969
def get_path ( src ) : # pragma: no cover res = None while not res : if res is False : print ( colored ( 'You must provide a path to an existing directory!' , 'red' ) ) print ( 'You need a local clone or release of (a fork of) ' 'https://github.com/{0}' . format ( src ) ) res = input ( colored ( 'Local path to {0}: ' . format ( src ) , 'green' , attrs = [ 'blink' ] ) ) if res and Path ( res ) . exists ( ) : return Path ( res ) . resolve ( ) res = False
Prompts the user to input a local path .
140
11
9,970
def execute_all ( self ) : for workflow_id in self . workflows : if self . workflows [ workflow_id ] . online : for interval in self . workflows [ workflow_id ] . requested_intervals : logging . info ( "Executing workflow {} over interval {}" . format ( workflow_id , interval ) ) self . workflows [ workflow_id ] . execute ( interval )
Execute all workflows
86
5
9,971
def execute ( self , sources , sink , interval , alignment_stream = None ) : if not isinstance ( interval , TimeInterval ) : raise TypeError ( 'Expected TimeInterval, got {}' . format ( type ( interval ) ) ) # logging.info(self.message(interval)) if interval . end > sink . channel . up_to_timestamp : raise StreamNotAvailableError ( sink . channel . up_to_timestamp ) required_intervals = TimeIntervals ( [ interval ] ) - sink . calculated_intervals if not required_intervals . is_empty : document_count = 0 for interval in required_intervals : for stream_instance in self . _execute ( sources = sources , alignment_stream = alignment_stream , interval = interval ) : sink . writer ( stream_instance ) document_count += 1 sink . calculated_intervals += interval required_intervals = TimeIntervals ( [ interval ] ) - sink . calculated_intervals if not required_intervals . is_empty : # raise ToolExecutionError(required_intervals) logging . error ( "{} execution error for time interval {} on stream {}" . format ( self . name , interval , sink ) ) if not document_count : logging . debug ( "{} did not produce any data for time interval {} on stream {}" . format ( self . name , interval , sink ) ) self . write_to_history ( interval = interval , tool = self . name , document_count = document_count )
Execute the tool over the given time interval . If an alignment stream is given the output instances will be aligned to this stream
324
25
9,972
def create_stream ( self , stream_id , sandbox = None ) : if stream_id in self . streams : raise StreamAlreadyExistsError ( "Stream with id '{}' already exists" . format ( stream_id ) ) if sandbox is not None : raise ValueError ( "Cannot use sandboxes with memory streams" ) stream = Stream ( channel = self , stream_id = stream_id , calculated_intervals = None , sandbox = None ) self . streams [ stream_id ] = stream self . data [ stream_id ] = StreamInstanceCollection ( ) return stream
Must be overridden by deriving classes must create the stream according to the tool and return its unique identifier stream_id
125
24
9,973
def purge_all ( self , remove_definitions = False ) : for stream_id in list ( self . streams . keys ( ) ) : self . purge_stream ( stream_id , remove_definition = remove_definitions )
Clears all streams in the channel - use with caution!
50
12
9,974
def update_state ( self , up_to_timestamp ) : for stream_id in self . streams : self . streams [ stream_id ] . calculated_intervals = TimeIntervals ( [ ( MIN_DATE , up_to_timestamp ) ] ) self . up_to_timestamp = up_to_timestamp
Call this function to ensure that the channel is up to date at the time of timestamp . I . e . all the streams that have been created before or at that timestamp are calculated exactly until up_to_timestamp .
73
45
9,975
def compile_regex ( self , pattern , flags = 0 ) : pattern_re = regex . compile ( '(?P<substr>%\{(?P<fullname>(?P<patname>\w+)(?::(?P<subname>\w+))?)\})' ) while 1 : matches = [ md . groupdict ( ) for md in pattern_re . finditer ( pattern ) ] if len ( matches ) == 0 : break for md in matches : if md [ 'patname' ] in self . pattern_dict : if md [ 'subname' ] : # TODO error if more than one occurance if '(?P<' in self . pattern_dict [ md [ 'patname' ] ] : # this is not part of the original logstash implementation # but it might be useful to be able to replace the # group name used in the pattern repl = regex . sub ( '\(\?P<(\w+)>' , '(?P<%s>' % md [ 'subname' ] , self . pattern_dict [ md [ 'patname' ] ] , 1 ) else : repl = '(?P<%s>%s)' % ( md [ 'subname' ] , self . pattern_dict [ md [ 'patname' ] ] ) else : repl = self . pattern_dict [ md [ 'patname' ] ] # print "Replacing %s with %s" %(md['substr'], repl) pattern = pattern . replace ( md [ 'substr' ] , repl ) else : # print('patname not found') # maybe missing path entry or missing pattern file? return # print 'pattern: %s' % pattern return regex . compile ( pattern , flags )
Compile regex from pattern and pattern_dict
380
9
9,976
def _load_patterns ( self , folders , pattern_dict = None ) : if pattern_dict is None : pattern_dict = { } for folder in folders : for file in os . listdir ( folder ) : if regex . match ( '^[\w-]+$' , file ) : self . _load_pattern_file ( os . path . join ( folder , file ) , pattern_dict ) return pattern_dict
Load all pattern from all the files in folders
93
9
9,977
def load_pkl ( filenames ) : if not isinstance ( filenames , ( list , tuple ) ) : filenames = [ filenames ] times = [ ] for name in filenames : name = str ( name ) with open ( name , 'rb' ) as file : loaded_obj = pickle . load ( file ) if not isinstance ( loaded_obj , Times ) : raise TypeError ( "At least one loaded object is not a Times data object." ) times . append ( loaded_obj ) return times if len ( times ) > 1 else times [ 0 ]
Unpickle file contents .
128
6
9,978
async def retrieve ( self , url , * * kwargs ) : try : async with self . websession . request ( 'GET' , url , * * kwargs ) as res : if res . status != 200 : raise Exception ( "Could not retrieve information from API" ) if res . content_type == 'application/json' : return await res . json ( ) return await res . text ( ) except aiohttp . ClientError as err : logging . error ( err )
Issue API requests .
104
4
9,979
def _to_number ( cls , string ) : try : if float ( string ) - int ( string ) == 0 : return int ( string ) return float ( string ) except ValueError : try : return float ( string ) except ValueError : return string
Convert string to int or float .
54
8
9,980
async def stations ( self ) : data = await self . retrieve ( API_DISTRITS ) Station = namedtuple ( 'Station' , [ 'latitude' , 'longitude' , 'idAreaAviso' , 'idConselho' , 'idDistrito' , 'idRegiao' , 'globalIdLocal' , 'local' ] ) _stations = [ ] for station in data [ 'data' ] : _station = Station ( self . _to_number ( station [ 'latitude' ] ) , self . _to_number ( station [ 'longitude' ] ) , station [ 'idAreaAviso' ] , station [ 'idConcelho' ] , station [ 'idDistrito' ] , station [ 'idRegiao' ] , station [ 'globalIdLocal' ] // 100 * 100 , station [ 'local' ] , ) _stations . append ( _station ) return _stations
Retrieve stations .
206
4
9,981
async def weather_type_classe ( self ) : data = await self . retrieve ( url = API_WEATHER_TYPE ) self . weather_type = dict ( ) for _type in data [ 'data' ] : self . weather_type [ _type [ 'idWeatherType' ] ] = _type [ 'descIdWeatherTypePT' ] return self . weather_type
Retrieve translation for weather type .
83
7
9,982
async def wind_type_classe ( self ) : data = await self . retrieve ( url = API_WIND_TYPE ) self . wind_type = dict ( ) for _type in data [ 'data' ] : self . wind_type [ int ( _type [ 'classWindSpeed' ] ) ] = _type [ 'descClassWindSpeedDailyPT' ] return self . wind_type
Retrieve translation for wind type .
86
7
9,983
def register ( self , plugin ) : for listener in plugin . listeners : self . listeners [ listener ] . add ( plugin ) self . plugins . add ( plugin ) plugin . messenger = self . messages plugin . start ( )
Add the plugin to our set of listeners for each message that it listens to tell it to use our messages Queue for communication and start it up .
46
30
9,984
def start ( self ) : self . recieve ( 'APP_START' ) self . alive = True while self . alive : message , payload = self . messages . get ( ) if message == 'APP_STOP' : for plugin in self . plugins : plugin . recieve ( 'SHUTDOWN' ) self . alive = False else : self . recieve ( message , payload )
Send APP_START to any plugins that listen for it and loop around waiting for messages and sending them to their listening plugins until it s time to shutdown .
83
32
9,985
def choose ( self , palette ) : try : self . _cycler = cycle ( self . colours [ palette ] ) except KeyError : raise KeyError ( "Chose one of the following colour palettes: {0}" . format ( self . available ) )
Pick a palette
55
3
9,986
def refresh_styles ( self ) : import matplotlib . pyplot as plt self . colours = { } for style in plt . style . available : try : style_colours = plt . style . library [ style ] [ 'axes.prop_cycle' ] self . colours [ style ] = [ c [ 'color' ] for c in list ( style_colours ) ] except KeyError : continue self . colours [ 'km3pipe' ] = [ "#ff7869" , "#4babe1" , "#96ad3e" , "#e4823d" , "#5d72b2" , "#e2a3c2" , "#fd9844" , "#e480e7" ]
Load all available styles
159
4
9,987
def get_file_object ( username , password , utc_start = None , utc_stop = None ) : if not utc_start : utc_start = datetime . now ( ) if not utc_stop : utc_stop = utc_start + timedelta ( days = 1 ) logging . info ( "Downloading schedules for username [%s] in range [%s] to " "[%s]." % ( username , utc_start , utc_stop ) ) replacements = { 'start_time' : utc_start . strftime ( '%Y-%m-%dT%H:%M:%SZ' ) , 'stop_time' : utc_stop . strftime ( '%Y-%m-%dT%H:%M:%SZ' ) } soap_message_xml = ( soap_message_xml_template % replacements ) authinfo = urllib2 . HTTPDigestAuthHandler ( ) authinfo . add_password ( realm , url , username , password ) try : request = urllib2 . Request ( url , soap_message_xml , request_headers ) response = urllib2 . build_opener ( authinfo ) . open ( request ) if response . headers [ 'Content-Encoding' ] == 'gzip' : response = GzipStream ( response ) except : logging . exception ( "Could not acquire connection to Schedules Direct." ) raise return response
Make the connection . Return a file - like object .
322
11
9,988
def process_file_object ( file_obj , importer , progress ) : logging . info ( "Processing schedule data." ) try : handler = XmlCallbacks ( importer , progress ) parser = sax . make_parser ( ) parser . setContentHandler ( handler ) parser . setErrorHandler ( handler ) parser . parse ( file_obj ) except : logging . exception ( "Parse failed." ) raise logging . info ( "Schedule data processed." )
Parse the data using the connected file - like object .
99
12
9,989
def parse_schedules ( username , password , importer , progress , utc_start = None , utc_stop = None ) : file_obj = get_file_object ( username , password , utc_start , utc_stop ) process_file_object ( file_obj , importer , progress )
A utility function to marry the connecting and reading functions .
70
11
9,990
def km3h5concat ( input_files , output_file , n_events = None , * * kwargs ) : from km3pipe import Pipeline # noqa from km3pipe . io import HDF5Pump , HDF5Sink # noqa pipe = Pipeline ( ) pipe . attach ( HDF5Pump , filenames = input_files , * * kwargs ) pipe . attach ( StatusBar , every = 250 ) pipe . attach ( HDF5Sink , filename = output_file , * * kwargs ) pipe . drain ( n_events )
Concatenate KM3HDF5 files via pipeline .
129
13
9,991
def get_data ( stream , parameters , fmt ) : sds = kp . db . StreamDS ( ) if stream not in sds . streams : log . error ( "Stream '{}' not found in the database." . format ( stream ) ) return params = { } if parameters : for parameter in parameters : if '=' not in parameter : log . error ( "Invalid parameter syntax '{}'\n" "The correct syntax is 'parameter=value'" . format ( parameter ) ) continue key , value = parameter . split ( '=' ) params [ key ] = value data = sds . get ( stream , fmt , * * params ) if data is not None : with pd . option_context ( 'display.max_rows' , None , 'display.max_columns' , None ) : print ( data ) else : sds . help ( stream )
Retrieve data for given stream and parameters or None if not found
189
13
9,992
def available_streams ( ) : sds = kp . db . StreamDS ( ) print ( "Available streams: " ) print ( ', ' . join ( sorted ( sds . streams ) ) )
Show a short list of available streams .
44
8
9,993
def upload_runsummary ( csv_filename , dryrun = False ) : print ( "Checking '{}' for consistency." . format ( csv_filename ) ) if not os . path . exists ( csv_filename ) : log . critical ( "{} -> file not found." . format ( csv_filename ) ) return try : df = pd . read_csv ( csv_filename , sep = '\t' ) except pd . errors . EmptyDataError as e : log . error ( e ) return cols = set ( df . columns ) if not REQUIRED_COLUMNS . issubset ( cols ) : log . error ( "Missing columns: {}." . format ( ', ' . join ( str ( c ) for c in REQUIRED_COLUMNS - cols ) ) ) return parameters = cols - REQUIRED_COLUMNS if len ( parameters ) < 1 : log . error ( "No parameter columns found." ) return if len ( df ) == 0 : log . critical ( "Empty dataset." ) return print ( "Found data for parameters: {}." . format ( ', ' . join ( str ( c ) for c in parameters ) ) ) print ( "Converting CSV data into JSON" ) if dryrun : log . warn ( "Dryrun: adding 'TEST_' prefix to parameter names" ) prefix = "TEST_" else : prefix = "" data = convert_runsummary_to_json ( df , prefix = prefix ) print ( "We have {:.3f} MB to upload." . format ( len ( data ) / 1024 ** 2 ) ) print ( "Requesting database session." ) db = kp . db . DBManager ( ) # noqa if kp . db . we_are_in_lyon ( ) : session_cookie = "sid=_kmcprod_134.158_lyo7783844001343100343mcprod1223user" # noqa else : session_cookie = kp . config . Config ( ) . get ( 'DB' , 'session_cookie' ) if session_cookie is None : raise SystemExit ( "Could not restore DB session." ) log . debug ( "Using the session cookie: {}" . format ( session_cookie ) ) cookie_key , sid = session_cookie . split ( '=' ) print ( "Uploading the data to the database." ) r = requests . post ( RUNSUMMARY_URL , cookies = { cookie_key : sid } , files = { 'datafile' : data } ) if r . status_code == 200 : log . debug ( "POST request status code: {}" . format ( r . status_code ) ) print ( "Database response:" ) db_answer = json . loads ( r . text ) for key , value in db_answer . items ( ) : print ( " -> {}: {}" . format ( key , value ) ) if db_answer [ 'Result' ] == 'OK' : print ( "Upload successful." ) else : log . critical ( "Something went wrong." ) else : log . error ( "POST request status code: {}" . format ( r . status_code ) ) log . critical ( "Something went wrong..." ) return
Reads the CSV file and uploads its contents to the runsummary table
704
16
9,994
def convert_runsummary_to_json ( df , comment = 'Uploaded via km3pipe.StreamDS' , prefix = 'TEST_' ) : data_field = [ ] comment += ", by {}" . format ( getpass . getuser ( ) ) for det_id , det_data in df . groupby ( 'det_id' ) : runs_field = [ ] data_field . append ( { "DetectorId" : det_id , "Runs" : runs_field } ) for run , run_data in det_data . groupby ( 'run' ) : parameters_field = [ ] runs_field . append ( { "Run" : int ( run ) , "Parameters" : parameters_field } ) parameter_dict = { } for row in run_data . itertuples ( ) : for parameter_name in run_data . columns : if parameter_name in REQUIRED_COLUMNS : continue if parameter_name not in parameter_dict : entry = { 'Name' : prefix + parameter_name , 'Data' : [ ] } parameter_dict [ parameter_name ] = entry data_value = getattr ( row , parameter_name ) try : data_value = float ( data_value ) except ValueError as e : log . critical ( "Data values has to be floats!" ) raise ValueError ( e ) value = { 'S' : str ( getattr ( row , 'source' ) ) , 'D' : data_value } parameter_dict [ parameter_name ] [ 'Data' ] . append ( value ) for parameter_data in parameter_dict . values ( ) : parameters_field . append ( parameter_data ) data_to_upload = { "Comment" : comment , "Data" : data_field } file_data_to_upload = json . dumps ( data_to_upload ) return file_data_to_upload
Convert a Pandas DataFrame with runsummary to JSON for DB upload
413
16
9,995
def calcAcceptanceRatio ( self , V , W ) : acceptanceRatio = 1.0 for comb in itertools . combinations ( V , 2 ) : #Check if comb[0] is ranked before comb[1] in V and W vIOverJ = 1 wIOverJ = 1 if V . index ( comb [ 0 ] ) > V . index ( comb [ 1 ] ) : vIOverJ = 0 if W . index ( comb [ 0 ] ) > W . index ( comb [ 1 ] ) : wIOverJ = 0 acceptanceRatio = acceptanceRatio * self . phi ** ( self . wmg [ comb [ 0 ] ] [ comb [ 1 ] ] * ( vIOverJ - wIOverJ ) ) return acceptanceRatio
Given a order vector V and a proposed order vector W calculate the acceptance ratio for changing to W when using MCMC .
166
24
9,996
def getNextSample ( self , V ) : # Select a random alternative in V to switch with its adacent alternatives. randPos = random . randint ( 0 , len ( V ) - 2 ) W = copy . deepcopy ( V ) d = V [ randPos ] c = V [ randPos + 1 ] W [ randPos ] = c W [ randPos + 1 ] = d # Check whether we should change to the new ranking. prMW = 1 prMV = 1 prob = min ( 1.0 , ( prMW / prMV ) * pow ( self . phi , self . wmg [ d ] [ c ] ) ) / 2 if random . random ( ) <= prob : V = W return V
Generate the next sample by randomly flipping two adjacent candidates .
155
12
9,997
def getNextSample ( self , V ) : positions = range ( 0 , len ( self . wmg ) ) randPoss = random . sample ( positions , self . shuffleSize ) flipSet = copy . deepcopy ( randPoss ) randPoss . sort ( ) W = copy . deepcopy ( V ) for j in range ( 0 , self . shuffleSize ) : W [ randPoss [ j ] ] = V [ flipSet [ j ] ] # Check whether we should change to the new ranking. prMW = 1.0 prMV = 1.0 acceptanceRatio = self . calcAcceptanceRatio ( V , W ) prob = min ( 1.0 , ( prMW / prMV ) * acceptanceRatio ) if random . random ( ) <= prob : V = W return V
Generate the next sample by randomly shuffling candidates .
173
11
9,998
def getNextSample ( self , V ) : phi = self . phi wmg = self . wmg W = [ ] W . append ( V [ 0 ] ) for j in range ( 2 , len ( V ) + 1 ) : randomSelect = random . random ( ) threshold = 0.0 denom = 1.0 for k in range ( 1 , j ) : denom = denom + phi ** k for k in range ( 1 , j + 1 ) : numerator = phi ** ( j - k ) threshold = threshold + numerator / denom if randomSelect <= threshold : W . insert ( k - 1 , V [ j - 1 ] ) break # Check whether we should change to the new ranking. acceptanceRatio = self . calcAcceptanceRatio ( V , W ) prob = min ( 1.0 , acceptanceRatio ) if random . random ( ) <= prob : V = W return V
We generate a new ranking based on a Mallows - based jumping distribution . The algorithm is described in Bayesian Ordinal Peer Grading by Raman and Joachims .
198
35
9,999
def getNextSample ( self , V ) : W , WProb = self . drawRankingPlakettLuce ( V ) VProb = self . calcProbOfVFromW ( V , W ) acceptanceRatio = self . calcAcceptanceRatio ( V , W ) prob = min ( 1.0 , acceptanceRatio * ( VProb / WProb ) ) if random . random ( ) <= prob : V = W return V
Given a ranking over the candidates generate a new ranking by assigning each candidate at position i a Plakett - Luce weight of phi^i and draw a new ranking .
99
36