idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
233,700
def calc_percentile_interval ( self , conf_percentage ) : alpha = bc . get_alpha_from_conf_percentage ( conf_percentage ) single_column_names = [ '{:.3g}%' . format ( alpha / 2.0 ) , '{:.3g}%' . format ( 100 - alpha / 2.0 ) ] conf_intervals = bc . calc_percentile_interval ( self . bootstrap_replicates . values , conf_p...
Calculates percentile bootstrap confidence intervals for one s model .
233,701
def calc_abc_interval ( self , conf_percentage , init_vals , epsilon = 0.001 , ** fit_kwargs ) : print ( "Calculating Approximate Bootstrap Confidence (ABC) Intervals" ) print ( time . strftime ( "%a %m-%d-%Y %I:%M%p" ) ) sys . stdout . flush ( ) alpha = bc . get_alpha_from_conf_percentage ( conf_percentage ) single_co...
Calculates Approximate Bootstrap Confidence Intervals for one s model .
233,702
def calc_conf_intervals ( self , conf_percentage , interval_type = 'all' , init_vals = None , epsilon = abc . EPSILON , ** fit_kwargs ) : if interval_type == 'pi' : self . calc_percentile_interval ( conf_percentage ) elif interval_type == 'bca' : self . calc_bca_interval ( conf_percentage ) elif interval_type == 'abc' ...
Calculates percentile bias - corrected and accelerated and approximate bootstrap confidence intervals .
233,703
def create_calc_dh_d_alpha ( estimator ) : if estimator . intercept_ref_pos is not None : needed_idxs = range ( estimator . rows_to_alts . shape [ 1 ] ) needed_idxs . remove ( estimator . intercept_ref_pos ) dh_d_alpha = ( estimator . rows_to_alts . copy ( ) . transpose ( ) [ needed_idxs , : ] . transpose ( ) ) else : ...
Return the function that can be used in the various gradient and hessian calculations to calculate the derivative of the transformation with respect to the outside intercept parameters .
233,704
def calc_individual_chi_squares ( residuals , long_probabilities , rows_to_obs ) : chi_squared_terms = np . square ( residuals ) / long_probabilities return rows_to_obs . T . dot ( chi_squared_terms )
Calculates individual chi - squared values for each choice situation in the dataset .
233,705
def calc_rho_and_rho_bar_squared ( final_log_likelihood , null_log_likelihood , num_est_parameters ) : rho_squared = 1.0 - final_log_likelihood / null_log_likelihood rho_bar_squared = 1.0 - ( ( final_log_likelihood - num_est_parameters ) / null_log_likelihood ) return rho_squared , rho_bar_squared
Calculates McFadden s rho - squared and rho - bar squared for the given model .
233,706
def calc_and_store_post_estimation_results ( results_dict , estimator ) : final_log_likelihood = - 1 * results_dict [ "fun" ] results_dict [ "final_log_likelihood" ] = final_log_likelihood final_params = results_dict [ "x" ] split_res = estimator . convenience_split_params ( final_params , return_all_types = True ) res...
Calculates and stores post - estimation results that require the use of the systematic utility transformation functions or the various derivative functions . Note that this function is only valid for logit - type models .
233,707
def estimate ( init_values , estimator , method , loss_tol , gradient_tol , maxiter , print_results , use_hessian = True , just_point = False , ** kwargs ) : if not just_point : log_likelihood_at_zero = estimator . convenience_calc_log_likelihood ( estimator . zero_vector ) initial_log_likelihood = estimator . convenie...
Estimate the given choice model that is defined by estimator .
233,708
def calc_neg_log_likelihood_and_neg_gradient ( self , params ) : neg_log_likelihood = - 1 * self . convenience_calc_log_likelihood ( params ) neg_gradient = - 1 * self . convenience_calc_gradient ( params ) if self . constrained_pos is not None : neg_gradient [ self . constrained_pos ] = 0 return neg_log_likelihood , n...
Calculates and returns the negative of the log - likelihood and the negative of the gradient . This function is used as the objective function in scipy . optimize . minimize .
233,709
def ensure_samples_is_ndim_ndarray ( samples , name = 'bootstrap' , ndim = 2 ) : assert isinstance ( ndim , int ) assert isinstance ( name , str ) if not isinstance ( samples , np . ndarray ) or not ( samples . ndim == ndim ) : sample_name = name + "_samples" msg = "`{}` MUST be a {}D ndarray." . format ( sample_name ,...
Ensures that samples is an ndim numpy array . Raises a helpful ValueError if otherwise .
233,710
def create_estimation_obj ( model_obj , init_vals , mappings = None , ridge = None , constrained_pos = None , weights = None ) : mapping_matrices = model_obj . get_mappings_for_fit ( ) if mappings is None else mappings zero_vector = np . zeros ( init_vals . shape [ 0 ] ) internal_model_name = display_name_to_model_type...
Should return a model estimation object corresponding to the model type of the model_obj .
233,711
def ensure_wide_weights_is_1D_or_2D_ndarray ( wide_weights ) : if not isinstance ( wide_weights , np . ndarray ) : msg = "wide_weights MUST be a ndarray." raise ValueError ( msg ) ndim = wide_weights . ndim if not 0 < ndim < 3 : msg = "wide_weights MUST be a 1D or 2D ndarray." raise ValueError ( msg ) return None
Ensures that wide_weights is a 1D or 2D ndarray . Raises a helpful ValueError if otherwise .
233,712
def check_validity_of_long_form_args ( model_obj , wide_weights , rows_to_obs ) : ensure_model_obj_has_mapping_constructor ( model_obj ) ensure_wide_weights_is_1D_or_2D_ndarray ( wide_weights ) ensure_rows_to_obs_validity ( rows_to_obs ) return None
Ensures the args to create_long_form_weights have expected properties .
233,713
def calc_finite_diff_terms_for_abc ( model_obj , mle_params , init_vals , epsilon , ** fit_kwargs ) : num_obs = model_obj . data [ model_obj . obs_id_col ] . unique ( ) . size init_weights_wide = np . ones ( num_obs , dtype = float ) / num_obs init_wide_weights_plus = ( 1 - epsilon ) * init_weights_wide init_wide_weigh...
Calculates the terms needed for the finite difference approximations of the empirical influence and second order empirical influence functions .
233,714
def calc_abc_interval ( model_obj , mle_params , init_vals , conf_percentage , epsilon = 0.001 , ** fit_kwargs ) : check_conf_percentage_validity ( conf_percentage ) empirical_influence , second_order_influence = calc_influence_arrays_for_abc ( model_obj , mle_params , init_vals , epsilon , ** fit_kwargs ) acceleration...
Calculate approximate bootstrap confidence intervals .
233,715
def check_length_of_init_values ( design_3d , init_values ) : if init_values . shape [ 0 ] != design_3d . shape [ 2 ] : msg_1 = "The initial values are of the wrong dimension. " msg_2 = "They should be of dimension {}" . format ( design_3d . shape [ 2 ] ) raise ValueError ( msg_1 + msg_2 ) return None
Ensures that the initial values are of the correct length given the design matrix that they will be dot - producted with . Raises a ValueError if that is not the case and provides a useful error message to users .
233,716
def add_mixl_specific_results_to_estimation_res ( estimator , results_dict ) : prob_res = mlc . calc_choice_sequence_probs ( results_dict [ "long_probs" ] , estimator . choice_vector , estimator . rows_to_mixers , return_type = 'all' ) results_dict [ "simulated_sequence_probs" ] = prob_res [ 0 ] results_dict [ "expande...
Stores particular items in the results dictionary that are unique to mixed logit - type models . In particular this function calculates and adds sequence_probs and expanded_sequence_probs to the results dictionary . The constrained_pos object is also stored to the results_dict .
233,717
def identify_degenerate_nests ( nest_spec ) : degenerate_positions = [ ] for pos , key in enumerate ( nest_spec ) : if len ( nest_spec [ key ] ) == 1 : degenerate_positions . append ( pos ) return degenerate_positions
Identify the nests within nest_spec that are degenerate i . e . those nests with only a single alternative within the nest .
233,718
def check_length_of_initial_values ( self , init_values ) : num_nests = self . rows_to_nests . shape [ 1 ] num_index_coefs = self . design . shape [ 1 ] assumed_param_dimensions = num_index_coefs + num_nests if init_values . shape [ 0 ] != assumed_param_dimensions : msg = "The initial values are of the wrong dimension"...
Ensures that the initial values are of the correct length .
233,719
def convenience_split_params ( self , params , return_all_types = False ) : return split_param_vec ( params , self . rows_to_nests , return_all_types = return_all_types )
Splits parameter vector into nest parameters and index parameters .
233,720
def robust_outer_product ( vec_1 , vec_2 ) : mantissa_1 , exponents_1 = np . frexp ( vec_1 ) mantissa_2 , exponents_2 = np . frexp ( vec_2 ) new_mantissas = mantissa_1 [ None , : ] * mantissa_2 [ : , None ] new_exponents = exponents_1 [ None , : ] + exponents_2 [ : , None ] return new_mantissas * np . exp2 ( new_expone...
Calculates a robust outer product of two vectors that may or may not contain very small values .
233,721
def calc_percentile_interval ( bootstrap_replicates , conf_percentage ) : check_conf_percentage_validity ( conf_percentage ) ensure_samples_is_ndim_ndarray ( bootstrap_replicates , ndim = 2 ) alpha = get_alpha_from_conf_percentage ( conf_percentage ) lower_percent = alpha / 2.0 upper_percent = 100.0 - lower_percent low...
Calculate bootstrap confidence intervals based on raw percentiles of the bootstrap distribution of samples .
233,722
def calc_bca_interval ( bootstrap_replicates , jackknife_replicates , mle_params , conf_percentage ) : check_conf_percentage_validity ( conf_percentage ) ensure_samples_is_ndim_ndarray ( bootstrap_replicates , ndim = 2 ) ensure_samples_is_ndim_ndarray ( jackknife_replicates , name = 'jackknife' , ndim = 2 ) alpha_perce...
Calculate bias - corrected and accelerated bootstrap confidence intervals .
233,723
def extract_default_init_vals ( orig_model_obj , mnl_point_series , num_params ) : init_vals = np . zeros ( num_params , dtype = float ) no_outside_intercepts = orig_model_obj . intercept_names is None if no_outside_intercepts : init_index_coefs = mnl_point_series . values init_intercepts = None else : init_index_coefs...
Get the default initial values for the desired model type based on the point estimate of the MNL model that is closest to the desired model .
233,724
def get_model_abbrev ( model_obj ) : model_type = model_obj . model_type for key in model_type_to_display_name : if model_type_to_display_name [ key ] == model_type : return key msg = "Model object has an unknown or incorrect model type." raise ValueError ( msg )
Extract the string used to specify the model type of this model object in pylogit . create_chohice_model .
233,725
def get_model_creation_kwargs ( model_obj ) : model_abbrev = get_model_abbrev ( model_obj ) model_kwargs = { "model_type" : model_abbrev , "names" : model_obj . name_spec , "intercept_names" : model_obj . intercept_names , "intercept_ref_pos" : model_obj . intercept_ref_position , "shape_names" : model_obj . shape_name...
Get a dictionary of the keyword arguments needed to create the passed model object using pylogit . create_choice_model .
233,726
def ensure_valid_model_type ( specified_type , model_type_list ) : if specified_type not in model_type_list : msg_1 = "The specified model_type was not valid." msg_2 = "Valid model-types are {}" . format ( model_type_list ) msg_3 = "The passed model-type was: {}" . format ( specified_type ) total_msg = "\n" . join ( [ ...
Checks to make sure that specified_type is in model_type_list and raises a helpful error if this is not the case .
233,727
def ensure_valid_nums_in_specification_cols ( specification , dataframe ) : problem_cols = [ ] for col in specification : if dataframe [ col ] . dtype . kind not in [ 'f' , 'i' , 'u' ] : problem_cols . append ( col ) elif np . isinf ( dataframe [ col ] ) . any ( ) : problem_cols . append ( col ) elif np . isnan ( dataf...
Checks whether each column in specification contains numeric data excluding positive or negative infinity and excluding NaN . Raises ValueError if any of the columns do not meet these requirements .
233,728
def check_length_of_shape_or_intercept_names ( name_list , num_alts , constrained_param , list_title ) : if len ( name_list ) != ( num_alts - constrained_param ) : msg_1 = "{} is of the wrong length:" . format ( list_title ) msg_2 = "len({}) == {}" . format ( list_title , len ( name_list ) ) correct_length = num_alts -...
Ensures that the length of the parameter names matches the number of parameters that will be estimated . Will raise a ValueError otherwise .
233,729
def check_type_of_nest_spec_keys_and_values ( nest_spec ) : try : assert all ( [ isinstance ( k , str ) for k in nest_spec ] ) assert all ( [ isinstance ( nest_spec [ k ] , list ) for k in nest_spec ] ) except AssertionError : msg = "All nest_spec keys/values must be strings/lists." raise TypeError ( msg ) return None
Ensures that the keys and values of nest_spec are strings and lists . Raises a helpful ValueError if they are .
233,730
def check_for_empty_nests_in_nest_spec ( nest_spec ) : empty_nests = [ ] for k in nest_spec : if len ( nest_spec [ k ] ) == 0 : empty_nests . append ( k ) if empty_nests != [ ] : msg = "The following nests are INCORRECTLY empty: {}" raise ValueError ( msg . format ( empty_nests ) ) return None
Ensures that the values of nest_spec are not empty lists . Raises a helpful ValueError if they are .
233,731
def ensure_alt_ids_in_nest_spec_are_ints ( nest_spec , list_elements ) : try : assert all ( [ isinstance ( x , int ) for x in list_elements ] ) except AssertionError : msg = "All elements of the nest_spec values should be integers" raise ValueError ( msg ) return None
Ensures that the alternative id s in nest_spec are integers . Raises a helpful ValueError if they are not .
233,732
def ensure_alt_ids_are_only_in_one_nest ( nest_spec , list_elements ) : try : assert len ( set ( list_elements ) ) == len ( list_elements ) except AssertionError : msg = "Each alternative id should only be in a single nest." raise ValueError ( msg ) return None
Ensures that the alternative id s in nest_spec are only associated with a single nest . Raises a helpful ValueError if they are not .
233,733
def ensure_all_alt_ids_have_a_nest ( nest_spec , list_elements , all_ids ) : unaccounted_alt_ids = [ ] for alt_id in all_ids : if alt_id not in list_elements : unaccounted_alt_ids . append ( alt_id ) if unaccounted_alt_ids != [ ] : msg = "Associate the following alternative ids with a nest: {}" raise ValueError ( msg ....
Ensures that the alternative id s in nest_spec are all associated with a nest . Raises a helpful ValueError if they are not .
233,734
def ensure_nest_alts_are_valid_alts ( nest_spec , list_elements , all_ids ) : invalid_alt_ids = [ ] for x in list_elements : if x not in all_ids : invalid_alt_ids . append ( x ) if invalid_alt_ids != [ ] : msg = "The following elements are not in df[alt_id_col]: {}" raise ValueError ( msg . format ( invalid_alt_ids ) )...
Ensures that the alternative id s in nest_spec are all in the universal choice set for this dataset . Raises a helpful ValueError if they are not .
233,735
def check_type_and_size_of_param_list ( param_list , expected_length ) : try : assert isinstance ( param_list , list ) assert len ( param_list ) == expected_length except AssertionError : msg = "param_list must be a list containing {} elements." raise ValueError ( msg . format ( expected_length ) ) return None
Ensure that param_list is a list with the expected length . Raises a helpful ValueError if this is not the case .
233,736
def check_type_of_param_list_elements ( param_list ) : try : assert isinstance ( param_list [ 0 ] , np . ndarray ) assert all ( [ ( x is None or isinstance ( x , np . ndarray ) ) for x in param_list ] ) except AssertionError : msg = "param_list[0] must be a numpy array." msg_2 = "All other elements must be numpy arrays...
Ensures that all elements of param_list are ndarrays or None . Raises a helpful ValueError if otherwise .
233,737
def check_num_columns_in_param_list_arrays ( param_list ) : try : num_columns = param_list [ 0 ] . shape [ 1 ] assert all ( [ x is None or ( x . shape [ 1 ] == num_columns ) for x in param_list ] ) except AssertionError : msg = "param_list arrays should have equal number of columns." raise ValueError ( msg ) return Non...
Ensure that each array in param_list that is not None has the same number of columns . Raises a helpful ValueError if otherwise .
233,738
def ensure_all_mixing_vars_are_in_the_name_dict ( mixing_vars , name_dict , ind_var_names ) : if mixing_vars is None : return None problem_names = [ variable_name for variable_name in mixing_vars if variable_name not in ind_var_names ] msg_0 = "The following parameter names were not in the values of the " msg_1 = "pass...
Ensures that all of the variables listed in mixing_vars are present in ind_var_names . Raises a helpful ValueError if otherwise .
233,739
def compute_aic ( model_object ) : assert isinstance ( model_object . params , pd . Series ) assert isinstance ( model_object . log_likelihood , Number ) return - 2 * model_object . log_likelihood + 2 * model_object . params . size
Compute the Akaike Information Criteria for an estimated model .
233,740
def compute_bic ( model_object ) : assert isinstance ( model_object . params , pd . Series ) assert isinstance ( model_object . log_likelihood , Number ) assert isinstance ( model_object . nobs , Number ) log_likelihood = model_object . log_likelihood num_obs = model_object . nobs num_params = model_object . params . s...
Compute the Bayesian Information Criteria for an estimated model .
233,741
def _create_results_summary ( self ) : needed_attributes = [ "params" , "standard_errors" , "tvalues" , "pvalues" , "robust_std_errs" , "robust_t_stats" , "robust_p_vals" ] try : assert all ( [ hasattr ( self , attr ) for attr in needed_attributes ] ) assert all ( [ isinstance ( getattr ( self , attr ) , pd . Series ) ...
Create the dataframe that displays the estimation results and store it on the model instance .
233,742
def _record_values_for_fit_summary_and_statsmodels ( self ) : needed_attributes = [ "fitted_probs" , "params" , "log_likelihood" , "standard_errors" ] try : assert all ( [ hasattr ( self , attr ) for attr in needed_attributes ] ) assert all ( [ getattr ( self , attr ) is not None for attr in needed_attributes ] ) excep...
Store the various estimation results that are used to describe how well the estimated model fits the given dataset and record the values that are needed for the statsmodels estimation results table . All values are stored on the model instance .
233,743
def _store_inferential_results ( self , value_array , index_names , attribute_name , series_name = None , column_names = None ) : if len ( value_array . shape ) == 1 : assert series_name is not None new_attribute_value = pd . Series ( value_array , index = index_names , name = series_name ) elif len ( value_array . sha...
Store the estimation results that relate to statistical inference such as parameter estimates standard errors p - values etc .
233,744
def _store_generic_inference_results ( self , results_dict , all_params , all_names ) : self . _store_inferential_results ( results_dict [ "utility_coefs" ] , index_names = self . ind_var_names , attribute_name = "coefs" , series_name = "coefficients" ) self . _store_inferential_results ( results_dict [ "final_gradient...
Store the model inference values that are common to all choice models . This includes things like index coefficients gradients hessians asymptotic covariance matrices t - values p - values and robust versions of these values .
233,745
def _store_optional_parameters ( self , optional_params , name_list_attr , default_name_str , all_names , all_params , param_attr_name , series_name ) : num_elements = optional_params . shape [ 0 ] parameter_names = getattr ( self , name_list_attr ) if parameter_names is None : parameter_names = [ default_name_str . fo...
Extract the optional parameters from the results_dict save them to the model object and update the list of all parameters and all parameter names .
233,746
def _adjust_inferential_results_for_parameter_constraints ( self , constraints ) : if constraints is not None : inferential_attributes = [ "standard_errors" , "tvalues" , "pvalues" , "robust_std_errs" , "robust_t_stats" , "robust_p_vals" ] assert all ( [ hasattr ( self , x ) for x in inferential_attributes ] ) assert h...
Ensure that parameters that were constrained during estimation do not have any values showed for inferential results . After all no inference was performed .
233,747
def _check_result_dict_for_needed_keys ( self , results_dict ) : missing_cols = [ x for x in needed_result_keys if x not in results_dict ] if missing_cols != [ ] : msg = "The following keys are missing from results_dict\n{}" raise ValueError ( msg . format ( missing_cols ) ) return None
Ensure that results_dict has the needed keys to store all the estimation results . Raise a helpful ValueError otherwise .
233,748
def _add_mixing_variable_names_to_individual_vars ( self ) : assert isinstance ( self . ind_var_names , list ) already_included = any ( [ "Sigma " in x for x in self . ind_var_names ] ) if self . mixing_vars is not None and not already_included : new_ind_var_names = [ "Sigma " + x for x in self . mixing_vars ] self . i...
Ensure that the model objects mixing variables are added to its list of individual variables .
233,749
def print_summaries ( self ) : if hasattr ( self , "fit_summary" ) and hasattr ( self , "summary" ) : print ( "\n" ) print ( self . fit_summary ) print ( "=" * 30 ) print ( self . summary ) else : msg = "This {} object has not yet been estimated so there " msg_2 = "are no estimation summaries to print." raise NotImplem...
Returns None . Will print the measures of fit and the estimation results for the model .
233,750
def prefix ( * kinds ) : def wrap ( fn ) : try : fn . prefix_kinds . extend ( kinds ) except AttributeError : fn . prefix_kinds = list ( kinds ) return fn return wrap
Decorate a method as handling prefix tokens of the given kinds
233,751
def infix ( * kinds ) : def wrap ( fn ) : try : fn . infix_kinds . extend ( kinds ) except AttributeError : fn . infix_kinds = list ( kinds ) return fn return wrap
Decorate a method as handling infix tokens of the given kinds
233,752
def attempt ( self , * kinds ) : if self . _error : raise self . _error token = self . next_token if not token : return None if kinds and token . kind not in kinds : return None self . _advance ( ) return token
Try to get the next token if it matches one of the kinds given otherwise returning None . If no kinds are given any kind is accepted .
233,753
def require ( self , * kinds ) : token = self . attempt ( ) if not token : raise SyntaxError ( 'Unexpected end of input' ) if kinds and token . kind not in kinds : raise SyntaxError . unexpected ( token , kinds ) return token
Get the next token raising an exception if it doesn t match one of the given kinds or the input ends . If no kinds are given returns the next token of any kind .
233,754
def local_symbol_table ( imports = None , symbols = ( ) ) : return SymbolTable ( table_type = LOCAL_TABLE_TYPE , symbols = symbols , imports = imports )
Constructs a local symbol table .
233,755
def shared_symbol_table ( name , version , symbols , imports = None ) : return SymbolTable ( table_type = SHARED_TABLE_TYPE , symbols = symbols , name = name , version = version , imports = imports )
Constructs a shared symbol table .
233,756
def placeholder_symbol_table ( name , version , max_id ) : if version <= 0 : raise ValueError ( 'Version must be grater than or equal to 1: %s' % version ) if max_id < 0 : raise ValueError ( 'Max ID must be zero or positive: %s' % max_id ) return SymbolTable ( table_type = SHARED_TABLE_TYPE , symbols = repeat ( None , ...
Constructs a shared symbol table that consists symbols that all have no known text .
233,757
def substitute_symbol_table ( table , version , max_id ) : if not table . table_type . is_shared : raise ValueError ( 'Symbol table to substitute from must be a shared table' ) if version <= 0 : raise ValueError ( 'Version must be grater than or equal to 1: %s' % version ) if max_id < 0 : raise ValueError ( 'Max ID mus...
Substitutes a given shared symbol table for another version .
233,758
def __add ( self , token ) : self . __symbols . append ( token ) text = token . text if text is not None and text not in self . __mapping : self . __mapping [ text ] = token
Unconditionally adds a token to the table .
233,759
def __add_shared ( self , original_token ) : sid = self . __new_sid ( ) token = SymbolToken ( original_token . text , sid , self . __import_location ( sid ) ) self . __add ( token ) return token
Adds a token normalizing the SID and import reference to this table .
233,760
def __add_import ( self , original_token ) : sid = self . __new_sid ( ) token = SymbolToken ( original_token . text , sid , original_token . location ) self . __add ( token ) return token
Adds a token normalizing only the SID
233,761
def __add_text ( self , text ) : if text is not None and not isinstance ( text , six . text_type ) : raise TypeError ( 'Local symbol definition must be a Unicode sequence or None: %r' % text ) sid = self . __new_sid ( ) location = None if self . table_type . is_shared : location = self . __import_location ( sid ) token...
Adds the given Unicode text as a locally defined symbol .
233,762
def intern ( self , text ) : if self . table_type . is_shared : raise TypeError ( 'Cannot intern on shared symbol table' ) if not isinstance ( text , six . text_type ) : raise TypeError ( 'Cannot intern non-Unicode sequence into symbol table: %r' % text ) token = self . get ( text ) if token is None : token = self . __...
Interns the given Unicode sequence into the symbol table .
233,763
def get ( self , key , default = None ) : if isinstance ( key , six . text_type ) : return self . __mapping . get ( key , None ) if not isinstance ( key , int ) : raise TypeError ( 'Key must be int or Unicode sequence.' ) if key == 0 : return SYMBOL_ZERO_TOKEN index = key - 1 if index < 0 or key > len ( self ) : return...
Returns a token by text or local ID with a default .
233,764
def register ( self , table ) : if table . table_type . is_system : raise ValueError ( 'Cannot add system table to catalog' ) if not table . table_type . is_shared : raise ValueError ( 'Cannot add local table to catalog' ) if table . is_substitute : raise ValueError ( 'Cannot add substitute table to catalog' ) versions...
Adds a shared table to the catalog .
233,765
def resolve ( self , name , version , max_id ) : if not isinstance ( name , six . text_type ) : raise TypeError ( 'Name must be a Unicode sequence: %r' % name ) if not isinstance ( version , int ) : raise TypeError ( 'Version must be an int: %r' % version ) if version <= 0 : raise ValueError ( 'Version must be positive...
Resolves the table for a given name and version .
233,766
def start_container ( self ) : self . __container_lengths . append ( self . current_container_length ) self . current_container_length = 0 new_container_node = _Node ( ) self . __container_node . add_child ( new_container_node ) self . __container_nodes . append ( self . __container_node ) self . __container_node = new...
Add a node to the tree that represents the start of a container .
233,767
def end_container ( self , header_buf ) : if not self . __container_nodes : raise ValueError ( "Attempted to end container with none active." ) self . __container_node . add_leaf ( _Node ( header_buf ) ) self . __container_node = self . __container_nodes . pop ( ) parent_container_length = self . __container_lengths . ...
Add a node containing the container s header to the current subtree .
233,768
def add_scalar_value ( self , value_buf ) : self . __container_node . add_child ( _Node ( value_buf ) ) self . current_container_length += len ( value_buf )
Add a node to the tree containing a scalar value .
233,769
def drain ( self ) : if self . __container_nodes : raise ValueError ( "Attempted to drain without ending all containers." ) for buf in self . __depth_traverse ( self . __root ) : if buf is not None : yield buf self . __reset ( )
Walk the BufferTree and reset it when finished .
233,770
def ion_equals ( a , b , timestamps_instants_only = False ) : if timestamps_instants_only : return _ion_equals_timestamps_instants ( a , b ) return _ion_equals_timestamps_data_model ( a , b )
Tests two objects for equivalence under the Ion data model .
233,771
def _ion_equals ( a , b , timestamp_comparison_func , recursive_comparison_func ) : for a , b in ( ( a , b ) , ( b , a ) ) : if isinstance ( a , _IonNature ) : if isinstance ( b , _IonNature ) : eq = a . ion_type is b . ion_type and _annotations_eq ( a , b ) else : eq = not a . ion_annotations if eq : if isinstance ( a...
Compares a and b according to the description of the ion_equals method .
233,772
def _timestamps_eq ( a , b ) : assert isinstance ( a , datetime ) if not isinstance ( b , datetime ) : return False if ( a . tzinfo is None ) ^ ( b . tzinfo is None ) : return False if a . utcoffset ( ) != b . utcoffset ( ) : return False for a , b in ( ( a , b ) , ( b , a ) ) : if isinstance ( a , Timestamp ) : if isi...
Compares two timestamp operands for equivalence under the Ion data model .
233,773
def _timestamp_instants_eq ( a , b ) : assert isinstance ( a , datetime ) if not isinstance ( b , datetime ) : return False if a . tzinfo is None : a = a . replace ( tzinfo = OffsetTZInfo ( ) ) if b . tzinfo is None : b = b . replace ( tzinfo = OffsetTZInfo ( ) ) return a == b
Compares two timestamp operands for point - in - time equivalence only .
233,774
def _parse_var_int_components ( buf , signed ) : value = 0 sign = 1 while True : ch = buf . read ( 1 ) if ch == '' : raise IonException ( 'Variable integer under-run' ) octet = ord ( ch ) if signed : if octet & _VAR_INT_SIGN_MASK : sign = - 1 value = octet & _VAR_INT_SIGN_VALUE_MASK signed = False else : value <<= _VAR...
Parses a VarInt or VarUInt field from a file - like object .
233,775
def _parse_signed_int_components ( buf ) : sign_bit = 0 value = 0 first = True while True : ch = buf . read ( 1 ) if ch == b'' : break octet = ord ( ch ) if first : if octet & _SIGNED_INT_SIGN_MASK : sign_bit = 1 value = octet & _SIGNED_INT_SIGN_VALUE_MASK first = False else : value <<= 8 value |= octet return sign_bit...
Parses the remainder of a file - like object as a signed magnitude value .
233,776
def _parse_decimal ( buf ) : exponent = _parse_var_int ( buf , signed = True ) sign_bit , coefficient = _parse_signed_int_components ( buf ) if coefficient == 0 : value = Decimal ( ( sign_bit , ( 0 , ) , exponent ) ) else : coefficient *= sign_bit and - 1 or 1 value = Decimal ( coefficient ) . scaleb ( exponent ) retur...
Parses the remainder of a file - like object as a decimal .
233,777
def _create_delegate_handler ( delegate ) : @ coroutine def handler ( * args ) : yield yield delegate . send ( Transition ( args , delegate ) ) return handler
Creates a handler function that creates a co - routine that can yield once with the given positional arguments to the delegate as a transition .
233,778
def _var_uint_field_handler ( handler , ctx ) : _ , self = yield queue = ctx . queue value = 0 while True : if len ( queue ) == 0 : yield ctx . read_data_transition ( 1 , self ) octet = queue . read_byte ( ) value <<= _VAR_INT_VALUE_BITS value |= octet & _VAR_INT_VALUE_MASK if octet & _VAR_INT_SIGNAL_MASK : break yield...
Handler co - routine for variable unsigned integer fields that .
233,779
def _length_scalar_handler ( scalar_factory , ion_type , length , ctx ) : _ , self = yield if length == 0 : data = b'' else : yield ctx . read_data_transition ( length , self ) data = ctx . queue . read ( length ) scalar = scalar_factory ( data ) event_cls = IonEvent if callable ( scalar ) : event_cls = IonThunkEvent y...
Handles scalars scalar_factory is a function that returns a value or thunk .
233,780
def _annotation_handler ( ion_type , length , ctx ) : _ , self = yield self_handler = _create_delegate_handler ( self ) if ctx . annotations is not None : raise IonException ( 'Annotation cannot be nested in annotations' ) ctx = ctx . derive_container_context ( length , add_depth = 0 ) ( ann_length , _ ) , _ = yield ct...
Handles annotations . ion_type is ignored .
233,781
def _ordered_struct_start_handler ( handler , ctx ) : _ , self = yield self_handler = _create_delegate_handler ( self ) ( length , _ ) , _ = yield ctx . immediate_transition ( _var_uint_field_handler ( self_handler , ctx ) ) if length < 2 : raise IonException ( 'Ordered structs (type ID 0xD1) must have at least one fie...
Handles the special case of ordered structs specified by the type ID 0xD1 .
233,782
def _container_start_handler ( ion_type , length , ctx ) : _ , self = yield container_ctx = ctx . derive_container_context ( length ) if ctx . annotations and ctx . limit != container_ctx . limit : raise IonException ( 'Incorrect annotation wrapper length.' ) delegate = _container_handler ( ion_type , container_ctx ) y...
Handles container delegation .
233,783
def _bind_length_handlers ( tids , user_handler , lns ) : for tid in tids : for ln in lns : type_octet = _gen_type_octet ( tid , ln ) ion_type = _TID_VALUE_TYPE_TABLE [ tid ] if ln == 1 and ion_type is IonType . STRUCT : handler = partial ( _ordered_struct_start_handler , partial ( user_handler , ion_type ) ) elif ln <...
Binds a set of handlers with the given factory .
233,784
def _bind_length_scalar_handlers ( tids , scalar_factory , lns = _NON_ZERO_LENGTH_LNS ) : handler = partial ( _length_scalar_handler , scalar_factory ) return _bind_length_handlers ( tids , handler , lns )
Binds a set of scalar handlers for an inclusive range of low - nibble values .
233,785
def remaining ( self ) : if self . depth == 0 : return _STREAM_REMAINING return self . limit - self . queue . position
Determines how many bytes are remaining in the current context .
233,786
def read_data_transition ( self , length , whence = None , skip = False , stream_event = ION_STREAM_INCOMPLETE_EVENT ) : if whence is None : whence = self . whence return Transition ( None , _read_data_handler ( length , whence , self , skip , stream_event ) )
Returns an immediate event_transition to read a specified number of bytes .
233,787
def _narrow_unichr ( code_point ) : try : if len ( code_point . char ) > 1 : return code_point . char except AttributeError : pass return six . unichr ( code_point )
Retrieves the unicode character representing any given code point in a way that won t break on narrow builds .
233,788
def reader_trampoline ( start , allow_flush = False ) : data_event = yield if data_event is None or data_event . type is not ReadEventType . NEXT : raise TypeError ( 'Reader must be started with NEXT' ) trans = Transition ( None , start ) while True : trans = trans . delegate . send ( Transition ( data_event , trans . ...
Provides the co - routine trampoline for a reader state machine .
233,789
def blocking_reader ( reader , input , buffer_size = _DEFAULT_BUFFER_SIZE ) : ion_event = None while True : read_event = ( yield ion_event ) ion_event = reader . send ( read_event ) while ion_event is not None and ion_event . event_type . is_stream_signal : data = input . read ( buffer_size ) if len ( data ) == 0 : if ...
Provides an implementation of using the reader co - routine with a file - like object .
233,790
def read ( self , length , skip = False ) : if length > self . __size : raise IndexError ( 'Cannot pop %d bytes, %d bytes in buffer queue' % ( length , self . __size ) ) self . position += length self . __size -= length segments = self . __segments offset = self . __offset data = self . __data_cls ( ) while length > 0 ...
Consumes the first length bytes from the accumulator .
233,791
def unread ( self , c ) : if self . position < 1 : raise IndexError ( 'Cannot unread an empty buffer queue.' ) if isinstance ( c , six . text_type ) : if not self . is_unicode : BufferQueue . _incompatible_types ( self . is_unicode , c ) else : c = self . __chr ( c ) num_code_units = self . is_unicode and len ( c ) or ...
Unread the given character byte or code point .
233,792
def skip ( self , length ) : if length >= self . __size : skip_amount = self . __size rem = length - skip_amount self . __segments . clear ( ) self . __offset = 0 self . __size = 0 self . position += skip_amount else : rem = 0 self . read ( length , skip = True ) return rem
Removes length bytes and returns the number length still required to skip
233,793
def managed_reader ( reader , catalog = None ) : if catalog is None : catalog = SymbolTableCatalog ( ) ctx = _ManagedContext ( catalog ) symbol_trans = Transition ( None , None ) ion_event = None while True : if symbol_trans . delegate is not None and ion_event is not None and not ion_event . event_type . is_stream_sig...
Managed reader wrapping another reader .
233,794
def _illegal_character ( c , ctx , message = '' ) : container_type = ctx . container . ion_type is None and 'top-level' or ctx . container . ion_type . name value_type = ctx . ion_type is None and 'unknown' or ctx . ion_type . name if c is None : header = 'Illegal token' else : c = 'EOF' if BufferQueue . is_eof ( c ) e...
Raises an IonException upon encountering the given illegal character in the given context .
233,795
def _defaultdict ( dct , fallback = _illegal_character ) : out = defaultdict ( lambda : fallback ) for k , v in six . iteritems ( dct ) : out [ k ] = v return out
Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is accessed .
233,796
def _number_negative_start_handler ( c , ctx ) : assert c == _MINUS assert len ( ctx . value ) == 0 ctx . set_ion_type ( IonType . INT ) ctx . value . append ( c ) c , _ = yield yield ctx . immediate_transition ( _NEGATIVE_TABLE [ c ] ( c , ctx ) )
Handles numeric values that start with a negative sign . Branches to delegate co - routines according to _NEGATIVE_TABLE .
233,797
def _number_zero_start_handler ( c , ctx ) : assert c == _ZERO assert len ( ctx . value ) == 0 or ( len ( ctx . value ) == 1 and ctx . value [ 0 ] == _MINUS ) ctx . set_ion_type ( IonType . INT ) ctx . value . append ( c ) c , _ = yield if _ends_value ( c ) : trans = ctx . event_transition ( IonThunkEvent , IonEventTyp...
Handles numeric values that start with zero or negative zero . Branches to delegate co - routines according to _ZERO_START_TABLE .
233,798
def _number_or_timestamp_handler ( c , ctx ) : assert c in _DIGITS ctx . set_ion_type ( IonType . INT ) val = ctx . value val . append ( c ) c , self = yield trans = ctx . immediate_transition ( self ) while True : if _ends_value ( c ) : trans = ctx . event_transition ( IonThunkEvent , IonEventType . SCALAR , ctx . ion...
Handles numeric values that start with digits 1 - 9 . May terminate a value in which case that value is an int . If it does not terminate a value it branches to delegate co - routines according to _NUMBER_OR_TIMESTAMP_TABLE .
233,799
def _number_slash_end_handler ( c , ctx , event ) : assert c == _SLASH c , self = yield next_ctx = ctx . derive_child_context ( ctx . whence ) comment = _comment_handler ( _SLASH , next_ctx , next_ctx . whence ) comment . send ( ( c , comment ) ) yield _CompositeTransition ( event , ctx , comment , next_ctx , initializ...
Handles numeric values that end in a forward slash . This is only legal if the slash begins a comment ; thus this co - routine either results in an error being raised or an event being yielded .