idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
43,600
def list_market_profit_and_loss ( self , market_ids , include_settled_bets = None , include_bsp_bets = None , net_of_commission = None , session = None , lightweight = None ) : params = clean_locals ( locals ( ) ) method = '%s%s' % ( self . URI , 'listMarketProfitAndLoss' ) ( response , elapsed_time ) = self . request ( method , params , session ) return self . process_response ( response , resources . MarketProfitLoss , elapsed_time , lightweight )
Retrieve profit and loss for a given list of OPEN markets .
43,601
def place_orders ( self , market_id , instructions , customer_ref = None , market_version = None , customer_strategy_ref = None , async_ = None , session = None , lightweight = None ) : params = clean_locals ( locals ( ) ) method = '%s%s' % ( self . URI , 'placeOrders' ) ( response , elapsed_time ) = self . request ( method , params , session ) return self . process_response ( response , resources . PlaceOrders , elapsed_time , lightweight )
Place new orders into market .
43,602
def serialise ( self ) : return { 'marketId' : self . market_id , 'totalAvailable' : None , 'isMarketDataDelayed' : None , 'lastMatchTime' : None , 'betDelay' : self . market_definition . get ( 'betDelay' ) , 'version' : self . market_definition . get ( 'version' ) , 'complete' : self . market_definition . get ( 'complete' ) , 'runnersVoidable' : self . market_definition . get ( 'runnersVoidable' ) , 'totalMatched' : self . total_matched , 'status' : self . market_definition . get ( 'status' ) , 'bspReconciled' : self . market_definition . get ( 'bspReconciled' ) , 'crossMatching' : self . market_definition . get ( 'crossMatching' ) , 'inplay' : self . market_definition . get ( 'inPlay' ) , 'numberOfWinners' : self . market_definition . get ( 'numberOfWinners' ) , 'numberOfRunners' : len ( self . market_definition . get ( 'runners' ) ) , 'numberOfActiveRunners' : self . market_definition . get ( 'numberOfActiveRunners' ) , 'runners' : [ runner . serialise ( self . market_definition_runner_dict [ ( runner . selection_id , runner . handicap ) ] ) for runner in self . runners ] , 'publishTime' : self . publish_time , 'priceLadderDefinition' : self . market_definition . get ( 'priceLadderDefinition' ) , 'keyLineDescription' : self . market_definition . get ( 'keyLineDefinition' ) , 'marketDefinition' : self . market_definition , }
Creates standard market book json response will error if EX_MARKET_DEF not incl .
43,603
def list_race_details ( self , meeting_ids = None , race_ids = None , session = None , lightweight = None ) : params = clean_locals ( locals ( ) ) method = '%s%s' % ( self . URI , 'listRaceDetails' ) ( response , elapsed_time ) = self . request ( method , params , session ) return self . process_response ( response , resources . RaceDetails , elapsed_time , lightweight )
Search for races to get their details .
43,604
def list_available_events ( self , event_ids = None , event_type_ids = None , event_status = None , session = None , lightweight = None ) : params = clean_locals ( locals ( ) ) method = '%s%s' % ( self . URI , 'listAvailableEvents' ) ( response , elapsed_time ) = self . request ( method , params , session ) return self . process_response ( response , resources . AvailableEvent , elapsed_time , lightweight )
Search for events that have live score data available .
43,605
def list_scores ( self , update_keys , session = None , lightweight = None ) : params = clean_locals ( locals ( ) ) method = '%s%s' % ( self . URI , 'listScores' ) ( response , elapsed_time ) = self . request ( method , params , session ) return self . process_response ( response , resources . Score , elapsed_time , lightweight )
Returns a list of current scores for the given events .
43,606
def list_incidents ( self , update_keys , session = None , lightweight = None ) : params = clean_locals ( locals ( ) ) method = '%s%s' % ( self . URI , 'listIncidents' ) ( response , elapsed_time ) = self . request ( method , params , session ) return self . process_response ( response , resources . Incidents , elapsed_time , lightweight )
Returns a list of incidents for the given events .
43,607
def get_event_timeline ( self , event_id , session = None , lightweight = None ) : url = '%s%s' % ( self . url , 'eventTimeline' ) params = { 'eventId' : event_id , 'alt' : 'json' , 'regionCode' : 'UK' , 'locale' : 'en_GB' } ( response , elapsed_time ) = self . request ( params = params , session = session , url = url ) return self . process_response ( response , resources . EventTimeline , elapsed_time , lightweight )
Returns event timeline for event id provided .
43,608
def get_event_timelines ( self , event_ids , session = None , lightweight = None ) : url = '%s%s' % ( self . url , 'eventTimelines' ) params = { 'eventIds' : ',' . join ( str ( x ) for x in event_ids ) , 'alt' : 'json' , 'regionCode' : 'UK' , 'locale' : 'en_GB' } ( response , elapsed_time ) = self . request ( params = params , session = session , url = url ) return self . process_response ( response , resources . EventTimeline , elapsed_time , lightweight )
Returns a list of event timelines based on event id s supplied .
43,609
def get_scores ( self , event_ids , session = None , lightweight = None ) : url = '%s%s' % ( self . url , 'scores' ) params = { 'eventIds' : ',' . join ( str ( x ) for x in event_ids ) , 'alt' : 'json' , 'regionCode' : 'UK' , 'locale' : 'en_GB' } ( response , elapsed_time ) = self . request ( params = params , session = session , url = url ) return self . process_response ( response , resources . Scores , elapsed_time , lightweight )
Returns a list of scores based on event id s supplied .
43,610
def create_stream ( self , unique_id = 0 , listener = None , timeout = 11 , buffer_size = 1024 , description = 'BetfairSocket' , host = None ) : listener = listener if listener else BaseListener ( ) return BetfairStream ( unique_id , listener , app_key = self . client . app_key , session_token = self . client . session_token , timeout = timeout , buffer_size = buffer_size , description = description , host = host , )
Creates BetfairStream .
43,611
def get_my_data ( self , session = None ) : params = clean_locals ( locals ( ) ) method = 'GetMyData' ( response , elapsed_time ) = self . request ( method , params , session ) return response
Returns a list of data descriptions for data which has been purchased by the signed in user .
43,612
def get_data_size ( self , sport , plan , from_day , from_month , from_year , to_day , to_month , to_year , event_id = None , event_name = None , market_types_collection = None , countries_collection = None , file_type_collection = None , session = None ) : params = clean_locals ( locals ( ) ) method = 'GetAdvBasketDataSize' ( response , elapsed_time ) = self . request ( method , params , session ) return response
Returns a dictionary of file count and combines size files .
43,613
def login ( self , session = None ) : session = session or self . client . session try : response = session . get ( self . login_url ) except ConnectionError : raise APIError ( None , self . login_url , None , 'ConnectionError' ) except Exception as e : raise APIError ( None , self . login_url , None , e ) app_key = re . findall ( r , response . text ) if app_key : self . app_key = app_key [ 0 ] else : raise RaceCardError ( "Unable to find appKey" )
Parses app key from betfair exchange site .
43,614
def get_race_card ( self , market_ids , data_entries = None , session = None , lightweight = None ) : if not self . app_key : raise RaceCardError ( "You need to login before requesting a race_card\n" "APIClient.race_card.login()" ) params = self . create_race_card_req ( market_ids , data_entries ) ( response , elapsed_time ) = self . request ( params = params , session = session ) return self . process_response ( response , resources . RaceCard , elapsed_time , lightweight )
Returns a list of race cards based on market ids provided .
43,615
def on_data ( self , raw_data ) : try : data = json . loads ( raw_data ) except ValueError : logger . error ( 'value error: %s' % raw_data ) return unique_id = data . get ( 'id' ) if self . _error_handler ( data , unique_id ) : return False operation = data [ 'op' ] if operation == 'connection' : self . _on_connection ( data , unique_id ) elif operation == 'status' : self . _on_status ( data , unique_id ) elif operation in [ 'mcm' , 'ocm' ] : if self . stream_unique_id not in [ unique_id , 'HISTORICAL' ] : logger . warning ( 'Unwanted data received from uniqueId: %s, expecting: %s' % ( unique_id , self . stream_unique_id ) ) return self . _on_change_message ( data , unique_id )
Called when raw data is received from connection . Override this method if you wish to manually handle the stream data
43,616
def _on_connection ( self , data , unique_id ) : if unique_id is None : unique_id = self . stream_unique_id self . connection_id = data . get ( 'connectionId' ) logger . info ( '[Connect: %s]: connection_id: %s' % ( unique_id , self . connection_id ) )
Called on collection operation
43,617
def _on_status ( data , unique_id ) : status_code = data . get ( 'statusCode' ) logger . info ( '[Subscription: %s]: %s' % ( unique_id , status_code ) )
Called on status operation
43,618
def _error_handler ( data , unique_id ) : if data . get ( 'statusCode' ) == 'FAILURE' : logger . error ( '[Subscription: %s] %s: %s' % ( unique_id , data . get ( 'errorCode' ) , data . get ( 'errorMessage' ) ) ) if data . get ( 'connectionClosed' ) : return True if data . get ( 'status' ) : logger . warning ( '[Subscription: %s] status: %s' % ( unique_id , data [ 'status' ] ) )
Called when data first received
43,619
def stop ( self ) : self . _running = False if self . _socket is None : return try : self . _socket . shutdown ( socket . SHUT_RDWR ) self . _socket . close ( ) except socket . error : pass self . _socket = None
Stops read loop and closes socket if it has been created .
43,620
def authenticate ( self ) : unique_id = self . new_unique_id ( ) message = { 'op' : 'authentication' , 'id' : unique_id , 'appKey' : self . app_key , 'session' : self . session_token , } self . _send ( message ) return unique_id
Authentication request .
43,621
def heartbeat ( self ) : unique_id = self . new_unique_id ( ) message = { 'op' : 'heartbeat' , 'id' : unique_id , } self . _send ( message ) return unique_id
Heartbeat request to keep session alive .
43,622
def subscribe_to_markets ( self , market_filter , market_data_filter , initial_clk = None , clk = None , conflate_ms = None , heartbeat_ms = None , segmentation_enabled = True ) : unique_id = self . new_unique_id ( ) message = { 'op' : 'marketSubscription' , 'id' : unique_id , 'marketFilter' : market_filter , 'marketDataFilter' : market_data_filter , 'initialClk' : initial_clk , 'clk' : clk , 'conflateMs' : conflate_ms , 'heartbeatMs' : heartbeat_ms , 'segmentationEnabled' : segmentation_enabled , } if initial_clk and clk : self . listener . stream_unique_id = unique_id else : self . listener . register_stream ( unique_id , 'marketSubscription' ) self . _send ( message ) return unique_id
Market subscription request .
43,623
def subscribe_to_orders ( self , order_filter = None , initial_clk = None , clk = None , conflate_ms = None , heartbeat_ms = None , segmentation_enabled = True ) : unique_id = self . new_unique_id ( ) message = { 'op' : 'orderSubscription' , 'id' : unique_id , 'orderFilter' : order_filter , 'initialClk' : initial_clk , 'clk' : clk , 'conflateMs' : conflate_ms , 'heartbeatMs' : heartbeat_ms , 'segmentationEnabled' : segmentation_enabled , } if initial_clk and clk : self . listener . stream_unique_id = unique_id else : self . listener . register_stream ( unique_id , 'orderSubscription' ) self . _send ( message ) return unique_id
Order subscription request .
43,624
def _create_socket ( self ) : s = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) s = ssl . wrap_socket ( s ) s . connect ( ( self . host , self . __port ) ) s . settimeout ( self . timeout ) return s
Creates ssl socket connects to stream api and sets timeout .
43,625
def _read_loop ( self ) : while self . _running : received_data_raw = self . _receive_all ( ) if self . _running : self . receive_count += 1 self . datetime_last_received = datetime . datetime . utcnow ( ) received_data_split = received_data_raw . split ( self . __CRLF ) for received_data in received_data_split : if received_data : self . _data ( received_data )
Read loop splits by CRLF and pushes received data to _data .
43,626
def _receive_all ( self ) : ( data , part ) = ( '' , '' ) if is_py3 : crlf_bytes = bytes ( self . __CRLF , encoding = self . __encoding ) else : crlf_bytes = self . __CRLF while self . _running and part [ - 2 : ] != crlf_bytes : try : part = self . _socket . recv ( self . buffer_size ) except ( socket . timeout , socket . error ) as e : if self . _running : self . stop ( ) raise SocketError ( '[Connect: %s]: Socket %s' % ( self . _unique_id , e ) ) else : return if len ( part ) == 0 : self . stop ( ) raise SocketError ( 'Connection closed by server' ) data += part . decode ( self . __encoding ) return data
Whilst socket is running receives data from socket till CRLF is detected .
43,627
def _data ( self , received_data ) : if self . listener . on_data ( received_data ) is False : self . stop ( ) raise ListenerError ( self . listener . connection_id , received_data )
Sends data to listener if False is returned ; socket is closed .
43,628
def _send ( self , message ) : if not self . _running : self . _connect ( ) self . authenticate ( ) message_dumped = json . dumps ( message ) + self . __CRLF try : self . _socket . send ( message_dumped . encode ( ) ) except ( socket . timeout , socket . error ) as e : self . stop ( ) raise SocketError ( '[Connect: %s]: Socket %s' % ( self . _unique_id , e ) )
If not running connects socket and authenticates . Adds CRLF and sends message to Betfair .
43,629
def fit_transform ( self , X , y = None , ** fit_params ) : Xt , yt , fit_params = self . _fit ( X , y , ** fit_params ) if isinstance ( self . _final_estimator , XyTransformerMixin ) : Xt , yt , _ = self . _final_estimator . fit_transform ( Xt , yt ) else : if hasattr ( self . _final_estimator , 'fit_transform' ) : Xt = self . _final_estimator . fit_transform ( Xt , yt ) else : self . _final_estimator . fit ( Xt , yt ) Xt = self . _final_estimator . transform ( Xt ) self . N_fit = len ( yt ) return Xt , yt
Fit the model and transform with the final estimator Fits all the transforms one after the other and transforms the data then uses fit_transform on transformed data with the final estimator .
43,630
def predict ( self , X ) : Xt , _ , _ = self . _transform ( X ) return self . _final_estimator . predict ( Xt )
Apply transforms to the data and predict with the final estimator
43,631
def transform_predict ( self , X , y ) : Xt , yt , _ = self . _transform ( X , y ) yp = self . _final_estimator . predict ( Xt ) return yt , yp
Apply transforms to the data and predict with the final estimator . Unlike predict this also returns the transformed target
43,632
def score ( self , X , y = None , sample_weight = None ) : Xt , yt , swt = self . _transform ( X , y , sample_weight ) self . N_test = len ( yt ) score_params = { } if swt is not None : score_params [ 'sample_weight' ] = swt if self . scorer is None : return self . _final_estimator . score ( Xt , yt , ** score_params ) return self . scorer ( self . _final_estimator , Xt , yt , ** score_params )
Apply transforms and score with the final estimator
43,633
def predict_proba ( self , X ) : Xt , _ , _ = self . _transform ( X ) return self . _final_estimator . predict_proba ( Xt )
Apply transforms and predict_proba of the final estimator
43,634
def decision_function ( self , X ) : Xt , _ , _ = self . _transform ( X ) return self . _final_estimator . decision_function ( Xt )
Apply transforms and decision_function of the final estimator
43,635
def predict_log_proba ( self , X ) : Xt , _ , _ = self . _transform ( X ) return self . _final_estimator . predict_log_proba ( Xt )
Apply transforms and predict_log_proba of the final estimator
43,636
def base_features ( ) : features = { 'mean' : mean , 'median' : median , 'abs_energy' : abs_energy , 'std' : std , 'var' : var , 'min' : minimum , 'max' : maximum , 'skew' : skew , 'kurt' : kurt , 'mse' : mse , 'mnx' : mean_crossings } return features
Returns dictionary of some basic features that can be calculated for segmented time series data
43,637
def all_features ( ) : features = { 'mean' : mean , 'median' : median , 'gmean' : gmean , 'hmean' : hmean , 'vec_sum' : vec_sum , 'abs_sum' : abs_sum , 'abs_energy' : abs_energy , 'std' : std , 'var' : var , 'variation' : variation , 'min' : minimum , 'max' : maximum , 'skew' : skew , 'kurt' : kurt , 'mean_diff' : mean_diff , 'mean_abs_diff' : means_abs_diff , 'mse' : mse , 'mnx' : mean_crossings , 'hist4' : hist ( ) , 'corr' : corr2 , 'mean_abs_value' : mean_abs , 'zero_crossings' : zero_crossing ( ) , 'slope_sign_changes' : slope_sign_changes ( ) , 'waveform_length' : waveform_length , 'emg_var' : emg_var , 'root_mean_square' : root_mean_square , 'willison_amplitude' : willison_amplitude ( ) } return features
Returns dictionary of all features in the module
43,638
def emg_features ( threshold = 0 ) : return { 'mean_abs_value' : mean_abs , 'zero_crossings' : zero_crossing ( threshold ) , 'slope_sign_changes' : slope_sign_changes ( threshold ) , 'waveform_length' : waveform_length , 'integrated_emg' : abs_sum , 'emg_var' : emg_var , 'simple square integral' : abs_energy , 'root_mean_square' : root_mean_square , 'willison_amplitude' : willison_amplitude ( threshold ) , }
Return a dictionary of popular features used for EMG time series classification .
43,639
def means_abs_diff ( X ) : return np . mean ( np . abs ( np . diff ( X , axis = 1 ) ) , axis = 1 )
mean absolute temporal derivative
43,640
def mse ( X ) : return np . mean ( np . square ( np . abs ( np . fft . fft ( X , axis = 1 ) ) ) , axis = 1 )
computes mean spectral energy for each variable in a segmented time series
43,641
def mean_crossings ( X ) : X = np . atleast_3d ( X ) N = X . shape [ 0 ] D = X . shape [ 2 ] mnx = np . zeros ( ( N , D ) ) for i in range ( D ) : pos = X [ : , : , i ] > 0 npos = ~ pos c = ( pos [ : , : - 1 ] & npos [ : , 1 : ] ) | ( npos [ : , : - 1 ] & pos [ : , 1 : ] ) mnx [ : , i ] = np . count_nonzero ( c , axis = 1 ) return mnx
Computes number of mean crossings for each variable in a segmented time series
43,642
def corr2 ( X ) : X = np . atleast_3d ( X ) N = X . shape [ 0 ] D = X . shape [ 2 ] if D == 1 : return np . zeros ( N , dtype = np . float ) trii = np . triu_indices ( D , k = 1 ) DD = len ( trii [ 0 ] ) r = np . zeros ( ( N , DD ) ) for i in np . arange ( N ) : rmat = np . corrcoef ( X [ i ] ) r [ i ] = rmat [ trii ] return r
computes correlations between all variable pairs in a segmented time series
43,643
def waveform_length ( X ) : return np . sum ( np . abs ( np . diff ( X , axis = 1 ) ) , axis = 1 )
cumulative length of the waveform over a segment for each variable in the segmented time series
43,644
def root_mean_square ( X ) : segment_width = X . shape [ 1 ] return np . sqrt ( np . sum ( X * X , axis = 1 ) / segment_width )
root mean square for each variable in the segmented time series
43,645
def split ( self , X , y ) : check_ts_data ( X , y ) Xt , Xc = get_ts_data_parts ( X ) Ns = len ( Xt ) Xt_new , y_new = self . _ts_slice ( Xt , y ) if Xc is not None : Xc_new = np . concatenate ( [ Xc ] * self . n_splits ) X_new = TS_Data ( Xt_new , Xc_new ) else : X_new = np . array ( Xt_new ) cv = self . _make_indices ( Ns ) return X_new , y_new , cv
Splits time series data and target arrays and generates splitting indices
43,646
def _ts_slice ( self , Xt , y ) : Ns = len ( Xt ) Xt_new = [ ] for i in range ( self . n_splits ) : for j in range ( Ns ) : Njs = int ( len ( Xt [ j ] ) / self . n_splits ) Xt_new . append ( Xt [ j ] [ ( Njs * i ) : ( Njs * ( i + 1 ) ) ] ) Xt_new = np . array ( Xt_new ) if len ( np . atleast_1d ( y [ 0 ] ) ) == len ( Xt [ 0 ] ) : y_new = [ ] for i in range ( self . n_splits ) : for j in range ( Ns ) : Njs = int ( len ( y [ j ] ) / self . n_splits ) y_new . append ( y [ j ] [ ( Njs * i ) : ( Njs * ( i + 1 ) ) ] ) y_new = np . array ( y_new ) else : y_new = np . concatenate ( [ y for i in range ( self . n_splits ) ] ) return Xt_new , y_new
takes time series data and splits each series into temporal folds
43,647
def _make_indices ( self , Ns ) : N_new = int ( Ns * self . n_splits ) test = [ np . full ( N_new , False ) for i in range ( self . n_splits ) ] for i in range ( self . n_splits ) : test [ i ] [ np . arange ( Ns * i , Ns * ( i + 1 ) ) ] = True train = [ np . logical_not ( test [ i ] ) for i in range ( self . n_splits ) ] test = [ np . arange ( N_new ) [ test [ i ] ] for i in range ( self . n_splits ) ] train = [ np . arange ( N_new ) [ train [ i ] ] for i in range ( self . n_splits ) ] cv = list ( zip ( train , test ) ) return cv
makes indices for cross validation
43,648
def transform ( self , X , y , sample_weight = None ) : check_ts_data_with_ts_target ( X , y ) Xt , Xc = get_ts_data_parts ( X ) N = len ( Xt ) yt = [ ] Xtt = [ ] swt = sample_weight Nt = [ ] for i in range ( N ) : Xi , yi = self . _transform ( Xt [ i ] , y [ i ] ) yt += yi Xtt += Xi Nt . append ( len ( yi ) ) if Xc is not None : Xct = expand_variables_to_segments ( Xc , Nt ) Xtt = TS_Data ( Xtt , Xct ) if sample_weight is not None : swt = expand_variables_to_segments ( sample_weight , Nt ) return Xtt , yt , swt
Transforms the time series data with run length encoding of the target variable Note this transformation changes the number of samples in the data If sample_weight is provided it is transformed to align to the new target encoding
43,649
def _rle ( self , a ) : ia = np . asarray ( a ) n = len ( ia ) y = np . array ( ia [ 1 : ] != ia [ : - 1 ] ) i = np . append ( np . where ( y ) , n - 1 ) z = np . diff ( np . append ( - 1 , i ) ) p = np . cumsum ( np . append ( 0 , z ) ) [ : - 1 ] return ( z , p , ia [ i ] )
rle implementation credit to Thomas Browne from his SOF post Sept 2015
43,650
def _transform ( self , X , y ) : z , p , y_rle = self . _rle ( y ) p = np . append ( p , len ( y ) ) big_enough = p [ 1 : ] - p [ : - 1 ] >= self . min_length Xt = [ ] for i in range ( len ( y_rle ) ) : if ( big_enough [ i ] ) : Xt . append ( X [ p [ i ] : p [ i + 1 ] ] ) yt = y_rle [ big_enough ] . tolist ( ) return Xt , yt
Transforms single series
43,651
def get_ts_data_parts ( X ) : if not isinstance ( X , TS_Data ) : return X , None return X . ts_data , X . context_data
Separates time series data object into time series variables and contextual variables
43,652
def check_ts_data_with_ts_target ( X , y = None ) : if y is not None : Nx = len ( X ) Ny = len ( y ) if Nx != Ny : raise ValueError ( "Number of time series different in X (%d) and y (%d)" % ( Nx , Ny ) ) Xt , _ = get_ts_data_parts ( X ) Ntx = np . array ( [ len ( Xt [ i ] ) for i in np . arange ( Nx ) ] ) Nty = np . array ( [ len ( np . atleast_1d ( y [ i ] ) ) for i in np . arange ( Nx ) ] ) if np . count_nonzero ( Nty == Ntx ) == Nx : return else : raise ValueError ( "Invalid time series lengths.\n" "Ns: " , Nx , "Ntx: " , Ntx , "Nty: " , Nty )
Checks time series data with time series target is good . If not raises value error .
43,653
def ts_stats ( Xt , y , fs = 1.0 , class_labels = None ) : check_ts_data ( Xt ) Xt , Xs = get_ts_data_parts ( Xt ) if Xs is not None : S = len ( np . atleast_1d ( Xs [ 0 ] ) ) else : S = 0 C = np . max ( y ) + 1 if class_labels is None : class_labels = np . arange ( C ) N = len ( Xt ) if Xt [ 0 ] . ndim > 1 : D = Xt [ 0 ] . shape [ 1 ] else : D = 1 Ti = np . array ( [ Xt [ i ] . shape [ 0 ] for i in range ( N ) ] , dtype = np . float64 ) / fs ic = np . array ( [ y == i for i in range ( C ) ] ) Tic = [ Ti [ ic [ i ] ] for i in range ( C ) ] T = np . sum ( Ti ) total = { "n_series" : N , "n_classes" : C , "n_TS_vars" : D , "n_context_vars" : S , "Total_Time" : T , "Series_Time_Mean" : np . mean ( Ti ) , "Series_Time_Std" : np . std ( Ti ) , "Series_Time_Range" : ( np . min ( Ti ) , np . max ( Ti ) ) } by_class = { "Class_labels" : class_labels , "n_series" : np . array ( [ len ( Tic [ i ] ) for i in range ( C ) ] ) , "Total_Time" : np . array ( [ np . sum ( Tic [ i ] ) for i in range ( C ) ] ) , "Series_Time_Mean" : np . array ( [ np . mean ( Tic [ i ] ) for i in range ( C ) ] ) , "Series_Time_Std" : np . array ( [ np . std ( Tic [ i ] ) for i in range ( C ) ] ) , "Series_Time_Min" : np . array ( [ np . min ( Tic [ i ] ) for i in range ( C ) ] ) , "Series_Time_Max" : np . array ( [ np . max ( Tic [ i ] ) for i in range ( C ) ] ) } results = { 'total' : total , 'by_class' : by_class } return results
Generates some helpful statistics about the data X
43,654
def load_watch ( ) : module_path = dirname ( __file__ ) data = np . load ( module_path + "/data/watch_dataset.npy" ) . item ( ) return data
Loads some of the 6 - axis inertial sensor data from my smartwatch project . The sensor data was recorded as study subjects performed sets of 20 shoulder exercise repetitions while wearing a smartwatch . It is a multivariate time series .
43,655
def shuffle_data ( X , y = None , sample_weight = None ) : if len ( X ) > 1 : ind = np . arange ( len ( X ) , dtype = np . int ) np . random . shuffle ( ind ) Xt = X [ ind ] yt = y swt = sample_weight if yt is not None : yt = yt [ ind ] if swt is not None : swt = swt [ ind ] return Xt , yt , swt else : return X , y , sample_weight
Shuffles indices X y and sample_weight together
43,656
def expand_variables_to_segments ( v , Nt ) : N_v = len ( np . atleast_1d ( v [ 0 ] ) ) return np . concatenate ( [ np . full ( ( Nt [ i ] , N_v ) , v [ i ] ) for i in np . arange ( len ( v ) ) ] )
expands contextual variables v by repeating each instance as specified in Nt
43,657
def sliding_window ( time_series , width , step , order = 'F' ) : w = np . hstack ( [ time_series [ i : 1 + i - width or None : step ] for i in range ( 0 , width ) ] ) result = w . reshape ( ( int ( len ( w ) / width ) , width ) , order = 'F' ) if order == 'F' : return result else : return np . ascontiguousarray ( result )
Segments univariate time series with sliding window
43,658
def sliding_tensor ( mv_time_series , width , step , order = 'F' ) : D = mv_time_series . shape [ 1 ] data = [ sliding_window ( mv_time_series [ : , j ] , width , step , order ) for j in range ( D ) ] return np . stack ( data , axis = 2 )
segments multivariate time series with sliding window
43,659
def transform ( self , X , y = None , sample_weight = None ) : check_ts_data ( X , y ) Xt , Xc = get_ts_data_parts ( X ) yt = y N = len ( Xt ) if Xt [ 0 ] . ndim > 1 : Xt = np . array ( [ sliding_tensor ( Xt [ i ] , self . width , self . _step , self . order ) for i in np . arange ( N ) ] ) else : Xt = np . array ( [ sliding_window ( Xt [ i ] , self . width , self . _step , self . order ) for i in np . arange ( N ) ] ) Nt = [ len ( Xt [ i ] ) for i in np . arange ( len ( Xt ) ) ] Xt = np . concatenate ( Xt ) if Xc is not None : Xc = expand_variables_to_segments ( Xc , Nt ) Xt = TS_Data ( Xt , Xc ) if yt is not None : yt = np . array ( [ sliding_window ( yt [ i ] , self . width , self . _step , self . order ) for i in np . arange ( N ) ] ) yt = np . concatenate ( yt ) yt = self . y_func ( yt ) if self . shuffle is True : check_random_state ( self . random_state ) Xt , yt , _ = shuffle_data ( Xt , yt ) return Xt , yt , None
Transforms the time series data into segments Note this transformation changes the number of samples in the data If y is provided it is segmented and transformed to align to the new samples as per y_func Currently sample weights always returned as None
43,660
def transform ( self , X , y = None , sample_weight = None ) : check_ts_data ( X , y ) Xt , Xc = get_ts_data_parts ( X ) yt = y swt = sample_weight Xt = self . _mv_resize ( Xt ) if Xc is not None : Xt = TS_Data ( Xt , Xc ) if yt is not None and len ( np . atleast_1d ( yt [ 0 ] ) ) > 1 : yt = self . _mv_resize ( yt ) swt = None elif yt is not None : yt = np . array ( yt ) return Xt , yt , swt
Transforms the time series data into fixed length segments using padding and or truncation If y is a time series and passed it will be transformed as well
43,661
def _check_data ( self , X ) : if len ( X ) > 1 : sval = np . unique ( X [ 0 ] [ : , 1 ] ) if np . all ( [ np . all ( np . unique ( X [ i ] [ : , 1 ] ) == sval ) for i in range ( 1 , len ( X ) ) ] ) : pass else : raise ValueError ( "Unique identifier var_types not consistent between time series" )
Checks that unique identifiers vaf_types are consistent between time series .
43,662
def _check_features ( self , features , Xti ) : N = Xti . shape [ 0 ] N_fts = len ( features ) fshapes = np . zeros ( ( N_fts , 2 ) , dtype = np . int ) keys = [ key for key in features ] for i in np . arange ( N_fts ) : fshapes [ i ] = np . row_stack ( features [ keys [ i ] ] ( Xti ) ) . shape if not np . all ( fshapes [ : , 0 ] == N ) : raise ValueError ( "feature function returned array with invalid length, " , np . array ( features . keys ( ) ) [ fshapes [ : , 0 ] != N ] ) return { keys [ i ] : fshapes [ i , 1 ] for i in range ( N_fts ) }
tests output of each feature against a segmented time series X
43,663
def _generate_feature_labels ( self , X ) : Xt , Xc = get_ts_data_parts ( X ) ftr_sizes = self . _check_features ( self . features , Xt [ 0 : 3 ] ) f_labels = [ ] for key in ftr_sizes : for i in range ( ftr_sizes [ key ] ) : f_labels += [ key + '_' + str ( i ) ] if Xc is not None : Ns = len ( np . atleast_1d ( Xc [ 0 ] ) ) s_labels = [ "context_" + str ( i ) for i in range ( Ns ) ] f_labels += s_labels return f_labels
Generates string feature labels
43,664
def _retrieve_indices ( cols ) : if isinstance ( cols , int ) : return [ cols ] elif isinstance ( cols , slice ) : start = cols . start if cols . start else 0 stop = cols . stop step = cols . step if cols . step else 1 return list ( range ( start , stop , step ) ) elif isinstance ( cols , list ) and cols : if isinstance ( cols [ 0 ] , bool ) : return np . flatnonzero ( np . asarray ( cols ) ) elif isinstance ( cols [ 0 ] , int ) : return cols else : raise TypeError ( 'No valid column specifier. Only a scalar, list or slice of all' 'integers or a boolean mask are allowed.' )
Retrieve a list of indices corresponding to the provided column specification .
43,665
def _validate ( self ) : if self . f_labels is None : raise NotFittedError ( 'FeatureRepMix' ) if not self . transformers : return names , transformers , _ = zip ( * self . transformers ) self . _validate_names ( names ) for trans in transformers : if not isinstance ( trans , FeatureRep ) : raise TypeError ( "All transformers must be an instance of FeatureRep." " '%s' (type %s) doesn't." % ( trans , type ( trans ) ) )
Internal function to validate the transformer before applying all internal transformers .
43,666
def transform ( self , X ) : if self . func is None : return X else : Xt , Xc = get_ts_data_parts ( X ) n_samples = len ( Xt ) Xt = self . func ( Xt , ** self . func_kwargs ) if len ( Xt ) != n_samples : raise ValueError ( "FunctionTransformer changes sample number (not supported)." ) if Xc is not None : Xt = TS_Data ( Xt , Xc ) return Xt
Transforms the time series data based on the provided function . Note this transformation must not change the number of samples in the data .
43,667
def build_payload ( self , payload ) : remaining_size = self . MAX_SEGMENT_PAYLOAD_SIZE for part in self . parts : part_payload = part . pack ( remaining_size ) payload . write ( part_payload ) remaining_size -= len ( part_payload )
Build payload of all parts and write them into the payload buffer
43,668
def escape ( value ) : if isinstance ( value , ( tuple , list ) ) : return "(" + ", " . join ( [ escape ( arg ) for arg in value ] ) + ")" else : typ = by_python_type . get ( value . __class__ ) if typ is None : raise InterfaceError ( "Unsupported python input: %s (%s)" % ( value , value . __class__ ) ) return typ . to_sql ( value )
Escape a single value .
43,669
def escape_values ( values ) : if isinstance ( values , ( tuple , list ) ) : return tuple ( [ escape ( value ) for value in values ] ) elif isinstance ( values , dict ) : return dict ( [ ( key , escape ( value ) ) for ( key , value ) in values . items ( ) ] ) else : raise InterfaceError ( "escape_values expects list, tuple or dict" )
Escape multiple values from a list tuple or dict .
43,670
def prepare ( cls , value ) : pfield = struct . pack ( 'b' , cls . type_code ) if isinstance ( value , string_types ) : value = datetime . datetime . strptime ( value , "%Y-%m-%d" ) year = value . year | 0x8000 month = value . month - 1 pfield += cls . _struct . pack ( year , month , value . day ) return pfield
Pack datetime value into proper binary format
43,671
def prepare ( cls , value ) : pfield = struct . pack ( 'b' , cls . type_code ) if isinstance ( value , string_types ) : if "." in value : value = datetime . datetime . strptime ( value , "%H:%M:%S.%f" ) else : value = datetime . datetime . strptime ( value , "%H:%M:%S" ) millisecond = value . second * 1000 + value . microsecond // 1000 hour = value . hour | 0x80 pfield += cls . _struct . pack ( hour , value . minute , millisecond ) return pfield
Pack time value into proper binary format
43,672
def prepare ( cls , value , length = 0 , position = 0 , is_last_data = True ) : hstruct = WriteLobHeader . header_struct lob_option_dataincluded = WriteLobHeader . LOB_OPTION_DATAINCLUDED if length > 0 else 0 lob_option_lastdata = WriteLobHeader . LOB_OPTION_LASTDATA if is_last_data else 0 options = lob_option_dataincluded | lob_option_lastdata pfield = hstruct . pack ( cls . type_code , options , length , position ) return pfield
Prepare Lob header . Note that the actual lob data is NOT written here but appended after the parameter block for each row!
43,673
def seek ( self , offset , whence = SEEK_SET ) : self . data . seek ( offset , whence ) new_pos = self . data . tell ( ) missing_bytes_to_read = new_pos - self . _current_lob_length if missing_bytes_to_read > 0 : self . data . seek ( 0 , SEEK_END ) self . read ( missing_bytes_to_read + self . EXTRA_NUM_ITEMS_TO_READ_AFTER_SEEK ) self . data . seek ( new_pos ) return new_pos
Seek pointer in lob data buffer to requested position . Might trigger further loading of data from the database if the pointer is beyond currently read data .
43,674
def _read_missing_lob_data_from_db ( self , readoffset , readlength ) : logger . debug ( 'Reading missing lob data from db. Offset: %d, readlength: %d' % ( readoffset , readlength ) ) lob_data = self . _make_read_lob_request ( readoffset , readlength ) enc_lob_data = self . _decode_lob_data ( lob_data ) assert readlength == len ( enc_lob_data ) , 'expected: %d, received; %d' % ( readlength , len ( enc_lob_data ) ) self . data . seek ( 0 , SEEK_END ) self . data . write ( enc_lob_data ) self . _current_lob_length = len ( self . data . getvalue ( ) )
Read LOB request part from database
43,675
def _init_io_container ( self , init_value ) : if isinstance ( init_value , CLOB_STRING_IO_CLASSES ) : v = init_value else : if PY3 : init_value . encode ( 'ascii' ) v = CLOB_STRING_IO ( init_value ) return v
Initialize container to hold lob data . Here either a cStringIO or a io . StringIO class is used depending on the Python version . For CLobs ensure that an initial unicode value only contains valid ascii chars .
43,676
def _handle_upsert ( self , parts , unwritten_lobs = ( ) ) : self . description = None self . _received_last_resultset_part = True for part in parts : if part . kind == part_kinds . ROWSAFFECTED : self . rowcount = part . values [ 0 ] elif part . kind in ( part_kinds . TRANSACTIONFLAGS , part_kinds . STATEMENTCONTEXT , part_kinds . PARAMETERMETADATA ) : pass elif part . kind == part_kinds . WRITELOBREPLY : for lob_buffer , lob_locator_id in izip ( unwritten_lobs , part . locator_ids ) : lob_buffer . locator_id = lob_locator_id self . _perform_lob_write_requests ( unwritten_lobs ) else : raise InterfaceError ( "Prepared insert statement response, unexpected part kind %d." % part . kind ) self . _executed = True
Handle reply messages from INSERT or UPDATE statements
43,677
def _handle_select ( self , parts , result_metadata = None ) : self . rowcount = - 1 if result_metadata is not None : self . description , self . _column_types = self . _handle_result_metadata ( result_metadata ) for part in parts : if part . kind == part_kinds . RESULTSETID : self . _resultset_id = part . value elif part . kind == part_kinds . RESULTSETMETADATA : self . description , self . _column_types = self . _handle_result_metadata ( part ) elif part . kind == part_kinds . RESULTSET : self . _buffer = part . unpack_rows ( self . _column_types , self . connection ) self . _received_last_resultset_part = part . attribute & 1 self . _executed = True elif part . kind in ( part_kinds . STATEMENTCONTEXT , part_kinds . TRANSACTIONFLAGS , part_kinds . PARAMETERMETADATA ) : pass else : raise InterfaceError ( "Prepared select statement response, unexpected part kind %d." % part . kind )
Handle reply messages from SELECT statements
43,678
def _handle_dbproc_call ( self , parts , parameters_metadata ) : for part in parts : if part . kind == part_kinds . ROWSAFFECTED : self . rowcount = part . values [ 0 ] elif part . kind == part_kinds . TRANSACTIONFLAGS : pass elif part . kind == part_kinds . STATEMENTCONTEXT : pass elif part . kind == part_kinds . OUTPUTPARAMETERS : self . _buffer = part . unpack_rows ( parameters_metadata , self . connection ) self . _received_last_resultset_part = True self . _executed = True elif part . kind == part_kinds . RESULTSETMETADATA : self . description , self . _column_types = self . _handle_result_metadata ( part ) elif part . kind == part_kinds . RESULTSETID : self . _resultset_id = part . value elif part . kind == part_kinds . RESULTSET : self . _buffer = part . unpack_rows ( self . _column_types , self . connection ) self . _received_last_resultset_part = part . attribute & 1 self . _executed = True else : raise InterfaceError ( "Stored procedure call, unexpected part kind %d." % part . kind ) self . _executed = True
Handle reply messages from STORED PROCEDURE statements
43,679
def allhexlify ( data ) : hx = binascii . hexlify ( data ) return b'' . join ( [ b'\\x' + o for o in re . findall ( b'..' , hx ) ] )
Hexlify given data into a string representation with hex values for all chars Input like ab \ x04ce becomes \ x61 \ x62 \ x04 \ x63 \ x65
43,680
def pack ( self , remaining_size ) : arguments_count , payload = self . pack_data ( remaining_size - self . header_size ) payload_length = len ( payload ) if payload_length % 8 != 0 : payload += b"\x00" * ( 8 - payload_length % 8 ) self . header = PartHeader ( self . kind , self . attribute , arguments_count , self . bigargumentcount , payload_length , remaining_size ) hdr = self . header_struct . pack ( * self . header ) if pyhdb . tracing : self . trace_header = humanhexlify ( hdr , 30 ) self . trace_payload = humanhexlify ( payload , 30 ) return hdr + payload
Pack data of part into binary format
43,681
def unpack_from ( cls , payload , expected_parts ) : for num_part in iter_range ( expected_parts ) : hdr = payload . read ( cls . header_size ) try : part_header = PartHeader ( * cls . header_struct . unpack ( hdr ) ) except struct . error : raise InterfaceError ( "No valid part header" ) if part_header . payload_size % 8 != 0 : part_payload_size = part_header . payload_size + 8 - ( part_header . payload_size % 8 ) else : part_payload_size = part_header . payload_size pl = payload . read ( part_payload_size ) part_payload = io . BytesIO ( pl ) try : _PartClass = PART_MAPPING [ part_header . part_kind ] except KeyError : raise InterfaceError ( "Unknown part kind %s" % part_header . part_kind ) debug ( '%s (%d/%d): %s' , _PartClass . __name__ , num_part + 1 , expected_parts , str ( part_header ) ) debug ( 'Read %d bytes payload for part %d' , part_payload_size , num_part + 1 ) init_arguments = _PartClass . unpack_data ( part_header . argument_count , part_payload ) debug ( 'Part data: %s' , init_arguments ) part = _PartClass ( * init_arguments ) part . header = part_header part . attribute = part_header . part_attributes part . source = 'server' if pyhdb . tracing : part . trace_header = humanhexlify ( hdr [ : part_header . payload_size ] ) part . trace_payload = humanhexlify ( pl , 30 ) yield part
Unpack parts from payload
43,682
def pack_data ( self , remaining_size ) : payload = self . part_struct . pack ( self . locator_id , self . readoffset + 1 , self . readlength , b' ' ) return 4 , payload
Pack data . readoffset has to be increased by one seems like HANA starts from 1 not zero .
43,683
def build_payload ( self , payload ) : for segment in self . segments : segment . pack ( payload , commit = self . autocommit )
Build payload of message .
43,684
def pack ( self ) : payload = io . BytesIO ( ) payload . seek ( self . header_size , io . SEEK_CUR ) self . build_payload ( payload ) packet_length = len ( payload . getvalue ( ) ) - self . header_size self . header = MessageHeader ( self . session_id , self . packet_count , packet_length , constants . MAX_SEGMENT_SIZE , num_segments = len ( self . segments ) , packet_options = 0 ) packed_header = self . header_struct . pack ( * self . header ) payload . seek ( 0 ) payload . write ( packed_header ) payload . seek ( 0 , io . SEEK_END ) trace ( self ) return payload
Pack message to binary stream .
43,685
def check_specs ( specs , renamings , types ) : from pythran . types . tog import unify , clone , tr from pythran . types . tog import Function , TypeVariable , InferenceError functions = { renamings . get ( k , k ) : v for k , v in specs . functions . items ( ) } for fname , signatures in functions . items ( ) : ftype = types [ fname ] for signature in signatures : sig_type = Function ( [ tr ( p ) for p in signature ] , TypeVariable ( ) ) try : unify ( clone ( sig_type ) , clone ( ftype ) ) except InferenceError : raise PythranSyntaxError ( "Specification for `{}` does not match inferred type:\n" "expected `{}`\n" "got `Callable[[{}], ...]`" . format ( fname , ftype , ", " . join ( map ( str , sig_type . types [ : - 1 ] ) ) ) )
Does nothing but raising PythranSyntaxError if specs are incompatible with the actual code
43,686
def check_exports ( mod , specs , renamings ) : functions = { renamings . get ( k , k ) : v for k , v in specs . functions . items ( ) } mod_functions = { node . name : node for node in mod . body if isinstance ( node , ast . FunctionDef ) } for fname , signatures in functions . items ( ) : try : fnode = mod_functions [ fname ] except KeyError : raise PythranSyntaxError ( "Invalid spec: exporting undefined function `{}`" . format ( fname ) ) for signature in signatures : args_count = len ( fnode . args . args ) if len ( signature ) > args_count : raise PythranSyntaxError ( "Too many arguments when exporting `{}`" . format ( fname ) ) elif len ( signature ) < args_count - len ( fnode . args . defaults ) : raise PythranSyntaxError ( "Not enough arguments when exporting `{}`" . format ( fname ) )
Does nothing but raising PythranSyntaxError if specs references an undefined global
43,687
def visit_Import ( self , node ) : for alias in node . names : current_module = MODULES for path in alias . name . split ( '.' ) : if path not in current_module : raise PythranSyntaxError ( "Module '{0}' unknown." . format ( alias . name ) , node ) else : current_module = current_module [ path ]
Check if imported module exists in MODULES .
43,688
def visit_ImportFrom ( self , node ) : if node . level : raise PythranSyntaxError ( "Relative import not supported" , node ) if not node . module : raise PythranSyntaxError ( "import from without module" , node ) module = node . module current_module = MODULES for path in module . split ( '.' ) : if path not in current_module : raise PythranSyntaxError ( "Module '{0}' unknown." . format ( module ) , node ) else : current_module = current_module [ path ] for alias in node . names : if alias . name == '*' : continue elif alias . name not in current_module : raise PythranSyntaxError ( "identifier '{0}' not found in module '{1}'" . format ( alias . name , module ) , node )
Check validity of imported functions .
43,689
def uncamel ( name ) : s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , name ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , s1 ) . lower ( )
Transform CamelCase naming convention into C - ish convention .
43,690
def verify_dependencies ( self ) : for i in range ( 1 , len ( self . deps ) ) : assert ( not ( isinstance ( self . deps [ i ] , Transformation ) and isinstance ( self . deps [ i - 1 ] , Analysis ) ) ) , "invalid dep order for %s" % self
Checks no analysis are called before a transformation as the transformation could invalidate the analysis .
43,691
def prepare ( self , node ) : if isinstance ( node , ast . Module ) : self . ctx . module = node elif isinstance ( node , ast . FunctionDef ) : self . ctx . function = node for D in self . deps : d = D ( ) d . attach ( self . passmanager , self . ctx ) result = d . run ( node ) setattr ( self , uncamel ( D . __name__ ) , result )
Gather analysis result required by this analysis
43,692
def run ( self , node ) : n = super ( Transformation , self ) . run ( node ) if self . update : ast . fix_missing_locations ( n ) self . passmanager . _cache . clear ( ) return n
Apply transformation and dependencies and fix new node location .
43,693
def apply ( self , node ) : new_node = self . run ( node ) return self . update , new_node
Apply transformation and return if an update happened .
43,694
def gather ( self , analysis , node ) : "High-level function to call an `analysis' on a `node'" assert issubclass ( analysis , Analysis ) a = analysis ( ) a . attach ( self ) return a . run ( node )
High - level function to call an analysis on a node
43,695
def dump ( self , backend , node ) : assert issubclass ( backend , Backend ) b = backend ( ) b . attach ( self ) return b . run ( node )
High - level function to call a backend on a node to generate code for module module_name .
43,696
def apply ( self , transformation , node ) : assert issubclass ( transformation , ( Transformation , Analysis ) ) a = transformation ( ) a . attach ( self ) res = a . apply ( node ) if a . update : self . _cache . clear ( ) return res
High - level function to call a transformation on a node . If the transformation is an analysis the result of the analysis is displayed .
43,697
def pytype_to_ctype ( t ) : if isinstance ( t , List ) : return 'pythonic::types::list<{0}>' . format ( pytype_to_ctype ( t . __args__ [ 0 ] ) ) elif isinstance ( t , Set ) : return 'pythonic::types::set<{0}>' . format ( pytype_to_ctype ( t . __args__ [ 0 ] ) ) elif isinstance ( t , Dict ) : tkey , tvalue = t . __args__ return 'pythonic::types::dict<{0},{1}>' . format ( pytype_to_ctype ( tkey ) , pytype_to_ctype ( tvalue ) ) elif isinstance ( t , Tuple ) : return 'decltype(pythonic::types::make_tuple({0}))' . format ( ", " . join ( 'std::declval<{}>()' . format ( pytype_to_ctype ( p ) ) for p in t . __args__ ) ) elif isinstance ( t , NDArray ) : dtype = pytype_to_ctype ( t . __args__ [ 0 ] ) ndim = len ( t . __args__ ) - 1 shapes = ',' . join ( ( 'long' if s . stop == - 1 or s . stop is None else 'std::integral_constant<long, {}>' . format ( s . stop ) ) for s in t . __args__ [ 1 : ] ) pshape = 'pythonic::types::pshape<{0}>' . format ( shapes ) arr = 'pythonic::types::ndarray<{0},{1}>' . format ( dtype , pshape ) if t . __args__ [ 1 ] . start == - 1 : return 'pythonic::types::numpy_texpr<{0}>' . format ( arr ) elif any ( s . step is not None and s . step < 0 for s in t . __args__ [ 1 : ] ) : slices = ", " . join ( [ 'pythonic::types::normalized_slice' ] * ndim ) return 'pythonic::types::numpy_gexpr<{0},{1}>' . format ( arr , slices ) else : return arr elif isinstance ( t , Pointer ) : return 'pythonic::types::pointer<{0}>' . format ( pytype_to_ctype ( t . __args__ [ 0 ] ) ) elif isinstance ( t , Fun ) : return 'pythonic::types::cfun<{0}({1})>' . format ( pytype_to_ctype ( t . __args__ [ - 1 ] ) , ", " . join ( pytype_to_ctype ( arg ) for arg in t . __args__ [ : - 1 ] ) , ) elif t in PYTYPE_TO_CTYPE_TABLE : return PYTYPE_TO_CTYPE_TABLE [ t ] else : raise NotImplementedError ( "{0}:{1}" . format ( type ( t ) , t ) )
Python - > pythonic type binding .
43,698
def pytype_to_pretty_type ( t ) : if isinstance ( t , List ) : return '{0} list' . format ( pytype_to_pretty_type ( t . __args__ [ 0 ] ) ) elif isinstance ( t , Set ) : return '{0} set' . format ( pytype_to_pretty_type ( t . __args__ [ 0 ] ) ) elif isinstance ( t , Dict ) : tkey , tvalue = t . __args__ return '{0}:{1} dict' . format ( pytype_to_pretty_type ( tkey ) , pytype_to_pretty_type ( tvalue ) ) elif isinstance ( t , Tuple ) : return '({0})' . format ( ", " . join ( pytype_to_pretty_type ( p ) for p in t . __args__ ) ) elif isinstance ( t , NDArray ) : dtype = pytype_to_pretty_type ( t . __args__ [ 0 ] ) ndim = len ( t . __args__ ) - 1 arr = '{0}[{1}]' . format ( dtype , ',' . join ( ':' if s . stop in ( - 1 , None ) else str ( s . stop ) for s in t . __args__ [ 1 : ] ) ) if t . __args__ [ 1 ] . start == - 1 : return '{} order(F)' . format ( arr ) elif any ( s . step is not None and s . step < 0 for s in t . __args__ [ 1 : ] ) : return '{0}[{1}]' . format ( dtype , ',' . join ( [ '::' ] * ndim ) ) else : return arr elif isinstance ( t , Pointer ) : dtype = pytype_to_pretty_type ( t . __args__ [ 0 ] ) return '{}*' . format ( dtype ) elif isinstance ( t , Fun ) : rtype = pytype_to_pretty_type ( t . __args__ [ - 1 ] ) argtypes = [ pytype_to_pretty_type ( arg ) for arg in t . __args__ [ : - 1 ] ] return '{}({})' . format ( rtype , ", " . join ( argtypes ) ) elif t in PYTYPE_TO_CTYPE_TABLE : return t . __name__ else : raise NotImplementedError ( "{0}:{1}" . format ( type ( t ) , t ) )
Python - > docstring type .
43,699
def get_type ( name , env , non_generic ) : if name in env : if isinstance ( env [ name ] , MultiType ) : return clone ( env [ name ] ) return fresh ( env [ name ] , non_generic ) else : print ( "W: Undefined symbol {0}" . format ( name ) ) return TypeVariable ( )
Get the type of identifier name from the type environment env .