repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
timothyb0912/pylogit
pylogit/bootstrap.py
Boot.calc_percentile_interval
def calc_percentile_interval(self, conf_percentage): """ Calculates percentile bootstrap confidence intervals for one's model. Parameters ---------- conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level for the returned endpoints. For instance, to calculate a 95% confidence interval, pass `95`. Returns ------- None. Will store the percentile intervals as `self.percentile_interval` Notes ----- Must have all ready called `self.generate_bootstrap_replicates`. """ # Get the alpha % that corresponds to the given confidence percentage. alpha = bc.get_alpha_from_conf_percentage(conf_percentage) # Create the column names for the dataframe of confidence intervals single_column_names =\ ['{:.3g}%'.format(alpha / 2.0), '{:.3g}%'.format(100 - alpha / 2.0)] # Calculate the desired confidence intervals. conf_intervals =\ bc.calc_percentile_interval(self.bootstrap_replicates.values, conf_percentage) # Store the desired confidence intervals self.percentile_interval =\ pd.DataFrame(conf_intervals.T, index=self.mle_params.index, columns=single_column_names) return None
python
def calc_percentile_interval(self, conf_percentage): """ Calculates percentile bootstrap confidence intervals for one's model. Parameters ---------- conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level for the returned endpoints. For instance, to calculate a 95% confidence interval, pass `95`. Returns ------- None. Will store the percentile intervals as `self.percentile_interval` Notes ----- Must have all ready called `self.generate_bootstrap_replicates`. """ # Get the alpha % that corresponds to the given confidence percentage. alpha = bc.get_alpha_from_conf_percentage(conf_percentage) # Create the column names for the dataframe of confidence intervals single_column_names =\ ['{:.3g}%'.format(alpha / 2.0), '{:.3g}%'.format(100 - alpha / 2.0)] # Calculate the desired confidence intervals. conf_intervals =\ bc.calc_percentile_interval(self.bootstrap_replicates.values, conf_percentage) # Store the desired confidence intervals self.percentile_interval =\ pd.DataFrame(conf_intervals.T, index=self.mle_params.index, columns=single_column_names) return None
[ "def", "calc_percentile_interval", "(", "self", ",", "conf_percentage", ")", ":", "# Get the alpha % that corresponds to the given confidence percentage.", "alpha", "=", "bc", ".", "get_alpha_from_conf_percentage", "(", "conf_percentage", ")", "# Create the column names for the dataframe of confidence intervals", "single_column_names", "=", "[", "'{:.3g}%'", ".", "format", "(", "alpha", "/", "2.0", ")", ",", "'{:.3g}%'", ".", "format", "(", "100", "-", "alpha", "/", "2.0", ")", "]", "# Calculate the desired confidence intervals.", "conf_intervals", "=", "bc", ".", "calc_percentile_interval", "(", "self", ".", "bootstrap_replicates", ".", "values", ",", "conf_percentage", ")", "# Store the desired confidence intervals", "self", ".", "percentile_interval", "=", "pd", ".", "DataFrame", "(", "conf_intervals", ".", "T", ",", "index", "=", "self", ".", "mle_params", ".", "index", ",", "columns", "=", "single_column_names", ")", "return", "None" ]
Calculates percentile bootstrap confidence intervals for one's model. Parameters ---------- conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level for the returned endpoints. For instance, to calculate a 95% confidence interval, pass `95`. Returns ------- None. Will store the percentile intervals as `self.percentile_interval` Notes ----- Must have all ready called `self.generate_bootstrap_replicates`.
[ "Calculates", "percentile", "bootstrap", "confidence", "intervals", "for", "one", "s", "model", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap.py#L663-L696
train
233,700
timothyb0912/pylogit
pylogit/bootstrap.py
Boot.calc_abc_interval
def calc_abc_interval(self, conf_percentage, init_vals, epsilon=0.001, **fit_kwargs): """ Calculates Approximate Bootstrap Confidence Intervals for one's model. Parameters ---------- conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level for the returned endpoints. For instance, to calculate a 95% confidence interval, pass `95`. init_vals : 1D ndarray. The initial values used to estimate the one's choice model. epsilon : positive float, optional. Should denote the 'very small' value being used to calculate the desired finite difference approximations to the various influence functions. Should be close to zero. Default == sys.float_info.epsilon. fit_kwargs : additional keyword arguments, optional. Should contain any additional kwargs used to alter the default behavior of `model_obj.fit_mle` and thereby enforce conformity with how the MLE was obtained. Will be passed directly to `model_obj.fit_mle`. Returns ------- None. Will store the ABC intervals as `self.abc_interval`. """ print("Calculating Approximate Bootstrap Confidence (ABC) Intervals") print(time.strftime("%a %m-%d-%Y %I:%M%p")) sys.stdout.flush() # Get the alpha % that corresponds to the given confidence percentage. alpha = bc.get_alpha_from_conf_percentage(conf_percentage) # Create the column names for the dataframe of confidence intervals single_column_names =\ ['{:.3g}%'.format(alpha / 2.0), '{:.3g}%'.format(100 - alpha / 2.0)] # Calculate the ABC confidence intervals conf_intervals =\ abc.calc_abc_interval(self.model_obj, self.mle_params.values, init_vals, conf_percentage, epsilon=epsilon, **fit_kwargs) # Store the ABC confidence intervals self.abc_interval = pd.DataFrame(conf_intervals.T, index=self.mle_params.index, columns=single_column_names) return None
python
def calc_abc_interval(self, conf_percentage, init_vals, epsilon=0.001, **fit_kwargs): """ Calculates Approximate Bootstrap Confidence Intervals for one's model. Parameters ---------- conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level for the returned endpoints. For instance, to calculate a 95% confidence interval, pass `95`. init_vals : 1D ndarray. The initial values used to estimate the one's choice model. epsilon : positive float, optional. Should denote the 'very small' value being used to calculate the desired finite difference approximations to the various influence functions. Should be close to zero. Default == sys.float_info.epsilon. fit_kwargs : additional keyword arguments, optional. Should contain any additional kwargs used to alter the default behavior of `model_obj.fit_mle` and thereby enforce conformity with how the MLE was obtained. Will be passed directly to `model_obj.fit_mle`. Returns ------- None. Will store the ABC intervals as `self.abc_interval`. """ print("Calculating Approximate Bootstrap Confidence (ABC) Intervals") print(time.strftime("%a %m-%d-%Y %I:%M%p")) sys.stdout.flush() # Get the alpha % that corresponds to the given confidence percentage. alpha = bc.get_alpha_from_conf_percentage(conf_percentage) # Create the column names for the dataframe of confidence intervals single_column_names =\ ['{:.3g}%'.format(alpha / 2.0), '{:.3g}%'.format(100 - alpha / 2.0)] # Calculate the ABC confidence intervals conf_intervals =\ abc.calc_abc_interval(self.model_obj, self.mle_params.values, init_vals, conf_percentage, epsilon=epsilon, **fit_kwargs) # Store the ABC confidence intervals self.abc_interval = pd.DataFrame(conf_intervals.T, index=self.mle_params.index, columns=single_column_names) return None
[ "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", "(", ")", "# Get the alpha % that corresponds to the given confidence percentage.", "alpha", "=", "bc", ".", "get_alpha_from_conf_percentage", "(", "conf_percentage", ")", "# Create the column names for the dataframe of confidence intervals", "single_column_names", "=", "[", "'{:.3g}%'", ".", "format", "(", "alpha", "/", "2.0", ")", ",", "'{:.3g}%'", ".", "format", "(", "100", "-", "alpha", "/", "2.0", ")", "]", "# Calculate the ABC confidence intervals", "conf_intervals", "=", "abc", ".", "calc_abc_interval", "(", "self", ".", "model_obj", ",", "self", ".", "mle_params", ".", "values", ",", "init_vals", ",", "conf_percentage", ",", "epsilon", "=", "epsilon", ",", "*", "*", "fit_kwargs", ")", "# Store the ABC confidence intervals", "self", ".", "abc_interval", "=", "pd", ".", "DataFrame", "(", "conf_intervals", ".", "T", ",", "index", "=", "self", ".", "mle_params", ".", "index", ",", "columns", "=", "single_column_names", ")", "return", "None" ]
Calculates Approximate Bootstrap Confidence Intervals for one's model. Parameters ---------- conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level for the returned endpoints. For instance, to calculate a 95% confidence interval, pass `95`. init_vals : 1D ndarray. The initial values used to estimate the one's choice model. epsilon : positive float, optional. Should denote the 'very small' value being used to calculate the desired finite difference approximations to the various influence functions. Should be close to zero. Default == sys.float_info.epsilon. fit_kwargs : additional keyword arguments, optional. Should contain any additional kwargs used to alter the default behavior of `model_obj.fit_mle` and thereby enforce conformity with how the MLE was obtained. Will be passed directly to `model_obj.fit_mle`. Returns ------- None. Will store the ABC intervals as `self.abc_interval`.
[ "Calculates", "Approximate", "Bootstrap", "Confidence", "Intervals", "for", "one", "s", "model", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap.py#L737-L788
train
233,701
timothyb0912/pylogit
pylogit/bootstrap.py
Boot.calc_conf_intervals
def calc_conf_intervals(self, conf_percentage, interval_type='all', init_vals=None, epsilon=abc.EPSILON, **fit_kwargs): """ Calculates percentile, bias-corrected and accelerated, and approximate bootstrap confidence intervals. Parameters ---------- conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level for the returned endpoints. For instance, to calculate a 95% confidence interval, pass `95`. interval_type : str in {'all', 'pi', 'bca', 'abc'}, optional. Denotes the type of confidence intervals that should be calculated. 'all' results in all types of confidence intervals being calculated. 'pi' means 'percentile intervals', 'bca' means 'bias-corrected and accelerated', and 'abc' means 'approximate bootstrap confidence' intervals. Default == 'all'. init_vals : 1D ndarray. The initial values used to estimate the one's choice model. epsilon : positive float, optional. Should denote the 'very small' value being used to calculate the desired finite difference approximations to the various influence functions for the 'abc' intervals. Should be close to zero. Default == sys.float_info.epsilon. fit_kwargs : additional keyword arguments, optional. Should contain any additional kwargs used to alter the default behavior of `model_obj.fit_mle` and thereby enforce conformity with how the MLE was obtained. Will be passed directly to `model_obj.fit_mle` when calculating the 'abc' intervals. Returns ------- None. Will store the confidence intervals on their respective model objects: `self.percentile_interval`, `self.bca_interval`, `self.abc_interval`, or all of these objects. """ if interval_type == 'pi': self.calc_percentile_interval(conf_percentage) elif interval_type == 'bca': self.calc_bca_interval(conf_percentage) elif interval_type == 'abc': self.calc_abc_interval(conf_percentage, init_vals, epsilon=epsilon, **fit_kwargs) elif interval_type == 'all': print("Calculating Percentile Confidence Intervals") sys.stdout.flush() self.calc_percentile_interval(conf_percentage) print("Calculating BCa Confidence Intervals") sys.stdout.flush() self.calc_bca_interval(conf_percentage) # Note we don't print a user message here since that is done in # self.calc_abc_interval(). self.calc_abc_interval(conf_percentage, init_vals, epsilon=epsilon, **fit_kwargs) # Get the alpha % for the given confidence percentage. alpha = bc.get_alpha_from_conf_percentage(conf_percentage) # Get lists of the interval type names and the endpoint names interval_type_names = ['percentile_interval', 'BCa_interval', 'ABC_interval'] endpoint_names = ['{:.3g}%'.format(alpha / 2.0), '{:.3g}%'.format(100 - alpha / 2.0)] # Create the column names for the dataframe of confidence intervals multi_index_names =\ list(itertools.product(interval_type_names, endpoint_names)) df_column_index = pd.MultiIndex.from_tuples(multi_index_names) # Create the dataframe containing all confidence intervals self.all_intervals = pd.concat([self.percentile_interval, self.bca_interval, self.abc_interval], axis=1, ignore_index=True) # Store the column names for the combined confidence intervals self.all_intervals.columns = df_column_index self.all_intervals.index = self.mle_params.index else: msg =\ "interval_type MUST be in `['pi', 'bca', 'abc', 'all']`" raise ValueError(msg) return None
python
def calc_conf_intervals(self, conf_percentage, interval_type='all', init_vals=None, epsilon=abc.EPSILON, **fit_kwargs): """ Calculates percentile, bias-corrected and accelerated, and approximate bootstrap confidence intervals. Parameters ---------- conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level for the returned endpoints. For instance, to calculate a 95% confidence interval, pass `95`. interval_type : str in {'all', 'pi', 'bca', 'abc'}, optional. Denotes the type of confidence intervals that should be calculated. 'all' results in all types of confidence intervals being calculated. 'pi' means 'percentile intervals', 'bca' means 'bias-corrected and accelerated', and 'abc' means 'approximate bootstrap confidence' intervals. Default == 'all'. init_vals : 1D ndarray. The initial values used to estimate the one's choice model. epsilon : positive float, optional. Should denote the 'very small' value being used to calculate the desired finite difference approximations to the various influence functions for the 'abc' intervals. Should be close to zero. Default == sys.float_info.epsilon. fit_kwargs : additional keyword arguments, optional. Should contain any additional kwargs used to alter the default behavior of `model_obj.fit_mle` and thereby enforce conformity with how the MLE was obtained. Will be passed directly to `model_obj.fit_mle` when calculating the 'abc' intervals. Returns ------- None. Will store the confidence intervals on their respective model objects: `self.percentile_interval`, `self.bca_interval`, `self.abc_interval`, or all of these objects. """ if interval_type == 'pi': self.calc_percentile_interval(conf_percentage) elif interval_type == 'bca': self.calc_bca_interval(conf_percentage) elif interval_type == 'abc': self.calc_abc_interval(conf_percentage, init_vals, epsilon=epsilon, **fit_kwargs) elif interval_type == 'all': print("Calculating Percentile Confidence Intervals") sys.stdout.flush() self.calc_percentile_interval(conf_percentage) print("Calculating BCa Confidence Intervals") sys.stdout.flush() self.calc_bca_interval(conf_percentage) # Note we don't print a user message here since that is done in # self.calc_abc_interval(). self.calc_abc_interval(conf_percentage, init_vals, epsilon=epsilon, **fit_kwargs) # Get the alpha % for the given confidence percentage. alpha = bc.get_alpha_from_conf_percentage(conf_percentage) # Get lists of the interval type names and the endpoint names interval_type_names = ['percentile_interval', 'BCa_interval', 'ABC_interval'] endpoint_names = ['{:.3g}%'.format(alpha / 2.0), '{:.3g}%'.format(100 - alpha / 2.0)] # Create the column names for the dataframe of confidence intervals multi_index_names =\ list(itertools.product(interval_type_names, endpoint_names)) df_column_index = pd.MultiIndex.from_tuples(multi_index_names) # Create the dataframe containing all confidence intervals self.all_intervals = pd.concat([self.percentile_interval, self.bca_interval, self.abc_interval], axis=1, ignore_index=True) # Store the column names for the combined confidence intervals self.all_intervals.columns = df_column_index self.all_intervals.index = self.mle_params.index else: msg =\ "interval_type MUST be in `['pi', 'bca', 'abc', 'all']`" raise ValueError(msg) return None
[ "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'", ":", "self", ".", "calc_abc_interval", "(", "conf_percentage", ",", "init_vals", ",", "epsilon", "=", "epsilon", ",", "*", "*", "fit_kwargs", ")", "elif", "interval_type", "==", "'all'", ":", "print", "(", "\"Calculating Percentile Confidence Intervals\"", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "self", ".", "calc_percentile_interval", "(", "conf_percentage", ")", "print", "(", "\"Calculating BCa Confidence Intervals\"", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "self", ".", "calc_bca_interval", "(", "conf_percentage", ")", "# Note we don't print a user message here since that is done in", "# self.calc_abc_interval().", "self", ".", "calc_abc_interval", "(", "conf_percentage", ",", "init_vals", ",", "epsilon", "=", "epsilon", ",", "*", "*", "fit_kwargs", ")", "# Get the alpha % for the given confidence percentage.", "alpha", "=", "bc", ".", "get_alpha_from_conf_percentage", "(", "conf_percentage", ")", "# Get lists of the interval type names and the endpoint names", "interval_type_names", "=", "[", "'percentile_interval'", ",", "'BCa_interval'", ",", "'ABC_interval'", "]", "endpoint_names", "=", "[", "'{:.3g}%'", ".", "format", "(", "alpha", "/", "2.0", ")", ",", "'{:.3g}%'", ".", "format", "(", "100", "-", "alpha", "/", "2.0", ")", "]", "# Create the column names for the dataframe of confidence intervals", "multi_index_names", "=", "list", "(", "itertools", ".", "product", "(", "interval_type_names", ",", "endpoint_names", ")", ")", "df_column_index", "=", "pd", ".", "MultiIndex", ".", "from_tuples", "(", "multi_index_names", ")", "# Create the dataframe containing all confidence intervals", "self", ".", "all_intervals", "=", "pd", ".", "concat", "(", "[", "self", ".", "percentile_interval", ",", "self", ".", "bca_interval", ",", "self", ".", "abc_interval", "]", ",", "axis", "=", "1", ",", "ignore_index", "=", "True", ")", "# Store the column names for the combined confidence intervals", "self", ".", "all_intervals", ".", "columns", "=", "df_column_index", "self", ".", "all_intervals", ".", "index", "=", "self", ".", "mle_params", ".", "index", "else", ":", "msg", "=", "\"interval_type MUST be in `['pi', 'bca', 'abc', 'all']`\"", "raise", "ValueError", "(", "msg", ")", "return", "None" ]
Calculates percentile, bias-corrected and accelerated, and approximate bootstrap confidence intervals. Parameters ---------- conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level for the returned endpoints. For instance, to calculate a 95% confidence interval, pass `95`. interval_type : str in {'all', 'pi', 'bca', 'abc'}, optional. Denotes the type of confidence intervals that should be calculated. 'all' results in all types of confidence intervals being calculated. 'pi' means 'percentile intervals', 'bca' means 'bias-corrected and accelerated', and 'abc' means 'approximate bootstrap confidence' intervals. Default == 'all'. init_vals : 1D ndarray. The initial values used to estimate the one's choice model. epsilon : positive float, optional. Should denote the 'very small' value being used to calculate the desired finite difference approximations to the various influence functions for the 'abc' intervals. Should be close to zero. Default == sys.float_info.epsilon. fit_kwargs : additional keyword arguments, optional. Should contain any additional kwargs used to alter the default behavior of `model_obj.fit_mle` and thereby enforce conformity with how the MLE was obtained. Will be passed directly to `model_obj.fit_mle` when calculating the 'abc' intervals. Returns ------- None. Will store the confidence intervals on their respective model objects: `self.percentile_interval`, `self.bca_interval`, `self.abc_interval`, or all of these objects.
[ "Calculates", "percentile", "bias", "-", "corrected", "and", "accelerated", "and", "approximate", "bootstrap", "confidence", "intervals", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap.py#L790-L879
train
233,702
timothyb0912/pylogit
pylogit/clog_log.py
create_calc_dh_d_alpha
def create_calc_dh_d_alpha(estimator): """ 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. Parameters ---------- estimator : an instance of the estimation.LogitTypeEstimator class. Should contain a `rows_to_alts` attribute that is a 2D scipy sparse matrix that maps the rows of the `design` matrix to the alternatives available in this dataset. Should also contain an `intercept_ref_pos` attribute that is either None or an int. This attribute should denote which intercept is not being estimated (in the case of outside intercept parameters) for identification purposes. Returns ------- Callable. Will accept a 1D array of systematic utility values, a 1D array of alternative IDs, (shape parameters if there are any) and miscellaneous args and kwargs. Should return a 2D array whose elements contain the derivative of the tranformed utility vector with respect to the vector of outside intercepts. The dimensions of the returned vector should be `(design.shape[0], num_alternatives - 1)`. """ 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: dh_d_alpha = None # Create a function that will take in the pre-formed matrix, replace its # data in-place with the new data, and return the correct dh_dalpha on each # iteration of the minimizer calc_dh_d_alpha = partial(_cloglog_transform_deriv_alpha, output_array=dh_d_alpha) return calc_dh_d_alpha
python
def create_calc_dh_d_alpha(estimator): """ 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. Parameters ---------- estimator : an instance of the estimation.LogitTypeEstimator class. Should contain a `rows_to_alts` attribute that is a 2D scipy sparse matrix that maps the rows of the `design` matrix to the alternatives available in this dataset. Should also contain an `intercept_ref_pos` attribute that is either None or an int. This attribute should denote which intercept is not being estimated (in the case of outside intercept parameters) for identification purposes. Returns ------- Callable. Will accept a 1D array of systematic utility values, a 1D array of alternative IDs, (shape parameters if there are any) and miscellaneous args and kwargs. Should return a 2D array whose elements contain the derivative of the tranformed utility vector with respect to the vector of outside intercepts. The dimensions of the returned vector should be `(design.shape[0], num_alternatives - 1)`. """ 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: dh_d_alpha = None # Create a function that will take in the pre-formed matrix, replace its # data in-place with the new data, and return the correct dh_dalpha on each # iteration of the minimizer calc_dh_d_alpha = partial(_cloglog_transform_deriv_alpha, output_array=dh_d_alpha) return calc_dh_d_alpha
[ "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", ":", "dh_d_alpha", "=", "None", "# Create a function that will take in the pre-formed matrix, replace its", "# data in-place with the new data, and return the correct dh_dalpha on each", "# iteration of the minimizer", "calc_dh_d_alpha", "=", "partial", "(", "_cloglog_transform_deriv_alpha", ",", "output_array", "=", "dh_d_alpha", ")", "return", "calc_dh_d_alpha" ]
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. Parameters ---------- estimator : an instance of the estimation.LogitTypeEstimator class. Should contain a `rows_to_alts` attribute that is a 2D scipy sparse matrix that maps the rows of the `design` matrix to the alternatives available in this dataset. Should also contain an `intercept_ref_pos` attribute that is either None or an int. This attribute should denote which intercept is not being estimated (in the case of outside intercept parameters) for identification purposes. Returns ------- Callable. Will accept a 1D array of systematic utility values, a 1D array of alternative IDs, (shape parameters if there are any) and miscellaneous args and kwargs. Should return a 2D array whose elements contain the derivative of the tranformed utility vector with respect to the vector of outside intercepts. The dimensions of the returned vector should be `(design.shape[0], num_alternatives - 1)`.
[ "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", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/clog_log.py#L374-L415
train
233,703
timothyb0912/pylogit
pylogit/estimation.py
calc_individual_chi_squares
def calc_individual_chi_squares(residuals, long_probabilities, rows_to_obs): """ Calculates individual chi-squared values for each choice situation in the dataset. Parameters ---------- residuals : 1D ndarray. The choice vector minus the predicted probability of each alternative for each observation. long_probabilities : 1D ndarray. The probability of each alternative being chosen in each choice situation. rows_to_obs : 2D scipy sparse array. Should map each row of the long format dataferame to the unique observations in the dataset. Returns ------- ind_chi_squareds : 1D ndarray. Will have as many elements as there are columns in `rows_to_obs`. Each element will contain the pearson chi-squared value for the given choice situation. """ chi_squared_terms = np.square(residuals) / long_probabilities return rows_to_obs.T.dot(chi_squared_terms)
python
def calc_individual_chi_squares(residuals, long_probabilities, rows_to_obs): """ Calculates individual chi-squared values for each choice situation in the dataset. Parameters ---------- residuals : 1D ndarray. The choice vector minus the predicted probability of each alternative for each observation. long_probabilities : 1D ndarray. The probability of each alternative being chosen in each choice situation. rows_to_obs : 2D scipy sparse array. Should map each row of the long format dataferame to the unique observations in the dataset. Returns ------- ind_chi_squareds : 1D ndarray. Will have as many elements as there are columns in `rows_to_obs`. Each element will contain the pearson chi-squared value for the given choice situation. """ chi_squared_terms = np.square(residuals) / long_probabilities return rows_to_obs.T.dot(chi_squared_terms)
[ "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. Parameters ---------- residuals : 1D ndarray. The choice vector minus the predicted probability of each alternative for each observation. long_probabilities : 1D ndarray. The probability of each alternative being chosen in each choice situation. rows_to_obs : 2D scipy sparse array. Should map each row of the long format dataferame to the unique observations in the dataset. Returns ------- ind_chi_squareds : 1D ndarray. Will have as many elements as there are columns in `rows_to_obs`. Each element will contain the pearson chi-squared value for the given choice situation.
[ "Calculates", "individual", "chi", "-", "squared", "values", "for", "each", "choice", "situation", "in", "the", "dataset", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/estimation.py#L424-L451
train
233,704
timothyb0912/pylogit
pylogit/estimation.py
calc_rho_and_rho_bar_squared
def calc_rho_and_rho_bar_squared(final_log_likelihood, null_log_likelihood, num_est_parameters): """ Calculates McFadden's rho-squared and rho-bar squared for the given model. Parameters ---------- final_log_likelihood : float. The final log-likelihood of the model whose rho-squared and rho-bar squared are being calculated for. null_log_likelihood : float. The log-likelihood of the model in question, when all parameters are zero or their 'base' values. num_est_parameters : int. The number of parameters estimated in this model. Returns ------- `(rho_squared, rho_bar_squared)` : tuple of floats. The rho-squared and rho-bar-squared for the model. """ 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
python
def calc_rho_and_rho_bar_squared(final_log_likelihood, null_log_likelihood, num_est_parameters): """ Calculates McFadden's rho-squared and rho-bar squared for the given model. Parameters ---------- final_log_likelihood : float. The final log-likelihood of the model whose rho-squared and rho-bar squared are being calculated for. null_log_likelihood : float. The log-likelihood of the model in question, when all parameters are zero or their 'base' values. num_est_parameters : int. The number of parameters estimated in this model. Returns ------- `(rho_squared, rho_bar_squared)` : tuple of floats. The rho-squared and rho-bar-squared for the model. """ 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
[ "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. Parameters ---------- final_log_likelihood : float. The final log-likelihood of the model whose rho-squared and rho-bar squared are being calculated for. null_log_likelihood : float. The log-likelihood of the model in question, when all parameters are zero or their 'base' values. num_est_parameters : int. The number of parameters estimated in this model. Returns ------- `(rho_squared, rho_bar_squared)` : tuple of floats. The rho-squared and rho-bar-squared for the model.
[ "Calculates", "McFadden", "s", "rho", "-", "squared", "and", "rho", "-", "bar", "squared", "for", "the", "given", "model", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/estimation.py#L454-L480
train
233,705
timothyb0912/pylogit
pylogit/estimation.py
calc_and_store_post_estimation_results
def calc_and_store_post_estimation_results(results_dict, estimator): """ 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. Parameters ---------- results_dict : dict. This dictionary should be the dictionary returned from scipy.optimize.minimize. In particular, it should have the following keys: `["fun", "x", "log_likelihood_null"]`. estimator : an instance of the EstimationObj class. Should contain the following attributes or methods: - convenience_split_params - convenience_calc_probs - convenience_calc_gradient - convenience_calc_hessian - convenience_calc_fisher_approx - choice_vector - rows_to_obs Returns ------- results_dict : dict. The following keys will have been entered into `results_dict`: - final_log_likelihood - utility_coefs - intercept_params - shape_params - nest_params - chosen_probs - long_probs - residuals - ind_chi_squareds - rho_squared - rho_bar_squared - final_gradient - final_hessian - fisher_info """ # Store the final log-likelihood final_log_likelihood = -1 * results_dict["fun"] results_dict["final_log_likelihood"] = final_log_likelihood # Get the final array of estimated parameters final_params = results_dict["x"] # Add the estimated parameters to the results dictionary split_res = estimator.convenience_split_params(final_params, return_all_types=True) results_dict["nest_params"] = split_res[0] results_dict["shape_params"] = split_res[1] results_dict["intercept_params"] = split_res[2] results_dict["utility_coefs"] = split_res[3] # Get the probability of the chosen alternative and long_form probabilities chosen_probs, long_probs = estimator.convenience_calc_probs(final_params) results_dict["chosen_probs"] = chosen_probs results_dict["long_probs"] = long_probs ##### # Calculate the residuals and individual chi-square values ##### # Calculate the residual vector if len(long_probs.shape) == 1: residuals = estimator.choice_vector - long_probs else: residuals = estimator.choice_vector[:, None] - long_probs results_dict["residuals"] = residuals # Calculate the observation specific chi-squared components args = [residuals, long_probs, estimator.rows_to_obs] results_dict["ind_chi_squareds"] = calc_individual_chi_squares(*args) # Calculate and store the rho-squared and rho-bar-squared log_likelihood_null = results_dict["log_likelihood_null"] rho_results = calc_rho_and_rho_bar_squared(final_log_likelihood, log_likelihood_null, final_params.shape[0]) results_dict["rho_squared"] = rho_results[0] results_dict["rho_bar_squared"] = rho_results[1] ##### # Calculate the gradient, hessian, and BHHH approximation to the fisher # info matrix ##### results_dict["final_gradient"] =\ estimator.convenience_calc_gradient(final_params) results_dict["final_hessian"] =\ estimator.convenience_calc_hessian(final_params) results_dict["fisher_info"] =\ estimator.convenience_calc_fisher_approx(final_params) # Store the constrained positions that was used in this estimation process results_dict["constrained_pos"] = estimator.constrained_pos return results_dict
python
def calc_and_store_post_estimation_results(results_dict, estimator): """ 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. Parameters ---------- results_dict : dict. This dictionary should be the dictionary returned from scipy.optimize.minimize. In particular, it should have the following keys: `["fun", "x", "log_likelihood_null"]`. estimator : an instance of the EstimationObj class. Should contain the following attributes or methods: - convenience_split_params - convenience_calc_probs - convenience_calc_gradient - convenience_calc_hessian - convenience_calc_fisher_approx - choice_vector - rows_to_obs Returns ------- results_dict : dict. The following keys will have been entered into `results_dict`: - final_log_likelihood - utility_coefs - intercept_params - shape_params - nest_params - chosen_probs - long_probs - residuals - ind_chi_squareds - rho_squared - rho_bar_squared - final_gradient - final_hessian - fisher_info """ # Store the final log-likelihood final_log_likelihood = -1 * results_dict["fun"] results_dict["final_log_likelihood"] = final_log_likelihood # Get the final array of estimated parameters final_params = results_dict["x"] # Add the estimated parameters to the results dictionary split_res = estimator.convenience_split_params(final_params, return_all_types=True) results_dict["nest_params"] = split_res[0] results_dict["shape_params"] = split_res[1] results_dict["intercept_params"] = split_res[2] results_dict["utility_coefs"] = split_res[3] # Get the probability of the chosen alternative and long_form probabilities chosen_probs, long_probs = estimator.convenience_calc_probs(final_params) results_dict["chosen_probs"] = chosen_probs results_dict["long_probs"] = long_probs ##### # Calculate the residuals and individual chi-square values ##### # Calculate the residual vector if len(long_probs.shape) == 1: residuals = estimator.choice_vector - long_probs else: residuals = estimator.choice_vector[:, None] - long_probs results_dict["residuals"] = residuals # Calculate the observation specific chi-squared components args = [residuals, long_probs, estimator.rows_to_obs] results_dict["ind_chi_squareds"] = calc_individual_chi_squares(*args) # Calculate and store the rho-squared and rho-bar-squared log_likelihood_null = results_dict["log_likelihood_null"] rho_results = calc_rho_and_rho_bar_squared(final_log_likelihood, log_likelihood_null, final_params.shape[0]) results_dict["rho_squared"] = rho_results[0] results_dict["rho_bar_squared"] = rho_results[1] ##### # Calculate the gradient, hessian, and BHHH approximation to the fisher # info matrix ##### results_dict["final_gradient"] =\ estimator.convenience_calc_gradient(final_params) results_dict["final_hessian"] =\ estimator.convenience_calc_hessian(final_params) results_dict["fisher_info"] =\ estimator.convenience_calc_fisher_approx(final_params) # Store the constrained positions that was used in this estimation process results_dict["constrained_pos"] = estimator.constrained_pos return results_dict
[ "def", "calc_and_store_post_estimation_results", "(", "results_dict", ",", "estimator", ")", ":", "# Store the final log-likelihood", "final_log_likelihood", "=", "-", "1", "*", "results_dict", "[", "\"fun\"", "]", "results_dict", "[", "\"final_log_likelihood\"", "]", "=", "final_log_likelihood", "# Get the final array of estimated parameters", "final_params", "=", "results_dict", "[", "\"x\"", "]", "# Add the estimated parameters to the results dictionary", "split_res", "=", "estimator", ".", "convenience_split_params", "(", "final_params", ",", "return_all_types", "=", "True", ")", "results_dict", "[", "\"nest_params\"", "]", "=", "split_res", "[", "0", "]", "results_dict", "[", "\"shape_params\"", "]", "=", "split_res", "[", "1", "]", "results_dict", "[", "\"intercept_params\"", "]", "=", "split_res", "[", "2", "]", "results_dict", "[", "\"utility_coefs\"", "]", "=", "split_res", "[", "3", "]", "# Get the probability of the chosen alternative and long_form probabilities", "chosen_probs", ",", "long_probs", "=", "estimator", ".", "convenience_calc_probs", "(", "final_params", ")", "results_dict", "[", "\"chosen_probs\"", "]", "=", "chosen_probs", "results_dict", "[", "\"long_probs\"", "]", "=", "long_probs", "#####", "# Calculate the residuals and individual chi-square values", "#####", "# Calculate the residual vector", "if", "len", "(", "long_probs", ".", "shape", ")", "==", "1", ":", "residuals", "=", "estimator", ".", "choice_vector", "-", "long_probs", "else", ":", "residuals", "=", "estimator", ".", "choice_vector", "[", ":", ",", "None", "]", "-", "long_probs", "results_dict", "[", "\"residuals\"", "]", "=", "residuals", "# Calculate the observation specific chi-squared components", "args", "=", "[", "residuals", ",", "long_probs", ",", "estimator", ".", "rows_to_obs", "]", "results_dict", "[", "\"ind_chi_squareds\"", "]", "=", "calc_individual_chi_squares", "(", "*", "args", ")", "# Calculate and store the rho-squared and rho-bar-squared", "log_likelihood_null", "=", "results_dict", "[", "\"log_likelihood_null\"", "]", "rho_results", "=", "calc_rho_and_rho_bar_squared", "(", "final_log_likelihood", ",", "log_likelihood_null", ",", "final_params", ".", "shape", "[", "0", "]", ")", "results_dict", "[", "\"rho_squared\"", "]", "=", "rho_results", "[", "0", "]", "results_dict", "[", "\"rho_bar_squared\"", "]", "=", "rho_results", "[", "1", "]", "#####", "# Calculate the gradient, hessian, and BHHH approximation to the fisher", "# info matrix", "#####", "results_dict", "[", "\"final_gradient\"", "]", "=", "estimator", ".", "convenience_calc_gradient", "(", "final_params", ")", "results_dict", "[", "\"final_hessian\"", "]", "=", "estimator", ".", "convenience_calc_hessian", "(", "final_params", ")", "results_dict", "[", "\"fisher_info\"", "]", "=", "estimator", ".", "convenience_calc_fisher_approx", "(", "final_params", ")", "# Store the constrained positions that was used in this estimation process", "results_dict", "[", "\"constrained_pos\"", "]", "=", "estimator", ".", "constrained_pos", "return", "results_dict" ]
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. Parameters ---------- results_dict : dict. This dictionary should be the dictionary returned from scipy.optimize.minimize. In particular, it should have the following keys: `["fun", "x", "log_likelihood_null"]`. estimator : an instance of the EstimationObj class. Should contain the following attributes or methods: - convenience_split_params - convenience_calc_probs - convenience_calc_gradient - convenience_calc_hessian - convenience_calc_fisher_approx - choice_vector - rows_to_obs Returns ------- results_dict : dict. The following keys will have been entered into `results_dict`: - final_log_likelihood - utility_coefs - intercept_params - shape_params - nest_params - chosen_probs - long_probs - residuals - ind_chi_squareds - rho_squared - rho_bar_squared - final_gradient - final_hessian - fisher_info
[ "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", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/estimation.py#L483-L583
train
233,706
timothyb0912/pylogit
pylogit/estimation.py
estimate
def estimate(init_values, estimator, method, loss_tol, gradient_tol, maxiter, print_results, use_hessian=True, just_point=False, **kwargs): """ Estimate the given choice model that is defined by `estimator`. Parameters ---------- init_vals : 1D ndarray. Should contain the initial values to start the optimization process with. estimator : an instance of the EstimationObj class. method : str, optional. Should be a valid string for scipy.optimize.minimize. Determines the optimization algorithm that is used for this problem. Default `== 'bfgs'`. loss_tol : float, optional. Determines the tolerance on the difference in objective function values from one iteration to the next that is needed to determine convergence. Default `== 1e-06`. gradient_tol : float, optional. Determines the tolerance on the difference in gradient values from one iteration to the next which is needed to determine convergence. Default `== 1e-06`. maxiter : int, optional. Determines the maximum number of iterations used by the optimizer. Default `== 1000`. print_res : bool, optional. Determines whether the timing and initial and final log likelihood results will be printed as they they are determined. Default `== True`. use_hessian : bool, optional. Determines whether the `calc_neg_hessian` method of the `estimator` object will be used as the hessian function during the estimation. This kwarg is used since some models (such as the Mixed Logit and Nested Logit) use a rather crude (i.e. the BHHH) approximation to the Fisher Information Matrix, and users may prefer to not use this approximation for the hessian during estimation. just_point : bool, optional. Determines whether or not calculations that are non-critical for obtaining the maximum likelihood point estimate will be performed. Default == False. Return ------ results : dict. The dictionary of estimation results that is returned by scipy.optimize.minimize. It will also have (at minimum) the following keys: - "log-likelihood_null" - "final_log_likelihood" - "utility_coefs" - "intercept_params" - "shape_params" - "nest_params" - "chosen_probs" - "long_probs" - "residuals" - "ind_chi_squareds" - "rho_squared" - "rho_bar_squared" - "final_gradient" - "final_hessian" - "fisher_info" """ if not just_point: # Perform preliminary calculations log_likelihood_at_zero =\ estimator.convenience_calc_log_likelihood(estimator.zero_vector) initial_log_likelihood =\ estimator.convenience_calc_log_likelihood(init_values) if print_results: # Print the log-likelihood at zero null_msg = "Log-likelihood at zero: {:,.4f}" print(null_msg.format(log_likelihood_at_zero)) # Print the log-likelihood at the starting values init_msg = "Initial Log-likelihood: {:,.4f}" print(init_msg.format(initial_log_likelihood)) sys.stdout.flush() # Get the hessian fucntion for this estimation process hess_func = estimator.calc_neg_hessian if use_hessian else None # Estimate the actual parameters of the model start_time = time.time() results = minimize(estimator.calc_neg_log_likelihood_and_neg_gradient, init_values, method=method, jac=True, hess=hess_func, tol=loss_tol, options={'gtol': gradient_tol, "maxiter": maxiter}, **kwargs) if not just_point: if print_results: # Stop timing the estimation process and report the timing results end_time = time.time() elapsed_sec = (end_time - start_time) elapsed_min = elapsed_sec / 60.0 if elapsed_min > 1.0: msg = "Estimation Time for Point Estimation: {:.2f} minutes." print(msg.format(elapsed_min)) else: msg = "Estimation Time for Point Estimation: {:.2f} seconds." print(msg.format(elapsed_sec)) print("Final log-likelihood: {:,.4f}".format(-1 * results["fun"])) sys.stdout.flush() # Store the log-likelihood at zero results["log_likelihood_null"] = log_likelihood_at_zero # Calculate and store the post-estimation results results = calc_and_store_post_estimation_results(results, estimator) return results
python
def estimate(init_values, estimator, method, loss_tol, gradient_tol, maxiter, print_results, use_hessian=True, just_point=False, **kwargs): """ Estimate the given choice model that is defined by `estimator`. Parameters ---------- init_vals : 1D ndarray. Should contain the initial values to start the optimization process with. estimator : an instance of the EstimationObj class. method : str, optional. Should be a valid string for scipy.optimize.minimize. Determines the optimization algorithm that is used for this problem. Default `== 'bfgs'`. loss_tol : float, optional. Determines the tolerance on the difference in objective function values from one iteration to the next that is needed to determine convergence. Default `== 1e-06`. gradient_tol : float, optional. Determines the tolerance on the difference in gradient values from one iteration to the next which is needed to determine convergence. Default `== 1e-06`. maxiter : int, optional. Determines the maximum number of iterations used by the optimizer. Default `== 1000`. print_res : bool, optional. Determines whether the timing and initial and final log likelihood results will be printed as they they are determined. Default `== True`. use_hessian : bool, optional. Determines whether the `calc_neg_hessian` method of the `estimator` object will be used as the hessian function during the estimation. This kwarg is used since some models (such as the Mixed Logit and Nested Logit) use a rather crude (i.e. the BHHH) approximation to the Fisher Information Matrix, and users may prefer to not use this approximation for the hessian during estimation. just_point : bool, optional. Determines whether or not calculations that are non-critical for obtaining the maximum likelihood point estimate will be performed. Default == False. Return ------ results : dict. The dictionary of estimation results that is returned by scipy.optimize.minimize. It will also have (at minimum) the following keys: - "log-likelihood_null" - "final_log_likelihood" - "utility_coefs" - "intercept_params" - "shape_params" - "nest_params" - "chosen_probs" - "long_probs" - "residuals" - "ind_chi_squareds" - "rho_squared" - "rho_bar_squared" - "final_gradient" - "final_hessian" - "fisher_info" """ if not just_point: # Perform preliminary calculations log_likelihood_at_zero =\ estimator.convenience_calc_log_likelihood(estimator.zero_vector) initial_log_likelihood =\ estimator.convenience_calc_log_likelihood(init_values) if print_results: # Print the log-likelihood at zero null_msg = "Log-likelihood at zero: {:,.4f}" print(null_msg.format(log_likelihood_at_zero)) # Print the log-likelihood at the starting values init_msg = "Initial Log-likelihood: {:,.4f}" print(init_msg.format(initial_log_likelihood)) sys.stdout.flush() # Get the hessian fucntion for this estimation process hess_func = estimator.calc_neg_hessian if use_hessian else None # Estimate the actual parameters of the model start_time = time.time() results = minimize(estimator.calc_neg_log_likelihood_and_neg_gradient, init_values, method=method, jac=True, hess=hess_func, tol=loss_tol, options={'gtol': gradient_tol, "maxiter": maxiter}, **kwargs) if not just_point: if print_results: # Stop timing the estimation process and report the timing results end_time = time.time() elapsed_sec = (end_time - start_time) elapsed_min = elapsed_sec / 60.0 if elapsed_min > 1.0: msg = "Estimation Time for Point Estimation: {:.2f} minutes." print(msg.format(elapsed_min)) else: msg = "Estimation Time for Point Estimation: {:.2f} seconds." print(msg.format(elapsed_sec)) print("Final log-likelihood: {:,.4f}".format(-1 * results["fun"])) sys.stdout.flush() # Store the log-likelihood at zero results["log_likelihood_null"] = log_likelihood_at_zero # Calculate and store the post-estimation results results = calc_and_store_post_estimation_results(results, estimator) return results
[ "def", "estimate", "(", "init_values", ",", "estimator", ",", "method", ",", "loss_tol", ",", "gradient_tol", ",", "maxiter", ",", "print_results", ",", "use_hessian", "=", "True", ",", "just_point", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "not", "just_point", ":", "# Perform preliminary calculations", "log_likelihood_at_zero", "=", "estimator", ".", "convenience_calc_log_likelihood", "(", "estimator", ".", "zero_vector", ")", "initial_log_likelihood", "=", "estimator", ".", "convenience_calc_log_likelihood", "(", "init_values", ")", "if", "print_results", ":", "# Print the log-likelihood at zero", "null_msg", "=", "\"Log-likelihood at zero: {:,.4f}\"", "print", "(", "null_msg", ".", "format", "(", "log_likelihood_at_zero", ")", ")", "# Print the log-likelihood at the starting values", "init_msg", "=", "\"Initial Log-likelihood: {:,.4f}\"", "print", "(", "init_msg", ".", "format", "(", "initial_log_likelihood", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "# Get the hessian fucntion for this estimation process", "hess_func", "=", "estimator", ".", "calc_neg_hessian", "if", "use_hessian", "else", "None", "# Estimate the actual parameters of the model", "start_time", "=", "time", ".", "time", "(", ")", "results", "=", "minimize", "(", "estimator", ".", "calc_neg_log_likelihood_and_neg_gradient", ",", "init_values", ",", "method", "=", "method", ",", "jac", "=", "True", ",", "hess", "=", "hess_func", ",", "tol", "=", "loss_tol", ",", "options", "=", "{", "'gtol'", ":", "gradient_tol", ",", "\"maxiter\"", ":", "maxiter", "}", ",", "*", "*", "kwargs", ")", "if", "not", "just_point", ":", "if", "print_results", ":", "# Stop timing the estimation process and report the timing results", "end_time", "=", "time", ".", "time", "(", ")", "elapsed_sec", "=", "(", "end_time", "-", "start_time", ")", "elapsed_min", "=", "elapsed_sec", "/", "60.0", "if", "elapsed_min", ">", "1.0", ":", "msg", "=", "\"Estimation Time for Point Estimation: {:.2f} minutes.\"", "print", "(", "msg", ".", "format", "(", "elapsed_min", ")", ")", "else", ":", "msg", "=", "\"Estimation Time for Point Estimation: {:.2f} seconds.\"", "print", "(", "msg", ".", "format", "(", "elapsed_sec", ")", ")", "print", "(", "\"Final log-likelihood: {:,.4f}\"", ".", "format", "(", "-", "1", "*", "results", "[", "\"fun\"", "]", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "# Store the log-likelihood at zero", "results", "[", "\"log_likelihood_null\"", "]", "=", "log_likelihood_at_zero", "# Calculate and store the post-estimation results", "results", "=", "calc_and_store_post_estimation_results", "(", "results", ",", "estimator", ")", "return", "results" ]
Estimate the given choice model that is defined by `estimator`. Parameters ---------- init_vals : 1D ndarray. Should contain the initial values to start the optimization process with. estimator : an instance of the EstimationObj class. method : str, optional. Should be a valid string for scipy.optimize.minimize. Determines the optimization algorithm that is used for this problem. Default `== 'bfgs'`. loss_tol : float, optional. Determines the tolerance on the difference in objective function values from one iteration to the next that is needed to determine convergence. Default `== 1e-06`. gradient_tol : float, optional. Determines the tolerance on the difference in gradient values from one iteration to the next which is needed to determine convergence. Default `== 1e-06`. maxiter : int, optional. Determines the maximum number of iterations used by the optimizer. Default `== 1000`. print_res : bool, optional. Determines whether the timing and initial and final log likelihood results will be printed as they they are determined. Default `== True`. use_hessian : bool, optional. Determines whether the `calc_neg_hessian` method of the `estimator` object will be used as the hessian function during the estimation. This kwarg is used since some models (such as the Mixed Logit and Nested Logit) use a rather crude (i.e. the BHHH) approximation to the Fisher Information Matrix, and users may prefer to not use this approximation for the hessian during estimation. just_point : bool, optional. Determines whether or not calculations that are non-critical for obtaining the maximum likelihood point estimate will be performed. Default == False. Return ------ results : dict. The dictionary of estimation results that is returned by scipy.optimize.minimize. It will also have (at minimum) the following keys: - "log-likelihood_null" - "final_log_likelihood" - "utility_coefs" - "intercept_params" - "shape_params" - "nest_params" - "chosen_probs" - "long_probs" - "residuals" - "ind_chi_squareds" - "rho_squared" - "rho_bar_squared" - "final_gradient" - "final_hessian" - "fisher_info"
[ "Estimate", "the", "given", "choice", "model", "that", "is", "defined", "by", "estimator", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/estimation.py#L586-L713
train
233,707
timothyb0912/pylogit
pylogit/estimation.py
EstimationObj.calc_neg_log_likelihood_and_neg_gradient
def calc_neg_log_likelihood_and_neg_gradient(self, params): """ 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. """ 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, neg_gradient
python
def calc_neg_log_likelihood_and_neg_gradient(self, params): """ 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. """ 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, neg_gradient
[ "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", ",", "neg_gradient" ]
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.
[ "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", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/estimation.py#L211-L223
train
233,708
timothyb0912/pylogit
pylogit/bootstrap_utils.py
ensure_samples_is_ndim_ndarray
def ensure_samples_is_ndim_ndarray(samples, name='bootstrap', ndim=2): """ Ensures that `samples` is an `ndim` numpy array. Raises a helpful ValueError if otherwise. """ 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, ndim) raise ValueError(msg) return None
python
def ensure_samples_is_ndim_ndarray(samples, name='bootstrap', ndim=2): """ Ensures that `samples` is an `ndim` numpy array. Raises a helpful ValueError if otherwise. """ 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, ndim) raise ValueError(msg) return None
[ "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", ",", "ndim", ")", "raise", "ValueError", "(", "msg", ")", "return", "None" ]
Ensures that `samples` is an `ndim` numpy array. Raises a helpful ValueError if otherwise.
[ "Ensures", "that", "samples", "is", "an", "ndim", "numpy", "array", ".", "Raises", "a", "helpful", "ValueError", "if", "otherwise", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_utils.py#L27-L38
train
233,709
timothyb0912/pylogit
pylogit/construct_estimator.py
create_estimation_obj
def create_estimation_obj(model_obj, init_vals, mappings=None, ridge=None, constrained_pos=None, weights=None): """ Should return a model estimation object corresponding to the model type of the `model_obj`. Parameters ---------- model_obj : an instance or sublcass of the MNDC class. init_vals : 1D ndarray. The initial values to start the estimation process with. In the following order, there should be one value for each nest coefficient, shape parameter, outside intercept parameter, or index coefficient that is being estimated. mappings : OrderedDict or None, optional. Keys will be `["rows_to_obs", "rows_to_alts", "chosen_row_to_obs", "rows_to_nests"]`. The value for `rows_to_obs` will map the rows of the `long_form` to the unique observations (on the columns) in their order of appearance. The value for `rows_to_alts` will map the rows of the `long_form` to the unique alternatives which are possible in the dataset (on the columns), in sorted order--not order of appearance. The value for `chosen_row_to_obs`, if not None, will map the rows of the `long_form` that contain the chosen alternatives to the specific observations those rows are associated with (denoted by the columns). The value of `rows_to_nests`, if not None, will map the rows of the `long_form` to the nest (denoted by the column) that contains the row's alternative. Default == None. ridge : int, float, long, or None, optional. Determines whether or not ridge regression is performed. If a scalar is passed, then that scalar determines the ridge penalty for the optimization. The scalar should be greater than or equal to zero. Default `== None`. constrained_pos : list or None, optional. Denotes the positions of the array of estimated parameters that are not to change from their initial values. If a list is passed, the elements are to be integers where no such integer is greater than `init_vals.size.` Default == None. weights : 1D ndarray. Should contain the weights for each corresponding observation for each row of the long format data. """ # Get the mapping matrices for each model mapping_matrices =\ model_obj.get_mappings_for_fit() if mappings is None else mappings # Create the zero vector for each model. zero_vector = np.zeros(init_vals.shape[0]) # Get the internal model name internal_model_name = display_name_to_model_type[model_obj.model_type] # Get the split parameter function and estimator class for this model. estimator_class, current_split_func =\ (model_type_to_resources[internal_model_name]['estimator'], model_type_to_resources[internal_model_name]['split_func']) # Create the estimator instance that is desired. estimation_obj = estimator_class(model_obj, mapping_matrices, ridge, zero_vector, current_split_func, constrained_pos, weights=weights) # Return the created object return estimation_obj
python
def create_estimation_obj(model_obj, init_vals, mappings=None, ridge=None, constrained_pos=None, weights=None): """ Should return a model estimation object corresponding to the model type of the `model_obj`. Parameters ---------- model_obj : an instance or sublcass of the MNDC class. init_vals : 1D ndarray. The initial values to start the estimation process with. In the following order, there should be one value for each nest coefficient, shape parameter, outside intercept parameter, or index coefficient that is being estimated. mappings : OrderedDict or None, optional. Keys will be `["rows_to_obs", "rows_to_alts", "chosen_row_to_obs", "rows_to_nests"]`. The value for `rows_to_obs` will map the rows of the `long_form` to the unique observations (on the columns) in their order of appearance. The value for `rows_to_alts` will map the rows of the `long_form` to the unique alternatives which are possible in the dataset (on the columns), in sorted order--not order of appearance. The value for `chosen_row_to_obs`, if not None, will map the rows of the `long_form` that contain the chosen alternatives to the specific observations those rows are associated with (denoted by the columns). The value of `rows_to_nests`, if not None, will map the rows of the `long_form` to the nest (denoted by the column) that contains the row's alternative. Default == None. ridge : int, float, long, or None, optional. Determines whether or not ridge regression is performed. If a scalar is passed, then that scalar determines the ridge penalty for the optimization. The scalar should be greater than or equal to zero. Default `== None`. constrained_pos : list or None, optional. Denotes the positions of the array of estimated parameters that are not to change from their initial values. If a list is passed, the elements are to be integers where no such integer is greater than `init_vals.size.` Default == None. weights : 1D ndarray. Should contain the weights for each corresponding observation for each row of the long format data. """ # Get the mapping matrices for each model mapping_matrices =\ model_obj.get_mappings_for_fit() if mappings is None else mappings # Create the zero vector for each model. zero_vector = np.zeros(init_vals.shape[0]) # Get the internal model name internal_model_name = display_name_to_model_type[model_obj.model_type] # Get the split parameter function and estimator class for this model. estimator_class, current_split_func =\ (model_type_to_resources[internal_model_name]['estimator'], model_type_to_resources[internal_model_name]['split_func']) # Create the estimator instance that is desired. estimation_obj = estimator_class(model_obj, mapping_matrices, ridge, zero_vector, current_split_func, constrained_pos, weights=weights) # Return the created object return estimation_obj
[ "def", "create_estimation_obj", "(", "model_obj", ",", "init_vals", ",", "mappings", "=", "None", ",", "ridge", "=", "None", ",", "constrained_pos", "=", "None", ",", "weights", "=", "None", ")", ":", "# Get the mapping matrices for each model", "mapping_matrices", "=", "model_obj", ".", "get_mappings_for_fit", "(", ")", "if", "mappings", "is", "None", "else", "mappings", "# Create the zero vector for each model.", "zero_vector", "=", "np", ".", "zeros", "(", "init_vals", ".", "shape", "[", "0", "]", ")", "# Get the internal model name", "internal_model_name", "=", "display_name_to_model_type", "[", "model_obj", ".", "model_type", "]", "# Get the split parameter function and estimator class for this model.", "estimator_class", ",", "current_split_func", "=", "(", "model_type_to_resources", "[", "internal_model_name", "]", "[", "'estimator'", "]", ",", "model_type_to_resources", "[", "internal_model_name", "]", "[", "'split_func'", "]", ")", "# Create the estimator instance that is desired.", "estimation_obj", "=", "estimator_class", "(", "model_obj", ",", "mapping_matrices", ",", "ridge", ",", "zero_vector", ",", "current_split_func", ",", "constrained_pos", ",", "weights", "=", "weights", ")", "# Return the created object", "return", "estimation_obj" ]
Should return a model estimation object corresponding to the model type of the `model_obj`. Parameters ---------- model_obj : an instance or sublcass of the MNDC class. init_vals : 1D ndarray. The initial values to start the estimation process with. In the following order, there should be one value for each nest coefficient, shape parameter, outside intercept parameter, or index coefficient that is being estimated. mappings : OrderedDict or None, optional. Keys will be `["rows_to_obs", "rows_to_alts", "chosen_row_to_obs", "rows_to_nests"]`. The value for `rows_to_obs` will map the rows of the `long_form` to the unique observations (on the columns) in their order of appearance. The value for `rows_to_alts` will map the rows of the `long_form` to the unique alternatives which are possible in the dataset (on the columns), in sorted order--not order of appearance. The value for `chosen_row_to_obs`, if not None, will map the rows of the `long_form` that contain the chosen alternatives to the specific observations those rows are associated with (denoted by the columns). The value of `rows_to_nests`, if not None, will map the rows of the `long_form` to the nest (denoted by the column) that contains the row's alternative. Default == None. ridge : int, float, long, or None, optional. Determines whether or not ridge regression is performed. If a scalar is passed, then that scalar determines the ridge penalty for the optimization. The scalar should be greater than or equal to zero. Default `== None`. constrained_pos : list or None, optional. Denotes the positions of the array of estimated parameters that are not to change from their initial values. If a list is passed, the elements are to be integers where no such integer is greater than `init_vals.size.` Default == None. weights : 1D ndarray. Should contain the weights for each corresponding observation for each row of the long format data.
[ "Should", "return", "a", "model", "estimation", "object", "corresponding", "to", "the", "model", "type", "of", "the", "model_obj", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/construct_estimator.py#L54-L119
train
233,710
timothyb0912/pylogit
pylogit/bootstrap_abc.py
ensure_wide_weights_is_1D_or_2D_ndarray
def ensure_wide_weights_is_1D_or_2D_ndarray(wide_weights): """ Ensures that `wide_weights` is a 1D or 2D ndarray. Raises a helpful ValueError if otherwise. """ 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
python
def ensure_wide_weights_is_1D_or_2D_ndarray(wide_weights): """ Ensures that `wide_weights` is a 1D or 2D ndarray. Raises a helpful ValueError if otherwise. """ 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
[ "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.
[ "Ensures", "that", "wide_weights", "is", "a", "1D", "or", "2D", "ndarray", ".", "Raises", "a", "helpful", "ValueError", "if", "otherwise", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_abc.py#L51-L63
train
233,711
timothyb0912/pylogit
pylogit/bootstrap_abc.py
check_validity_of_long_form_args
def check_validity_of_long_form_args(model_obj, wide_weights, rows_to_obs): """ Ensures the args to `create_long_form_weights` have expected properties. """ # Ensure model_obj has the necessary method for create_long_form_weights ensure_model_obj_has_mapping_constructor(model_obj) # Ensure wide_weights is a 1D or 2D ndarray. ensure_wide_weights_is_1D_or_2D_ndarray(wide_weights) # Ensure rows_to_obs is a scipy sparse matrix ensure_rows_to_obs_validity(rows_to_obs) return None
python
def check_validity_of_long_form_args(model_obj, wide_weights, rows_to_obs): """ Ensures the args to `create_long_form_weights` have expected properties. """ # Ensure model_obj has the necessary method for create_long_form_weights ensure_model_obj_has_mapping_constructor(model_obj) # Ensure wide_weights is a 1D or 2D ndarray. ensure_wide_weights_is_1D_or_2D_ndarray(wide_weights) # Ensure rows_to_obs is a scipy sparse matrix ensure_rows_to_obs_validity(rows_to_obs) return None
[ "def", "check_validity_of_long_form_args", "(", "model_obj", ",", "wide_weights", ",", "rows_to_obs", ")", ":", "# Ensure model_obj has the necessary method for create_long_form_weights", "ensure_model_obj_has_mapping_constructor", "(", "model_obj", ")", "# Ensure wide_weights is a 1D or 2D ndarray.", "ensure_wide_weights_is_1D_or_2D_ndarray", "(", "wide_weights", ")", "# Ensure rows_to_obs is a scipy sparse matrix", "ensure_rows_to_obs_validity", "(", "rows_to_obs", ")", "return", "None" ]
Ensures the args to `create_long_form_weights` have expected properties.
[ "Ensures", "the", "args", "to", "create_long_form_weights", "have", "expected", "properties", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_abc.py#L66-L76
train
233,712
timothyb0912/pylogit
pylogit/bootstrap_abc.py
calc_finite_diff_terms_for_abc
def calc_finite_diff_terms_for_abc(model_obj, mle_params, init_vals, epsilon, **fit_kwargs): """ Calculates the terms needed for the finite difference approximations of the empirical influence and second order empirical influence functions. Parameters ---------- model_obj : an instance or sublcass of the MNDC class. Should be the model object that corresponds to the model we are constructing the bootstrap confidence intervals for. mle_params : 1D ndarray. Should contain the desired model's maximum likelihood point estimate. init_vals : 1D ndarray. The initial values used to estimate the desired choice model. epsilon : positive float. Should denote the 'very small' value being used to calculate the desired finite difference approximations to the various influence functions. Should be 'close' to zero. fit_kwargs : additional keyword arguments, optional. Should contain any additional kwargs used to alter the default behavior of `model_obj.fit_mle` and thereby enforce conformity with how the MLE was obtained. Will be passed directly to `model_obj.fit_mle`. Returns ------- term_plus : 2D ndarray. Should have one row for each observation. Should have one column for each parameter in the parameter vector being estimated. Elements should denote the finite difference term that comes from adding a small value to the observation corresponding to that elements respective row. term_minus : 2D ndarray. Should have one row for each observation. Should have one column for each parameter in the parameter vector being estimated. Elements should denote the finite difference term that comes from subtracting a small value to the observation corresponding to that elements respective row. References ---------- Efron, Bradley, and Robert J. Tibshirani. An Introduction to the Bootstrap. CRC press, 1994. Section 22.6, Equations 22.32 and 22.36. Notes ----- The returned, symbolic value for `term_minus` does not explicitly appear in Equations 22.32 or 22.36. However, it is used to compute a midpoint / slope approximation to the finite difference derivative used to define the empirical influence function. """ # Determine the number of observations in this dataset. num_obs = model_obj.data[model_obj.obs_id_col].unique().size # Determine the initial weights per observation. init_weights_wide = np.ones(num_obs, dtype=float) / num_obs # Initialize wide weights for elements of the second order influence array. init_wide_weights_plus = (1 - epsilon) * init_weights_wide init_wide_weights_minus = (1 + epsilon) * init_weights_wide # Initialize the second order influence array term_plus = np.empty((num_obs, init_vals.shape[0]), dtype=float) term_minus = np.empty((num_obs, init_vals.shape[0]), dtype=float) # Get the rows_to_obs mapping matrix for this model. rows_to_obs = model_obj.get_mappings_for_fit()['rows_to_obs'] # Extract the initial weights from the fit kwargs new_fit_kwargs = deepcopy(fit_kwargs) if fit_kwargs is not None and 'weights' in fit_kwargs: orig_weights = fit_kwargs['weights'] del new_fit_kwargs['weights'] else: orig_weights = 1 # Make sure we're just getting the point estimate new_fit_kwargs['just_point'] = True # Populate the second order influence array for obs in xrange(num_obs): # Note we create the long weights in a for-loop to avoid creating a # num_obs by num_obs matrix, which may be a problem for large datasets # Get the wide format weights for this observation current_wide_weights_plus = init_wide_weights_plus.copy() current_wide_weights_plus[obs] += epsilon current_wide_weights_minus = init_wide_weights_minus.copy() current_wide_weights_minus[obs] -= epsilon # Get the long format weights for this observation long_weights_plus =\ (create_long_form_weights(model_obj, current_wide_weights_plus, rows_to_obs=rows_to_obs) * orig_weights) long_weights_minus =\ (create_long_form_weights(model_obj, current_wide_weights_minus, rows_to_obs=rows_to_obs) * orig_weights) # Get the needed influence estimates. term_plus[obs] = model_obj.fit_mle(init_vals, weights=long_weights_plus, **new_fit_kwargs)['x'] term_minus[obs] = model_obj.fit_mle(init_vals, weights=long_weights_minus, **new_fit_kwargs)['x'] return term_plus, term_minus
python
def calc_finite_diff_terms_for_abc(model_obj, mle_params, init_vals, epsilon, **fit_kwargs): """ Calculates the terms needed for the finite difference approximations of the empirical influence and second order empirical influence functions. Parameters ---------- model_obj : an instance or sublcass of the MNDC class. Should be the model object that corresponds to the model we are constructing the bootstrap confidence intervals for. mle_params : 1D ndarray. Should contain the desired model's maximum likelihood point estimate. init_vals : 1D ndarray. The initial values used to estimate the desired choice model. epsilon : positive float. Should denote the 'very small' value being used to calculate the desired finite difference approximations to the various influence functions. Should be 'close' to zero. fit_kwargs : additional keyword arguments, optional. Should contain any additional kwargs used to alter the default behavior of `model_obj.fit_mle` and thereby enforce conformity with how the MLE was obtained. Will be passed directly to `model_obj.fit_mle`. Returns ------- term_plus : 2D ndarray. Should have one row for each observation. Should have one column for each parameter in the parameter vector being estimated. Elements should denote the finite difference term that comes from adding a small value to the observation corresponding to that elements respective row. term_minus : 2D ndarray. Should have one row for each observation. Should have one column for each parameter in the parameter vector being estimated. Elements should denote the finite difference term that comes from subtracting a small value to the observation corresponding to that elements respective row. References ---------- Efron, Bradley, and Robert J. Tibshirani. An Introduction to the Bootstrap. CRC press, 1994. Section 22.6, Equations 22.32 and 22.36. Notes ----- The returned, symbolic value for `term_minus` does not explicitly appear in Equations 22.32 or 22.36. However, it is used to compute a midpoint / slope approximation to the finite difference derivative used to define the empirical influence function. """ # Determine the number of observations in this dataset. num_obs = model_obj.data[model_obj.obs_id_col].unique().size # Determine the initial weights per observation. init_weights_wide = np.ones(num_obs, dtype=float) / num_obs # Initialize wide weights for elements of the second order influence array. init_wide_weights_plus = (1 - epsilon) * init_weights_wide init_wide_weights_minus = (1 + epsilon) * init_weights_wide # Initialize the second order influence array term_plus = np.empty((num_obs, init_vals.shape[0]), dtype=float) term_minus = np.empty((num_obs, init_vals.shape[0]), dtype=float) # Get the rows_to_obs mapping matrix for this model. rows_to_obs = model_obj.get_mappings_for_fit()['rows_to_obs'] # Extract the initial weights from the fit kwargs new_fit_kwargs = deepcopy(fit_kwargs) if fit_kwargs is not None and 'weights' in fit_kwargs: orig_weights = fit_kwargs['weights'] del new_fit_kwargs['weights'] else: orig_weights = 1 # Make sure we're just getting the point estimate new_fit_kwargs['just_point'] = True # Populate the second order influence array for obs in xrange(num_obs): # Note we create the long weights in a for-loop to avoid creating a # num_obs by num_obs matrix, which may be a problem for large datasets # Get the wide format weights for this observation current_wide_weights_plus = init_wide_weights_plus.copy() current_wide_weights_plus[obs] += epsilon current_wide_weights_minus = init_wide_weights_minus.copy() current_wide_weights_minus[obs] -= epsilon # Get the long format weights for this observation long_weights_plus =\ (create_long_form_weights(model_obj, current_wide_weights_plus, rows_to_obs=rows_to_obs) * orig_weights) long_weights_minus =\ (create_long_form_weights(model_obj, current_wide_weights_minus, rows_to_obs=rows_to_obs) * orig_weights) # Get the needed influence estimates. term_plus[obs] = model_obj.fit_mle(init_vals, weights=long_weights_plus, **new_fit_kwargs)['x'] term_minus[obs] = model_obj.fit_mle(init_vals, weights=long_weights_minus, **new_fit_kwargs)['x'] return term_plus, term_minus
[ "def", "calc_finite_diff_terms_for_abc", "(", "model_obj", ",", "mle_params", ",", "init_vals", ",", "epsilon", ",", "*", "*", "fit_kwargs", ")", ":", "# Determine the number of observations in this dataset.", "num_obs", "=", "model_obj", ".", "data", "[", "model_obj", ".", "obs_id_col", "]", ".", "unique", "(", ")", ".", "size", "# Determine the initial weights per observation.", "init_weights_wide", "=", "np", ".", "ones", "(", "num_obs", ",", "dtype", "=", "float", ")", "/", "num_obs", "# Initialize wide weights for elements of the second order influence array.", "init_wide_weights_plus", "=", "(", "1", "-", "epsilon", ")", "*", "init_weights_wide", "init_wide_weights_minus", "=", "(", "1", "+", "epsilon", ")", "*", "init_weights_wide", "# Initialize the second order influence array", "term_plus", "=", "np", ".", "empty", "(", "(", "num_obs", ",", "init_vals", ".", "shape", "[", "0", "]", ")", ",", "dtype", "=", "float", ")", "term_minus", "=", "np", ".", "empty", "(", "(", "num_obs", ",", "init_vals", ".", "shape", "[", "0", "]", ")", ",", "dtype", "=", "float", ")", "# Get the rows_to_obs mapping matrix for this model.", "rows_to_obs", "=", "model_obj", ".", "get_mappings_for_fit", "(", ")", "[", "'rows_to_obs'", "]", "# Extract the initial weights from the fit kwargs", "new_fit_kwargs", "=", "deepcopy", "(", "fit_kwargs", ")", "if", "fit_kwargs", "is", "not", "None", "and", "'weights'", "in", "fit_kwargs", ":", "orig_weights", "=", "fit_kwargs", "[", "'weights'", "]", "del", "new_fit_kwargs", "[", "'weights'", "]", "else", ":", "orig_weights", "=", "1", "# Make sure we're just getting the point estimate", "new_fit_kwargs", "[", "'just_point'", "]", "=", "True", "# Populate the second order influence array", "for", "obs", "in", "xrange", "(", "num_obs", ")", ":", "# Note we create the long weights in a for-loop to avoid creating a", "# num_obs by num_obs matrix, which may be a problem for large datasets", "# Get the wide format weights for this observation", "current_wide_weights_plus", "=", "init_wide_weights_plus", ".", "copy", "(", ")", "current_wide_weights_plus", "[", "obs", "]", "+=", "epsilon", "current_wide_weights_minus", "=", "init_wide_weights_minus", ".", "copy", "(", ")", "current_wide_weights_minus", "[", "obs", "]", "-=", "epsilon", "# Get the long format weights for this observation", "long_weights_plus", "=", "(", "create_long_form_weights", "(", "model_obj", ",", "current_wide_weights_plus", ",", "rows_to_obs", "=", "rows_to_obs", ")", "*", "orig_weights", ")", "long_weights_minus", "=", "(", "create_long_form_weights", "(", "model_obj", ",", "current_wide_weights_minus", ",", "rows_to_obs", "=", "rows_to_obs", ")", "*", "orig_weights", ")", "# Get the needed influence estimates.", "term_plus", "[", "obs", "]", "=", "model_obj", ".", "fit_mle", "(", "init_vals", ",", "weights", "=", "long_weights_plus", ",", "*", "*", "new_fit_kwargs", ")", "[", "'x'", "]", "term_minus", "[", "obs", "]", "=", "model_obj", ".", "fit_mle", "(", "init_vals", ",", "weights", "=", "long_weights_minus", ",", "*", "*", "new_fit_kwargs", ")", "[", "'x'", "]", "return", "term_plus", ",", "term_minus" ]
Calculates the terms needed for the finite difference approximations of the empirical influence and second order empirical influence functions. Parameters ---------- model_obj : an instance or sublcass of the MNDC class. Should be the model object that corresponds to the model we are constructing the bootstrap confidence intervals for. mle_params : 1D ndarray. Should contain the desired model's maximum likelihood point estimate. init_vals : 1D ndarray. The initial values used to estimate the desired choice model. epsilon : positive float. Should denote the 'very small' value being used to calculate the desired finite difference approximations to the various influence functions. Should be 'close' to zero. fit_kwargs : additional keyword arguments, optional. Should contain any additional kwargs used to alter the default behavior of `model_obj.fit_mle` and thereby enforce conformity with how the MLE was obtained. Will be passed directly to `model_obj.fit_mle`. Returns ------- term_plus : 2D ndarray. Should have one row for each observation. Should have one column for each parameter in the parameter vector being estimated. Elements should denote the finite difference term that comes from adding a small value to the observation corresponding to that elements respective row. term_minus : 2D ndarray. Should have one row for each observation. Should have one column for each parameter in the parameter vector being estimated. Elements should denote the finite difference term that comes from subtracting a small value to the observation corresponding to that elements respective row. References ---------- Efron, Bradley, and Robert J. Tibshirani. An Introduction to the Bootstrap. CRC press, 1994. Section 22.6, Equations 22.32 and 22.36. Notes ----- The returned, symbolic value for `term_minus` does not explicitly appear in Equations 22.32 or 22.36. However, it is used to compute a midpoint / slope approximation to the finite difference derivative used to define the empirical influence function.
[ "Calculates", "the", "terms", "needed", "for", "the", "finite", "difference", "approximations", "of", "the", "empirical", "influence", "and", "second", "order", "empirical", "influence", "functions", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_abc.py#L123-L222
train
233,713
timothyb0912/pylogit
pylogit/bootstrap_abc.py
calc_abc_interval
def calc_abc_interval(model_obj, mle_params, init_vals, conf_percentage, epsilon=0.001, **fit_kwargs): """ Calculate 'approximate bootstrap confidence' intervals. Parameters ---------- model_obj : an instance or sublcass of the MNDC class. Should be the model object that corresponds to the model we are constructing the bootstrap confidence intervals for. mle_params : 1D ndarray. Should contain the desired model's maximum likelihood point estimate. init_vals : 1D ndarray. The initial values used to estimate the desired choice model. conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level of the returned confidence interval. For instance, to calculate a 95% confidence interval, pass `95`. epsilon : positive float, optional. Should denote the 'very small' value being used to calculate the desired finite difference approximations to the various influence functions. Should be close to zero. Default == sys.float_info.epsilon. fit_kwargs : additional keyword arguments, optional. Should contain any additional kwargs used to alter the default behavior of `model_obj.fit_mle` and thereby enforce conformity with how the MLE was obtained. Will be passed directly to `model_obj.fit_mle`. Returns ------- conf_intervals : 2D ndarray. The shape of the returned array will be `(2, samples.shape[1])`. The first row will correspond to the lower value in the confidence interval. The second row will correspond to the upper value in the confidence interval. There will be one column for each element of the parameter vector being estimated. References ---------- Efron, Bradley, and Robert J. Tibshirani. An Introduction to the Bootstrap. CRC press, 1994. Section 22.6. DiCiccio, Thomas J., and Bradley Efron. "Bootstrap confidence intervals." Statistical science (1996): 189-212. """ # Check validity of arguments check_conf_percentage_validity(conf_percentage) # Calculate the empirical influence component and second order empirical # influence component for each observation empirical_influence, second_order_influence =\ calc_influence_arrays_for_abc(model_obj, mle_params, init_vals, epsilon, **fit_kwargs) # Calculate the acceleration constant for the ABC interval. acceleration = calc_acceleration_abc(empirical_influence) # Use the delta method to calculate the standard error of the MLE parameter # estimate of the model using the original data. std_error = calc_std_error_abc(empirical_influence) # Approximate the bias of the MLE parameter estimates. bias = calc_bias_abc(second_order_influence) # Calculate the quadratic coefficient. Note we are using the 'efron' # version of the desired function because the direct implementation of the # formulas in the textbook don't return the correct results. The 'efron' # versions re-implement the calculations from 'abcnon.R' in Efron's # 'bootstrap' library in R. # quadratic_coef = calc_quadratic_coef_abc(model_obj, # mle_params, # init_vals, # empirical_influence, # std_error, # epsilon, # **fit_kwargs) quadratic_coef = efron_quadratic_coef_abc(model_obj, mle_params, init_vals, empirical_influence, std_error, epsilon, **fit_kwargs) # Calculate the total curvature of the level surface of the weight vector, # where the set of weights in the surface are those where the weighted MLE # equals the original (i.e. the equal-weighted) MLE. total_curvature = calc_total_curvature_abc(bias, std_error, quadratic_coef) # Calculate the bias correction constant. bias_correction = calc_bias_correction_abc(acceleration, total_curvature) # Calculate the lower limit of the conf_percentage confidence intervals # Note we are using the 'efron' version of the desired function because the # direct implementation of the formulas in the textbook don't return the # correct results. The 'efron' versions re-implement the calculations from # 'abcnon.R' in Efron's 'bootstrap' library in R. # lower_endpoint, upper_endpoint =\ # calc_endpoints_for_abc_confidence_interval(conf_percentage, # model_obj, # init_vals, # bias_correction, # acceleration, # std_error, # empirical_influence, # **fit_kwargs) lower_endpoint, upper_endpoint =\ efron_endpoints_for_abc_confidence_interval(conf_percentage, model_obj, init_vals, bias_correction, acceleration, std_error, empirical_influence, **fit_kwargs) # Combine the enpoints into a single ndarray. conf_intervals = combine_conf_endpoints(lower_endpoint, upper_endpoint) return conf_intervals
python
def calc_abc_interval(model_obj, mle_params, init_vals, conf_percentage, epsilon=0.001, **fit_kwargs): """ Calculate 'approximate bootstrap confidence' intervals. Parameters ---------- model_obj : an instance or sublcass of the MNDC class. Should be the model object that corresponds to the model we are constructing the bootstrap confidence intervals for. mle_params : 1D ndarray. Should contain the desired model's maximum likelihood point estimate. init_vals : 1D ndarray. The initial values used to estimate the desired choice model. conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level of the returned confidence interval. For instance, to calculate a 95% confidence interval, pass `95`. epsilon : positive float, optional. Should denote the 'very small' value being used to calculate the desired finite difference approximations to the various influence functions. Should be close to zero. Default == sys.float_info.epsilon. fit_kwargs : additional keyword arguments, optional. Should contain any additional kwargs used to alter the default behavior of `model_obj.fit_mle` and thereby enforce conformity with how the MLE was obtained. Will be passed directly to `model_obj.fit_mle`. Returns ------- conf_intervals : 2D ndarray. The shape of the returned array will be `(2, samples.shape[1])`. The first row will correspond to the lower value in the confidence interval. The second row will correspond to the upper value in the confidence interval. There will be one column for each element of the parameter vector being estimated. References ---------- Efron, Bradley, and Robert J. Tibshirani. An Introduction to the Bootstrap. CRC press, 1994. Section 22.6. DiCiccio, Thomas J., and Bradley Efron. "Bootstrap confidence intervals." Statistical science (1996): 189-212. """ # Check validity of arguments check_conf_percentage_validity(conf_percentage) # Calculate the empirical influence component and second order empirical # influence component for each observation empirical_influence, second_order_influence =\ calc_influence_arrays_for_abc(model_obj, mle_params, init_vals, epsilon, **fit_kwargs) # Calculate the acceleration constant for the ABC interval. acceleration = calc_acceleration_abc(empirical_influence) # Use the delta method to calculate the standard error of the MLE parameter # estimate of the model using the original data. std_error = calc_std_error_abc(empirical_influence) # Approximate the bias of the MLE parameter estimates. bias = calc_bias_abc(second_order_influence) # Calculate the quadratic coefficient. Note we are using the 'efron' # version of the desired function because the direct implementation of the # formulas in the textbook don't return the correct results. The 'efron' # versions re-implement the calculations from 'abcnon.R' in Efron's # 'bootstrap' library in R. # quadratic_coef = calc_quadratic_coef_abc(model_obj, # mle_params, # init_vals, # empirical_influence, # std_error, # epsilon, # **fit_kwargs) quadratic_coef = efron_quadratic_coef_abc(model_obj, mle_params, init_vals, empirical_influence, std_error, epsilon, **fit_kwargs) # Calculate the total curvature of the level surface of the weight vector, # where the set of weights in the surface are those where the weighted MLE # equals the original (i.e. the equal-weighted) MLE. total_curvature = calc_total_curvature_abc(bias, std_error, quadratic_coef) # Calculate the bias correction constant. bias_correction = calc_bias_correction_abc(acceleration, total_curvature) # Calculate the lower limit of the conf_percentage confidence intervals # Note we are using the 'efron' version of the desired function because the # direct implementation of the formulas in the textbook don't return the # correct results. The 'efron' versions re-implement the calculations from # 'abcnon.R' in Efron's 'bootstrap' library in R. # lower_endpoint, upper_endpoint =\ # calc_endpoints_for_abc_confidence_interval(conf_percentage, # model_obj, # init_vals, # bias_correction, # acceleration, # std_error, # empirical_influence, # **fit_kwargs) lower_endpoint, upper_endpoint =\ efron_endpoints_for_abc_confidence_interval(conf_percentage, model_obj, init_vals, bias_correction, acceleration, std_error, empirical_influence, **fit_kwargs) # Combine the enpoints into a single ndarray. conf_intervals = combine_conf_endpoints(lower_endpoint, upper_endpoint) return conf_intervals
[ "def", "calc_abc_interval", "(", "model_obj", ",", "mle_params", ",", "init_vals", ",", "conf_percentage", ",", "epsilon", "=", "0.001", ",", "*", "*", "fit_kwargs", ")", ":", "# Check validity of arguments", "check_conf_percentage_validity", "(", "conf_percentage", ")", "# Calculate the empirical influence component and second order empirical", "# influence component for each observation", "empirical_influence", ",", "second_order_influence", "=", "calc_influence_arrays_for_abc", "(", "model_obj", ",", "mle_params", ",", "init_vals", ",", "epsilon", ",", "*", "*", "fit_kwargs", ")", "# Calculate the acceleration constant for the ABC interval.", "acceleration", "=", "calc_acceleration_abc", "(", "empirical_influence", ")", "# Use the delta method to calculate the standard error of the MLE parameter", "# estimate of the model using the original data.", "std_error", "=", "calc_std_error_abc", "(", "empirical_influence", ")", "# Approximate the bias of the MLE parameter estimates.", "bias", "=", "calc_bias_abc", "(", "second_order_influence", ")", "# Calculate the quadratic coefficient. Note we are using the 'efron'", "# version of the desired function because the direct implementation of the", "# formulas in the textbook don't return the correct results. The 'efron'", "# versions re-implement the calculations from 'abcnon.R' in Efron's", "# 'bootstrap' library in R.", "# quadratic_coef = calc_quadratic_coef_abc(model_obj,", "# mle_params,", "# init_vals,", "# empirical_influence,", "# std_error,", "# epsilon,", "# **fit_kwargs)", "quadratic_coef", "=", "efron_quadratic_coef_abc", "(", "model_obj", ",", "mle_params", ",", "init_vals", ",", "empirical_influence", ",", "std_error", ",", "epsilon", ",", "*", "*", "fit_kwargs", ")", "# Calculate the total curvature of the level surface of the weight vector,", "# where the set of weights in the surface are those where the weighted MLE", "# equals the original (i.e. the equal-weighted) MLE.", "total_curvature", "=", "calc_total_curvature_abc", "(", "bias", ",", "std_error", ",", "quadratic_coef", ")", "# Calculate the bias correction constant.", "bias_correction", "=", "calc_bias_correction_abc", "(", "acceleration", ",", "total_curvature", ")", "# Calculate the lower limit of the conf_percentage confidence intervals", "# Note we are using the 'efron' version of the desired function because the", "# direct implementation of the formulas in the textbook don't return the", "# correct results. The 'efron' versions re-implement the calculations from", "# 'abcnon.R' in Efron's 'bootstrap' library in R.", "# lower_endpoint, upper_endpoint =\\", "# calc_endpoints_for_abc_confidence_interval(conf_percentage,", "# model_obj,", "# init_vals,", "# bias_correction,", "# acceleration,", "# std_error,", "# empirical_influence,", "# **fit_kwargs)", "lower_endpoint", ",", "upper_endpoint", "=", "efron_endpoints_for_abc_confidence_interval", "(", "conf_percentage", ",", "model_obj", ",", "init_vals", ",", "bias_correction", ",", "acceleration", ",", "std_error", ",", "empirical_influence", ",", "*", "*", "fit_kwargs", ")", "# Combine the enpoints into a single ndarray.", "conf_intervals", "=", "combine_conf_endpoints", "(", "lower_endpoint", ",", "upper_endpoint", ")", "return", "conf_intervals" ]
Calculate 'approximate bootstrap confidence' intervals. Parameters ---------- model_obj : an instance or sublcass of the MNDC class. Should be the model object that corresponds to the model we are constructing the bootstrap confidence intervals for. mle_params : 1D ndarray. Should contain the desired model's maximum likelihood point estimate. init_vals : 1D ndarray. The initial values used to estimate the desired choice model. conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level of the returned confidence interval. For instance, to calculate a 95% confidence interval, pass `95`. epsilon : positive float, optional. Should denote the 'very small' value being used to calculate the desired finite difference approximations to the various influence functions. Should be close to zero. Default == sys.float_info.epsilon. fit_kwargs : additional keyword arguments, optional. Should contain any additional kwargs used to alter the default behavior of `model_obj.fit_mle` and thereby enforce conformity with how the MLE was obtained. Will be passed directly to `model_obj.fit_mle`. Returns ------- conf_intervals : 2D ndarray. The shape of the returned array will be `(2, samples.shape[1])`. The first row will correspond to the lower value in the confidence interval. The second row will correspond to the upper value in the confidence interval. There will be one column for each element of the parameter vector being estimated. References ---------- Efron, Bradley, and Robert J. Tibshirani. An Introduction to the Bootstrap. CRC press, 1994. Section 22.6. DiCiccio, Thomas J., and Bradley Efron. "Bootstrap confidence intervals." Statistical science (1996): 189-212.
[ "Calculate", "approximate", "bootstrap", "confidence", "intervals", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_abc.py#L1160-L1278
train
233,714
timothyb0912/pylogit
pylogit/mixed_logit.py
check_length_of_init_values
def check_length_of_init_values(design_3d, init_values): """ 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. Parameters ---------- init_values : 1D ndarray. 1D numpy array of the initial values to start the optimizatin process with. There should be one value for each index coefficient being estimated. design_3d : 2D ndarray. 2D numpy array with one row per observation per available alternative. There should be one column per index coefficient being estimated. All elements should be ints, floats, or longs. Returns ------- None. """ 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
python
def check_length_of_init_values(design_3d, init_values): """ 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. Parameters ---------- init_values : 1D ndarray. 1D numpy array of the initial values to start the optimizatin process with. There should be one value for each index coefficient being estimated. design_3d : 2D ndarray. 2D numpy array with one row per observation per available alternative. There should be one column per index coefficient being estimated. All elements should be ints, floats, or longs. Returns ------- None. """ 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
[ "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. Parameters ---------- init_values : 1D ndarray. 1D numpy array of the initial values to start the optimizatin process with. There should be one value for each index coefficient being estimated. design_3d : 2D ndarray. 2D numpy array with one row per observation per available alternative. There should be one column per index coefficient being estimated. All elements should be ints, floats, or longs. Returns ------- 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", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/mixed_logit.py#L106-L132
train
233,715
timothyb0912/pylogit
pylogit/mixed_logit.py
add_mixl_specific_results_to_estimation_res
def add_mixl_specific_results_to_estimation_res(estimator, results_dict): """ 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. Parameters ---------- estimator : an instance of the MixedEstimator class. Should contain a `choice_vector` attribute that is a 1D ndarray representing the choices made for this model's dataset. Should also contain a `rows_to_mixers` attribute that maps each row of the long format data to a unit of observation that the mixing is being performed over. results_dict : dict. This dictionary should be the dictionary returned from scipy.optimize.minimize. In particular, it should have the following `long_probs` key. Returns ------- results_dict. """ # Get the probability of each sequence of choices, given the draws prob_res = mlc.calc_choice_sequence_probs(results_dict["long_probs"], estimator.choice_vector, estimator.rows_to_mixers, return_type='all') # Add the various items to the results_dict. results_dict["simulated_sequence_probs"] = prob_res[0] results_dict["expanded_sequence_probs"] = prob_res[1] return results_dict
python
def add_mixl_specific_results_to_estimation_res(estimator, results_dict): """ 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. Parameters ---------- estimator : an instance of the MixedEstimator class. Should contain a `choice_vector` attribute that is a 1D ndarray representing the choices made for this model's dataset. Should also contain a `rows_to_mixers` attribute that maps each row of the long format data to a unit of observation that the mixing is being performed over. results_dict : dict. This dictionary should be the dictionary returned from scipy.optimize.minimize. In particular, it should have the following `long_probs` key. Returns ------- results_dict. """ # Get the probability of each sequence of choices, given the draws prob_res = mlc.calc_choice_sequence_probs(results_dict["long_probs"], estimator.choice_vector, estimator.rows_to_mixers, return_type='all') # Add the various items to the results_dict. results_dict["simulated_sequence_probs"] = prob_res[0] results_dict["expanded_sequence_probs"] = prob_res[1] return results_dict
[ "def", "add_mixl_specific_results_to_estimation_res", "(", "estimator", ",", "results_dict", ")", ":", "# Get the probability of each sequence of choices, given the draws", "prob_res", "=", "mlc", ".", "calc_choice_sequence_probs", "(", "results_dict", "[", "\"long_probs\"", "]", ",", "estimator", ".", "choice_vector", ",", "estimator", ".", "rows_to_mixers", ",", "return_type", "=", "'all'", ")", "# Add the various items to the results_dict.", "results_dict", "[", "\"simulated_sequence_probs\"", "]", "=", "prob_res", "[", "0", "]", "results_dict", "[", "\"expanded_sequence_probs\"", "]", "=", "prob_res", "[", "1", "]", "return", "results_dict" ]
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. Parameters ---------- estimator : an instance of the MixedEstimator class. Should contain a `choice_vector` attribute that is a 1D ndarray representing the choices made for this model's dataset. Should also contain a `rows_to_mixers` attribute that maps each row of the long format data to a unit of observation that the mixing is being performed over. results_dict : dict. This dictionary should be the dictionary returned from scipy.optimize.minimize. In particular, it should have the following `long_probs` key. Returns ------- results_dict.
[ "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", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/mixed_logit.py#L135-L168
train
233,716
timothyb0912/pylogit
pylogit/nested_logit.py
identify_degenerate_nests
def identify_degenerate_nests(nest_spec): """ Identify the nests within nest_spec that are degenerate, i.e. those nests with only a single alternative within the nest. Parameters ---------- nest_spec : OrderedDict. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Returns ------- list. Will contain the positions in the list of keys from `nest_spec` that are degenerate. """ degenerate_positions = [] for pos, key in enumerate(nest_spec): if len(nest_spec[key]) == 1: degenerate_positions.append(pos) return degenerate_positions
python
def identify_degenerate_nests(nest_spec): """ Identify the nests within nest_spec that are degenerate, i.e. those nests with only a single alternative within the nest. Parameters ---------- nest_spec : OrderedDict. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Returns ------- list. Will contain the positions in the list of keys from `nest_spec` that are degenerate. """ degenerate_positions = [] for pos, key in enumerate(nest_spec): if len(nest_spec[key]) == 1: degenerate_positions.append(pos) return degenerate_positions
[ "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. Parameters ---------- nest_spec : OrderedDict. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Returns ------- list. Will contain the positions in the list of keys from `nest_spec` that are degenerate.
[ "Identify", "the", "nests", "within", "nest_spec", "that", "are", "degenerate", "i", ".", "e", ".", "those", "nests", "with", "only", "a", "single", "alternative", "within", "the", "nest", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/nested_logit.py#L36-L58
train
233,717
timothyb0912/pylogit
pylogit/nested_logit.py
NestedEstimator.check_length_of_initial_values
def check_length_of_initial_values(self, init_values): """ Ensures that the initial values are of the correct length. """ # Figure out how many shape parameters we should have and how many # index coefficients we should have 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" msg_1 = "It should be of dimension {}" msg_2 = "But instead it has dimension {}" raise ValueError(msg + msg_1.format(assumed_param_dimensions) + msg_2.format(init_values.shape[0])) return None
python
def check_length_of_initial_values(self, init_values): """ Ensures that the initial values are of the correct length. """ # Figure out how many shape parameters we should have and how many # index coefficients we should have 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" msg_1 = "It should be of dimension {}" msg_2 = "But instead it has dimension {}" raise ValueError(msg + msg_1.format(assumed_param_dimensions) + msg_2.format(init_values.shape[0])) return None
[ "def", "check_length_of_initial_values", "(", "self", ",", "init_values", ")", ":", "# Figure out how many shape parameters we should have and how many", "# index coefficients we should have", "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\"", "msg_1", "=", "\"It should be of dimension {}\"", "msg_2", "=", "\"But instead it has dimension {}\"", "raise", "ValueError", "(", "msg", "+", "msg_1", ".", "format", "(", "assumed_param_dimensions", ")", "+", "msg_2", ".", "format", "(", "init_values", ".", "shape", "[", "0", "]", ")", ")", "return", "None" ]
Ensures that the initial values are of the correct length.
[ "Ensures", "that", "the", "initial", "values", "are", "of", "the", "correct", "length", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/nested_logit.py#L177-L195
train
233,718
timothyb0912/pylogit
pylogit/nested_logit.py
NestedEstimator.convenience_split_params
def convenience_split_params(self, params, return_all_types=False): """ Splits parameter vector into nest parameters and index parameters. Parameters ---------- all_params : 1D ndarray. Should contain all of the parameters being estimated (i.e. all the nest coefficients and all of the index coefficients). All elements should be ints, floats, or longs. rows_to_nests : 2D scipy sparse array. There should be one row per observation per available alternative and one column per nest. This matrix maps the rows of the design matrix to the unique nests (on the columns). return_all_types : bool, optional. Determines whether or not a tuple of 4 elements will be returned (with one element for the nest, shape, intercept, and index parameters for this model). If False, a tuple of 2 elements will be returned, as described below. The tuple will contain the nest parameters and the index coefficients. Returns ------- orig_nest_coefs : 1D ndarray. The nest coefficients being used for estimation. Note that these values are the logit of the inverse of the scale parameters for each lower level nest. index_coefs : 1D ndarray. The index coefficients of this nested logit model. Note ---- If `return_all_types == True` then the function will return a tuple of four objects. In order, these objects will either be None or the arrays representing the arrays corresponding to the nest, shape, intercept, and index parameters. """ return split_param_vec(params, self.rows_to_nests, return_all_types=return_all_types)
python
def convenience_split_params(self, params, return_all_types=False): """ Splits parameter vector into nest parameters and index parameters. Parameters ---------- all_params : 1D ndarray. Should contain all of the parameters being estimated (i.e. all the nest coefficients and all of the index coefficients). All elements should be ints, floats, or longs. rows_to_nests : 2D scipy sparse array. There should be one row per observation per available alternative and one column per nest. This matrix maps the rows of the design matrix to the unique nests (on the columns). return_all_types : bool, optional. Determines whether or not a tuple of 4 elements will be returned (with one element for the nest, shape, intercept, and index parameters for this model). If False, a tuple of 2 elements will be returned, as described below. The tuple will contain the nest parameters and the index coefficients. Returns ------- orig_nest_coefs : 1D ndarray. The nest coefficients being used for estimation. Note that these values are the logit of the inverse of the scale parameters for each lower level nest. index_coefs : 1D ndarray. The index coefficients of this nested logit model. Note ---- If `return_all_types == True` then the function will return a tuple of four objects. In order, these objects will either be None or the arrays representing the arrays corresponding to the nest, shape, intercept, and index parameters. """ return split_param_vec(params, self.rows_to_nests, return_all_types=return_all_types)
[ "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. Parameters ---------- all_params : 1D ndarray. Should contain all of the parameters being estimated (i.e. all the nest coefficients and all of the index coefficients). All elements should be ints, floats, or longs. rows_to_nests : 2D scipy sparse array. There should be one row per observation per available alternative and one column per nest. This matrix maps the rows of the design matrix to the unique nests (on the columns). return_all_types : bool, optional. Determines whether or not a tuple of 4 elements will be returned (with one element for the nest, shape, intercept, and index parameters for this model). If False, a tuple of 2 elements will be returned, as described below. The tuple will contain the nest parameters and the index coefficients. Returns ------- orig_nest_coefs : 1D ndarray. The nest coefficients being used for estimation. Note that these values are the logit of the inverse of the scale parameters for each lower level nest. index_coefs : 1D ndarray. The index coefficients of this nested logit model. Note ---- If `return_all_types == True` then the function will return a tuple of four objects. In order, these objects will either be None or the arrays representing the arrays corresponding to the nest, shape, intercept, and index parameters.
[ "Splits", "parameter", "vector", "into", "nest", "parameters", "and", "index", "parameters", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/nested_logit.py#L197-L236
train
233,719
timothyb0912/pylogit
pylogit/choice_calcs.py
robust_outer_product
def robust_outer_product(vec_1, vec_2): """ Calculates a 'robust' outer product of two vectors that may or may not contain very small values. Parameters ---------- vec_1 : 1D ndarray vec_2 : 1D ndarray Returns ------- outer_prod : 2D ndarray. The outer product of vec_1 and 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_exponents)
python
def robust_outer_product(vec_1, vec_2): """ Calculates a 'robust' outer product of two vectors that may or may not contain very small values. Parameters ---------- vec_1 : 1D ndarray vec_2 : 1D ndarray Returns ------- outer_prod : 2D ndarray. The outer product of vec_1 and 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_exponents)
[ "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_exponents", ")" ]
Calculates a 'robust' outer product of two vectors that may or may not contain very small values. Parameters ---------- vec_1 : 1D ndarray vec_2 : 1D ndarray Returns ------- outer_prod : 2D ndarray. The outer product of vec_1 and vec_2
[ "Calculates", "a", "robust", "outer", "product", "of", "two", "vectors", "that", "may", "or", "may", "not", "contain", "very", "small", "values", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_calcs.py#L523-L541
train
233,720
timothyb0912/pylogit
pylogit/bootstrap_calcs.py
calc_percentile_interval
def calc_percentile_interval(bootstrap_replicates, conf_percentage): """ Calculate bootstrap confidence intervals based on raw percentiles of the bootstrap distribution of samples. Parameters ---------- bootstrap_replicates : 2D ndarray. Each row should correspond to a different bootstrap parameter sample. Each column should correspond to an element of the parameter vector being estimated. conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level of the returned confidence interval. For instance, to calculate a 95% confidence interval, pass `95`. Returns ------- conf_intervals : 2D ndarray. The shape of the returned array will be `(2, samples.shape[1])`. The first row will correspond to the lower value in the confidence interval. The second row will correspond to the upper value in the confidence interval. There will be one column for each element of the parameter vector being estimated. References ---------- Efron, Bradley, and Robert J. Tibshirani. An Introduction to the Bootstrap. CRC press, 1994. Section 12.5 and Section 13.3. See Equation 13.3. Notes ----- This function differs slightly from the actual percentile bootstrap procedure described in Efron and Tibshirani (1994). To ensure that the returned endpoints of one's bootstrap confidence intervals are actual values that were observed in the bootstrap distribution, both the procedure of Efron and Tibshirani and this function make more conservative confidence intervals. However, this function uses a simpler (and in some cases less conservative) correction than that of Efron and Tibshirani. """ # Check validity of arguments check_conf_percentage_validity(conf_percentage) ensure_samples_is_ndim_ndarray(bootstrap_replicates, ndim=2) # Get the alpha * 100% value alpha = get_alpha_from_conf_percentage(conf_percentage) # Get the lower and upper percentiles that demarcate the desired interval. lower_percent = alpha / 2.0 upper_percent = 100.0 - lower_percent # Calculate the lower and upper endpoints of the confidence intervals. # Note that the particular choices of interpolation methods are made in # order to produce conservatively wide confidence intervals and ensure that # all returned endpoints in the confidence intervals are actually observed # in the bootstrap distribution. This is in accordance with the spirit of # Efron and Tibshirani (1994). lower_endpoint = np.percentile(bootstrap_replicates, lower_percent, interpolation='lower', axis=0) upper_endpoint = np.percentile(bootstrap_replicates, upper_percent, interpolation='higher', axis=0) # Combine the enpoints into a single ndarray. conf_intervals = combine_conf_endpoints(lower_endpoint, upper_endpoint) return conf_intervals
python
def calc_percentile_interval(bootstrap_replicates, conf_percentage): """ Calculate bootstrap confidence intervals based on raw percentiles of the bootstrap distribution of samples. Parameters ---------- bootstrap_replicates : 2D ndarray. Each row should correspond to a different bootstrap parameter sample. Each column should correspond to an element of the parameter vector being estimated. conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level of the returned confidence interval. For instance, to calculate a 95% confidence interval, pass `95`. Returns ------- conf_intervals : 2D ndarray. The shape of the returned array will be `(2, samples.shape[1])`. The first row will correspond to the lower value in the confidence interval. The second row will correspond to the upper value in the confidence interval. There will be one column for each element of the parameter vector being estimated. References ---------- Efron, Bradley, and Robert J. Tibshirani. An Introduction to the Bootstrap. CRC press, 1994. Section 12.5 and Section 13.3. See Equation 13.3. Notes ----- This function differs slightly from the actual percentile bootstrap procedure described in Efron and Tibshirani (1994). To ensure that the returned endpoints of one's bootstrap confidence intervals are actual values that were observed in the bootstrap distribution, both the procedure of Efron and Tibshirani and this function make more conservative confidence intervals. However, this function uses a simpler (and in some cases less conservative) correction than that of Efron and Tibshirani. """ # Check validity of arguments check_conf_percentage_validity(conf_percentage) ensure_samples_is_ndim_ndarray(bootstrap_replicates, ndim=2) # Get the alpha * 100% value alpha = get_alpha_from_conf_percentage(conf_percentage) # Get the lower and upper percentiles that demarcate the desired interval. lower_percent = alpha / 2.0 upper_percent = 100.0 - lower_percent # Calculate the lower and upper endpoints of the confidence intervals. # Note that the particular choices of interpolation methods are made in # order to produce conservatively wide confidence intervals and ensure that # all returned endpoints in the confidence intervals are actually observed # in the bootstrap distribution. This is in accordance with the spirit of # Efron and Tibshirani (1994). lower_endpoint = np.percentile(bootstrap_replicates, lower_percent, interpolation='lower', axis=0) upper_endpoint = np.percentile(bootstrap_replicates, upper_percent, interpolation='higher', axis=0) # Combine the enpoints into a single ndarray. conf_intervals = combine_conf_endpoints(lower_endpoint, upper_endpoint) return conf_intervals
[ "def", "calc_percentile_interval", "(", "bootstrap_replicates", ",", "conf_percentage", ")", ":", "# Check validity of arguments", "check_conf_percentage_validity", "(", "conf_percentage", ")", "ensure_samples_is_ndim_ndarray", "(", "bootstrap_replicates", ",", "ndim", "=", "2", ")", "# Get the alpha * 100% value", "alpha", "=", "get_alpha_from_conf_percentage", "(", "conf_percentage", ")", "# Get the lower and upper percentiles that demarcate the desired interval.", "lower_percent", "=", "alpha", "/", "2.0", "upper_percent", "=", "100.0", "-", "lower_percent", "# Calculate the lower and upper endpoints of the confidence intervals.", "# Note that the particular choices of interpolation methods are made in", "# order to produce conservatively wide confidence intervals and ensure that", "# all returned endpoints in the confidence intervals are actually observed", "# in the bootstrap distribution. This is in accordance with the spirit of", "# Efron and Tibshirani (1994).", "lower_endpoint", "=", "np", ".", "percentile", "(", "bootstrap_replicates", ",", "lower_percent", ",", "interpolation", "=", "'lower'", ",", "axis", "=", "0", ")", "upper_endpoint", "=", "np", ".", "percentile", "(", "bootstrap_replicates", ",", "upper_percent", ",", "interpolation", "=", "'higher'", ",", "axis", "=", "0", ")", "# Combine the enpoints into a single ndarray.", "conf_intervals", "=", "combine_conf_endpoints", "(", "lower_endpoint", ",", "upper_endpoint", ")", "return", "conf_intervals" ]
Calculate bootstrap confidence intervals based on raw percentiles of the bootstrap distribution of samples. Parameters ---------- bootstrap_replicates : 2D ndarray. Each row should correspond to a different bootstrap parameter sample. Each column should correspond to an element of the parameter vector being estimated. conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level of the returned confidence interval. For instance, to calculate a 95% confidence interval, pass `95`. Returns ------- conf_intervals : 2D ndarray. The shape of the returned array will be `(2, samples.shape[1])`. The first row will correspond to the lower value in the confidence interval. The second row will correspond to the upper value in the confidence interval. There will be one column for each element of the parameter vector being estimated. References ---------- Efron, Bradley, and Robert J. Tibshirani. An Introduction to the Bootstrap. CRC press, 1994. Section 12.5 and Section 13.3. See Equation 13.3. Notes ----- This function differs slightly from the actual percentile bootstrap procedure described in Efron and Tibshirani (1994). To ensure that the returned endpoints of one's bootstrap confidence intervals are actual values that were observed in the bootstrap distribution, both the procedure of Efron and Tibshirani and this function make more conservative confidence intervals. However, this function uses a simpler (and in some cases less conservative) correction than that of Efron and Tibshirani.
[ "Calculate", "bootstrap", "confidence", "intervals", "based", "on", "raw", "percentiles", "of", "the", "bootstrap", "distribution", "of", "samples", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_calcs.py#L20-L83
train
233,721
timothyb0912/pylogit
pylogit/bootstrap_calcs.py
calc_bca_interval
def calc_bca_interval(bootstrap_replicates, jackknife_replicates, mle_params, conf_percentage): """ Calculate 'bias-corrected and accelerated' bootstrap confidence intervals. Parameters ---------- bootstrap_replicates : 2D ndarray. Each row should correspond to a different bootstrap parameter sample. Each column should correspond to an element of the parameter vector being estimated. jackknife_replicates : 2D ndarray. Each row should correspond to a different jackknife parameter sample, formed by deleting a particular observation and then re-estimating the desired model. Each column should correspond to an element of the parameter vector being estimated. mle_params : 1D ndarray. The original dataset's maximum likelihood point estimate. Should have the same number of elements as `samples.shape[1]`. conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level of the returned confidence interval. For instance, to calculate a 95% confidence interval, pass `95`. Returns ------- conf_intervals : 2D ndarray. The shape of the returned array will be `(2, samples.shape[1])`. The first row will correspond to the lower value in the confidence interval. The second row will correspond to the upper value in the confidence interval. There will be one column for each element of the parameter vector being estimated. References ---------- Efron, Bradley, and Robert J. Tibshirani. An Introduction to the Bootstrap. CRC press, 1994. Section 14.3. DiCiccio, Thomas J., and Bradley Efron. "Bootstrap confidence intervals." Statistical science (1996): 189-212. """ # Check validity of arguments 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) # Calculate the alpha * 100% value alpha_percent = get_alpha_from_conf_percentage(conf_percentage) # Estimate the bias correction for the bootstrap samples bias_correction =\ calc_bias_correction_bca(bootstrap_replicates, mle_params) # Estimate the acceleration acceleration = calc_acceleration_bca(jackknife_replicates) # Get the lower and upper percent value for the raw bootstrap samples. lower_percents =\ calc_lower_bca_percentile(alpha_percent, bias_correction, acceleration) upper_percents =\ calc_upper_bca_percentile(alpha_percent, bias_correction, acceleration) # Get the lower and upper endpoints for the desired confidence intervals. lower_endpoints = np.diag(np.percentile(bootstrap_replicates, lower_percents, interpolation='lower', axis=0)) upper_endpoints = np.diag(np.percentile(bootstrap_replicates, upper_percents, interpolation='higher', axis=0)) # Combine the enpoints into a single ndarray. conf_intervals = combine_conf_endpoints(lower_endpoints, upper_endpoints) return conf_intervals
python
def calc_bca_interval(bootstrap_replicates, jackknife_replicates, mle_params, conf_percentage): """ Calculate 'bias-corrected and accelerated' bootstrap confidence intervals. Parameters ---------- bootstrap_replicates : 2D ndarray. Each row should correspond to a different bootstrap parameter sample. Each column should correspond to an element of the parameter vector being estimated. jackknife_replicates : 2D ndarray. Each row should correspond to a different jackknife parameter sample, formed by deleting a particular observation and then re-estimating the desired model. Each column should correspond to an element of the parameter vector being estimated. mle_params : 1D ndarray. The original dataset's maximum likelihood point estimate. Should have the same number of elements as `samples.shape[1]`. conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level of the returned confidence interval. For instance, to calculate a 95% confidence interval, pass `95`. Returns ------- conf_intervals : 2D ndarray. The shape of the returned array will be `(2, samples.shape[1])`. The first row will correspond to the lower value in the confidence interval. The second row will correspond to the upper value in the confidence interval. There will be one column for each element of the parameter vector being estimated. References ---------- Efron, Bradley, and Robert J. Tibshirani. An Introduction to the Bootstrap. CRC press, 1994. Section 14.3. DiCiccio, Thomas J., and Bradley Efron. "Bootstrap confidence intervals." Statistical science (1996): 189-212. """ # Check validity of arguments 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) # Calculate the alpha * 100% value alpha_percent = get_alpha_from_conf_percentage(conf_percentage) # Estimate the bias correction for the bootstrap samples bias_correction =\ calc_bias_correction_bca(bootstrap_replicates, mle_params) # Estimate the acceleration acceleration = calc_acceleration_bca(jackknife_replicates) # Get the lower and upper percent value for the raw bootstrap samples. lower_percents =\ calc_lower_bca_percentile(alpha_percent, bias_correction, acceleration) upper_percents =\ calc_upper_bca_percentile(alpha_percent, bias_correction, acceleration) # Get the lower and upper endpoints for the desired confidence intervals. lower_endpoints = np.diag(np.percentile(bootstrap_replicates, lower_percents, interpolation='lower', axis=0)) upper_endpoints = np.diag(np.percentile(bootstrap_replicates, upper_percents, interpolation='higher', axis=0)) # Combine the enpoints into a single ndarray. conf_intervals = combine_conf_endpoints(lower_endpoints, upper_endpoints) return conf_intervals
[ "def", "calc_bca_interval", "(", "bootstrap_replicates", ",", "jackknife_replicates", ",", "mle_params", ",", "conf_percentage", ")", ":", "# Check validity of arguments", "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", ")", "# Calculate the alpha * 100% value", "alpha_percent", "=", "get_alpha_from_conf_percentage", "(", "conf_percentage", ")", "# Estimate the bias correction for the bootstrap samples", "bias_correction", "=", "calc_bias_correction_bca", "(", "bootstrap_replicates", ",", "mle_params", ")", "# Estimate the acceleration", "acceleration", "=", "calc_acceleration_bca", "(", "jackknife_replicates", ")", "# Get the lower and upper percent value for the raw bootstrap samples.", "lower_percents", "=", "calc_lower_bca_percentile", "(", "alpha_percent", ",", "bias_correction", ",", "acceleration", ")", "upper_percents", "=", "calc_upper_bca_percentile", "(", "alpha_percent", ",", "bias_correction", ",", "acceleration", ")", "# Get the lower and upper endpoints for the desired confidence intervals.", "lower_endpoints", "=", "np", ".", "diag", "(", "np", ".", "percentile", "(", "bootstrap_replicates", ",", "lower_percents", ",", "interpolation", "=", "'lower'", ",", "axis", "=", "0", ")", ")", "upper_endpoints", "=", "np", ".", "diag", "(", "np", ".", "percentile", "(", "bootstrap_replicates", ",", "upper_percents", ",", "interpolation", "=", "'higher'", ",", "axis", "=", "0", ")", ")", "# Combine the enpoints into a single ndarray.", "conf_intervals", "=", "combine_conf_endpoints", "(", "lower_endpoints", ",", "upper_endpoints", ")", "return", "conf_intervals" ]
Calculate 'bias-corrected and accelerated' bootstrap confidence intervals. Parameters ---------- bootstrap_replicates : 2D ndarray. Each row should correspond to a different bootstrap parameter sample. Each column should correspond to an element of the parameter vector being estimated. jackknife_replicates : 2D ndarray. Each row should correspond to a different jackknife parameter sample, formed by deleting a particular observation and then re-estimating the desired model. Each column should correspond to an element of the parameter vector being estimated. mle_params : 1D ndarray. The original dataset's maximum likelihood point estimate. Should have the same number of elements as `samples.shape[1]`. conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level of the returned confidence interval. For instance, to calculate a 95% confidence interval, pass `95`. Returns ------- conf_intervals : 2D ndarray. The shape of the returned array will be `(2, samples.shape[1])`. The first row will correspond to the lower value in the confidence interval. The second row will correspond to the upper value in the confidence interval. There will be one column for each element of the parameter vector being estimated. References ---------- Efron, Bradley, and Robert J. Tibshirani. An Introduction to the Bootstrap. CRC press, 1994. Section 14.3. DiCiccio, Thomas J., and Bradley Efron. "Bootstrap confidence intervals." Statistical science (1996): 189-212.
[ "Calculate", "bias", "-", "corrected", "and", "accelerated", "bootstrap", "confidence", "intervals", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_calcs.py#L254-L323
train
233,722
timothyb0912/pylogit
pylogit/bootstrap_mle.py
extract_default_init_vals
def extract_default_init_vals(orig_model_obj, mnl_point_series, num_params): """ 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. Parameters ---------- orig_model_obj : an instance or sublcass of the MNDC class. Should correspond to the actual model that we want to bootstrap. mnl_point_series : pandas Series. Should denote the point estimate from the MNL model that is 'closest' to the desired model. num_params : int. Should denote the number of parameters being estimated (including any parameters that are being constrained during estimation). Returns ------- init_vals : 1D ndarray of initial values for the MLE of the desired model. """ # Initialize the initial values init_vals = np.zeros(num_params, dtype=float) # Figure out which values in mnl_point_series are the index coefficients 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 =\ mnl_point_series.loc[orig_model_obj.ind_var_names].values init_intercepts =\ mnl_point_series.loc[orig_model_obj.intercept_names].values # Add any mixing variables to the index coefficients. if orig_model_obj.mixing_vars is not None: num_mixing_vars = len(orig_model_obj.mixing_vars) init_index_coefs = np.concatenate([init_index_coefs, np.zeros(num_mixing_vars)], axis=0) # Account for the special transformation of the index coefficients that is # needed for the asymmetric logit model. if orig_model_obj.model_type == model_type_to_display_name["Asym"]: multiplier = np.log(len(np.unique(orig_model_obj.alt_IDs))) # Cast the initial index coefficients to a float dtype to ensure # successful broadcasting init_index_coefs = init_index_coefs.astype(float) # Adjust the scale of the index coefficients for the asymmetric logit. init_index_coefs /= multiplier # Combine the initial interept values with the initial index coefficients if init_intercepts is not None: init_index_coefs =\ np.concatenate([init_intercepts, init_index_coefs], axis=0) # Add index coefficients (and mixing variables) to the total initial array num_index = init_index_coefs.shape[0] init_vals[-1 * num_index:] = init_index_coefs # Note that the initial values for the transformed nest coefficients and # the shape parameters is zero so we don't have to change anything return init_vals
python
def extract_default_init_vals(orig_model_obj, mnl_point_series, num_params): """ 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. Parameters ---------- orig_model_obj : an instance or sublcass of the MNDC class. Should correspond to the actual model that we want to bootstrap. mnl_point_series : pandas Series. Should denote the point estimate from the MNL model that is 'closest' to the desired model. num_params : int. Should denote the number of parameters being estimated (including any parameters that are being constrained during estimation). Returns ------- init_vals : 1D ndarray of initial values for the MLE of the desired model. """ # Initialize the initial values init_vals = np.zeros(num_params, dtype=float) # Figure out which values in mnl_point_series are the index coefficients 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 =\ mnl_point_series.loc[orig_model_obj.ind_var_names].values init_intercepts =\ mnl_point_series.loc[orig_model_obj.intercept_names].values # Add any mixing variables to the index coefficients. if orig_model_obj.mixing_vars is not None: num_mixing_vars = len(orig_model_obj.mixing_vars) init_index_coefs = np.concatenate([init_index_coefs, np.zeros(num_mixing_vars)], axis=0) # Account for the special transformation of the index coefficients that is # needed for the asymmetric logit model. if orig_model_obj.model_type == model_type_to_display_name["Asym"]: multiplier = np.log(len(np.unique(orig_model_obj.alt_IDs))) # Cast the initial index coefficients to a float dtype to ensure # successful broadcasting init_index_coefs = init_index_coefs.astype(float) # Adjust the scale of the index coefficients for the asymmetric logit. init_index_coefs /= multiplier # Combine the initial interept values with the initial index coefficients if init_intercepts is not None: init_index_coefs =\ np.concatenate([init_intercepts, init_index_coefs], axis=0) # Add index coefficients (and mixing variables) to the total initial array num_index = init_index_coefs.shape[0] init_vals[-1 * num_index:] = init_index_coefs # Note that the initial values for the transformed nest coefficients and # the shape parameters is zero so we don't have to change anything return init_vals
[ "def", "extract_default_init_vals", "(", "orig_model_obj", ",", "mnl_point_series", ",", "num_params", ")", ":", "# Initialize the initial values", "init_vals", "=", "np", ".", "zeros", "(", "num_params", ",", "dtype", "=", "float", ")", "# Figure out which values in mnl_point_series are the index coefficients", "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", "=", "mnl_point_series", ".", "loc", "[", "orig_model_obj", ".", "ind_var_names", "]", ".", "values", "init_intercepts", "=", "mnl_point_series", ".", "loc", "[", "orig_model_obj", ".", "intercept_names", "]", ".", "values", "# Add any mixing variables to the index coefficients.", "if", "orig_model_obj", ".", "mixing_vars", "is", "not", "None", ":", "num_mixing_vars", "=", "len", "(", "orig_model_obj", ".", "mixing_vars", ")", "init_index_coefs", "=", "np", ".", "concatenate", "(", "[", "init_index_coefs", ",", "np", ".", "zeros", "(", "num_mixing_vars", ")", "]", ",", "axis", "=", "0", ")", "# Account for the special transformation of the index coefficients that is", "# needed for the asymmetric logit model.", "if", "orig_model_obj", ".", "model_type", "==", "model_type_to_display_name", "[", "\"Asym\"", "]", ":", "multiplier", "=", "np", ".", "log", "(", "len", "(", "np", ".", "unique", "(", "orig_model_obj", ".", "alt_IDs", ")", ")", ")", "# Cast the initial index coefficients to a float dtype to ensure", "# successful broadcasting", "init_index_coefs", "=", "init_index_coefs", ".", "astype", "(", "float", ")", "# Adjust the scale of the index coefficients for the asymmetric logit.", "init_index_coefs", "/=", "multiplier", "# Combine the initial interept values with the initial index coefficients", "if", "init_intercepts", "is", "not", "None", ":", "init_index_coefs", "=", "np", ".", "concatenate", "(", "[", "init_intercepts", ",", "init_index_coefs", "]", ",", "axis", "=", "0", ")", "# Add index coefficients (and mixing variables) to the total initial array", "num_index", "=", "init_index_coefs", ".", "shape", "[", "0", "]", "init_vals", "[", "-", "1", "*", "num_index", ":", "]", "=", "init_index_coefs", "# Note that the initial values for the transformed nest coefficients and", "# the shape parameters is zero so we don't have to change anything", "return", "init_vals" ]
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. Parameters ---------- orig_model_obj : an instance or sublcass of the MNDC class. Should correspond to the actual model that we want to bootstrap. mnl_point_series : pandas Series. Should denote the point estimate from the MNL model that is 'closest' to the desired model. num_params : int. Should denote the number of parameters being estimated (including any parameters that are being constrained during estimation). Returns ------- init_vals : 1D ndarray of initial values for the MLE of the desired model.
[ "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", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_mle.py#L14-L75
train
233,723
timothyb0912/pylogit
pylogit/bootstrap_mle.py
get_model_abbrev
def get_model_abbrev(model_obj): """ Extract the string used to specify the model type of this model object in `pylogit.create_chohice_model`. Parameters ---------- model_obj : An MNDC_Model instance. Returns ------- str. The internal abbreviation used for the particular type of MNDC_Model. """ # Get the 'display name' for our model. model_type = model_obj.model_type # Find the model abbreviation for this model's display name. for key in model_type_to_display_name: if model_type_to_display_name[key] == model_type: return key # If none of the strings in model_type_to_display_name matches our model # object, then raise an error. msg = "Model object has an unknown or incorrect model type." raise ValueError(msg)
python
def get_model_abbrev(model_obj): """ Extract the string used to specify the model type of this model object in `pylogit.create_chohice_model`. Parameters ---------- model_obj : An MNDC_Model instance. Returns ------- str. The internal abbreviation used for the particular type of MNDC_Model. """ # Get the 'display name' for our model. model_type = model_obj.model_type # Find the model abbreviation for this model's display name. for key in model_type_to_display_name: if model_type_to_display_name[key] == model_type: return key # If none of the strings in model_type_to_display_name matches our model # object, then raise an error. msg = "Model object has an unknown or incorrect model type." raise ValueError(msg)
[ "def", "get_model_abbrev", "(", "model_obj", ")", ":", "# Get the 'display name' for our model.", "model_type", "=", "model_obj", ".", "model_type", "# Find the model abbreviation for this model's display name.", "for", "key", "in", "model_type_to_display_name", ":", "if", "model_type_to_display_name", "[", "key", "]", "==", "model_type", ":", "return", "key", "# If none of the strings in model_type_to_display_name matches our model", "# object, then raise an error.", "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`. Parameters ---------- model_obj : An MNDC_Model instance. Returns ------- str. The internal abbreviation used for the particular type of MNDC_Model.
[ "Extract", "the", "string", "used", "to", "specify", "the", "model", "type", "of", "this", "model", "object", "in", "pylogit", ".", "create_chohice_model", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_mle.py#L78-L100
train
233,724
timothyb0912/pylogit
pylogit/bootstrap_mle.py
get_model_creation_kwargs
def get_model_creation_kwargs(model_obj): """ Get a dictionary of the keyword arguments needed to create the passed model object using `pylogit.create_choice_model`. Parameters ---------- model_obj : An MNDC_Model instance. Returns ------- model_kwargs : dict. Contains the keyword arguments and the required values that are needed to initialize a replica of `model_obj`. """ # Extract the model abbreviation for this model model_abbrev = get_model_abbrev(model_obj) # Create a dictionary to store the keyword arguments needed to Initialize # the new model object.d 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_names, "shape_ref_pos": model_obj.shape_ref_position, "nest_spec": model_obj.nest_spec, "mixing_vars": model_obj.mixing_vars, "mixing_id_col": model_obj.mixing_id_col} return model_kwargs
python
def get_model_creation_kwargs(model_obj): """ Get a dictionary of the keyword arguments needed to create the passed model object using `pylogit.create_choice_model`. Parameters ---------- model_obj : An MNDC_Model instance. Returns ------- model_kwargs : dict. Contains the keyword arguments and the required values that are needed to initialize a replica of `model_obj`. """ # Extract the model abbreviation for this model model_abbrev = get_model_abbrev(model_obj) # Create a dictionary to store the keyword arguments needed to Initialize # the new model object.d 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_names, "shape_ref_pos": model_obj.shape_ref_position, "nest_spec": model_obj.nest_spec, "mixing_vars": model_obj.mixing_vars, "mixing_id_col": model_obj.mixing_id_col} return model_kwargs
[ "def", "get_model_creation_kwargs", "(", "model_obj", ")", ":", "# Extract the model abbreviation for this model", "model_abbrev", "=", "get_model_abbrev", "(", "model_obj", ")", "# Create a dictionary to store the keyword arguments needed to Initialize", "# the new model object.d", "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_names", ",", "\"shape_ref_pos\"", ":", "model_obj", ".", "shape_ref_position", ",", "\"nest_spec\"", ":", "model_obj", ".", "nest_spec", ",", "\"mixing_vars\"", ":", "model_obj", ".", "mixing_vars", ",", "\"mixing_id_col\"", ":", "model_obj", ".", "mixing_id_col", "}", "return", "model_kwargs" ]
Get a dictionary of the keyword arguments needed to create the passed model object using `pylogit.create_choice_model`. Parameters ---------- model_obj : An MNDC_Model instance. Returns ------- model_kwargs : dict. Contains the keyword arguments and the required values that are needed to initialize a replica of `model_obj`.
[ "Get", "a", "dictionary", "of", "the", "keyword", "arguments", "needed", "to", "create", "the", "passed", "model", "object", "using", "pylogit", ".", "create_choice_model", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_mle.py#L103-L133
train
233,725
timothyb0912/pylogit
pylogit/pylogit.py
ensure_valid_model_type
def ensure_valid_model_type(specified_type, model_type_list): """ Checks to make sure that `specified_type` is in `model_type_list` and raises a helpful error if this is not the case. Parameters ---------- specified_type : str. Denotes the user-specified model type that is to be checked. model_type_list : list of strings. Contains all of the model types that are acceptable kwarg values. Returns ------- None. """ 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([msg_1, msg_2, msg_3]) raise ValueError(total_msg) return None
python
def ensure_valid_model_type(specified_type, model_type_list): """ Checks to make sure that `specified_type` is in `model_type_list` and raises a helpful error if this is not the case. Parameters ---------- specified_type : str. Denotes the user-specified model type that is to be checked. model_type_list : list of strings. Contains all of the model types that are acceptable kwarg values. Returns ------- None. """ 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([msg_1, msg_2, msg_3]) raise ValueError(total_msg) return None
[ "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", "(", "[", "msg_1", ",", "msg_2", ",", "msg_3", "]", ")", "raise", "ValueError", "(", "total_msg", ")", "return", "None" ]
Checks to make sure that `specified_type` is in `model_type_list` and raises a helpful error if this is not the case. Parameters ---------- specified_type : str. Denotes the user-specified model type that is to be checked. model_type_list : list of strings. Contains all of the model types that are acceptable kwarg values. Returns ------- None.
[ "Checks", "to", "make", "sure", "that", "specified_type", "is", "in", "model_type_list", "and", "raises", "a", "helpful", "error", "if", "this", "is", "not", "the", "case", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/pylogit.py#L58-L80
train
233,726
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
ensure_valid_nums_in_specification_cols
def ensure_valid_nums_in_specification_cols(specification, dataframe): """ 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. Parameters ---------- specification : iterable of column headers in `dataframe`. dataframe : pandas DataFrame. Dataframe containing the data for the choice model to be estimated. Returns ------- None. """ problem_cols = [] for col in specification: # The condition below checks for values that are not floats or integers # This will catch values that are strings. if dataframe[col].dtype.kind not in ['f', 'i', 'u']: problem_cols.append(col) # The condition below checks for positive or negative inifinity values. elif np.isinf(dataframe[col]).any(): problem_cols.append(col) # This condition will check for NaN values. elif np.isnan(dataframe[col]).any(): problem_cols.append(col) if problem_cols != []: msg = "The following columns contain either +/- inifinity values, " msg_2 = "NaN values, or values that are not real numbers " msg_3 = "(e.g. strings):\n{}" total_msg = msg + msg_2 + msg_3 raise ValueError(total_msg.format(problem_cols)) return None
python
def ensure_valid_nums_in_specification_cols(specification, dataframe): """ 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. Parameters ---------- specification : iterable of column headers in `dataframe`. dataframe : pandas DataFrame. Dataframe containing the data for the choice model to be estimated. Returns ------- None. """ problem_cols = [] for col in specification: # The condition below checks for values that are not floats or integers # This will catch values that are strings. if dataframe[col].dtype.kind not in ['f', 'i', 'u']: problem_cols.append(col) # The condition below checks for positive or negative inifinity values. elif np.isinf(dataframe[col]).any(): problem_cols.append(col) # This condition will check for NaN values. elif np.isnan(dataframe[col]).any(): problem_cols.append(col) if problem_cols != []: msg = "The following columns contain either +/- inifinity values, " msg_2 = "NaN values, or values that are not real numbers " msg_3 = "(e.g. strings):\n{}" total_msg = msg + msg_2 + msg_3 raise ValueError(total_msg.format(problem_cols)) return None
[ "def", "ensure_valid_nums_in_specification_cols", "(", "specification", ",", "dataframe", ")", ":", "problem_cols", "=", "[", "]", "for", "col", "in", "specification", ":", "# The condition below checks for values that are not floats or integers", "# This will catch values that are strings.", "if", "dataframe", "[", "col", "]", ".", "dtype", ".", "kind", "not", "in", "[", "'f'", ",", "'i'", ",", "'u'", "]", ":", "problem_cols", ".", "append", "(", "col", ")", "# The condition below checks for positive or negative inifinity values.", "elif", "np", ".", "isinf", "(", "dataframe", "[", "col", "]", ")", ".", "any", "(", ")", ":", "problem_cols", ".", "append", "(", "col", ")", "# This condition will check for NaN values.", "elif", "np", ".", "isnan", "(", "dataframe", "[", "col", "]", ")", ".", "any", "(", ")", ":", "problem_cols", ".", "append", "(", "col", ")", "if", "problem_cols", "!=", "[", "]", ":", "msg", "=", "\"The following columns contain either +/- inifinity values, \"", "msg_2", "=", "\"NaN values, or values that are not real numbers \"", "msg_3", "=", "\"(e.g. strings):\\n{}\"", "total_msg", "=", "msg", "+", "msg_2", "+", "msg_3", "raise", "ValueError", "(", "total_msg", ".", "format", "(", "problem_cols", ")", ")", "return", "None" ]
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. Parameters ---------- specification : iterable of column headers in `dataframe`. dataframe : pandas DataFrame. Dataframe containing the data for the choice model to be estimated. Returns ------- None.
[ "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", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L60-L96
train
233,727
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
check_length_of_shape_or_intercept_names
def check_length_of_shape_or_intercept_names(name_list, num_alts, constrained_param, list_title): """ Ensures that the length of the parameter names matches the number of parameters that will be estimated. Will raise a ValueError otherwise. Parameters ---------- name_list : list of strings. Each element should be the name of a parameter that is to be estimated. num_alts : int. Should be the total number of alternatives in the universal choice set for this dataset. constrainted_param : {0, 1, True, False} Indicates whether (1 or True) or not (0 or False) one of the type of parameters being estimated will be constrained. For instance, constraining one of the intercepts. list_title : str. Should specify the type of parameters whose names are being checked. Examples include 'intercept_params' or 'shape_params'. Returns ------- None. """ 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 - constrained_param msg_3 = "The correct length is: {}".format(correct_length) total_msg = "\n".join([msg_1, msg_2, msg_3]) raise ValueError(total_msg) return None
python
def check_length_of_shape_or_intercept_names(name_list, num_alts, constrained_param, list_title): """ Ensures that the length of the parameter names matches the number of parameters that will be estimated. Will raise a ValueError otherwise. Parameters ---------- name_list : list of strings. Each element should be the name of a parameter that is to be estimated. num_alts : int. Should be the total number of alternatives in the universal choice set for this dataset. constrainted_param : {0, 1, True, False} Indicates whether (1 or True) or not (0 or False) one of the type of parameters being estimated will be constrained. For instance, constraining one of the intercepts. list_title : str. Should specify the type of parameters whose names are being checked. Examples include 'intercept_params' or 'shape_params'. Returns ------- None. """ 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 - constrained_param msg_3 = "The correct length is: {}".format(correct_length) total_msg = "\n".join([msg_1, msg_2, msg_3]) raise ValueError(total_msg) return None
[ "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", "-", "constrained_param", "msg_3", "=", "\"The correct length is: {}\"", ".", "format", "(", "correct_length", ")", "total_msg", "=", "\"\\n\"", ".", "join", "(", "[", "msg_1", ",", "msg_2", ",", "msg_3", "]", ")", "raise", "ValueError", "(", "total_msg", ")", "return", "None" ]
Ensures that the length of the parameter names matches the number of parameters that will be estimated. Will raise a ValueError otherwise. Parameters ---------- name_list : list of strings. Each element should be the name of a parameter that is to be estimated. num_alts : int. Should be the total number of alternatives in the universal choice set for this dataset. constrainted_param : {0, 1, True, False} Indicates whether (1 or True) or not (0 or False) one of the type of parameters being estimated will be constrained. For instance, constraining one of the intercepts. list_title : str. Should specify the type of parameters whose names are being checked. Examples include 'intercept_params' or 'shape_params'. Returns ------- None.
[ "Ensures", "that", "the", "length", "of", "the", "parameter", "names", "matches", "the", "number", "of", "parameters", "that", "will", "be", "estimated", ".", "Will", "raise", "a", "ValueError", "otherwise", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L145-L180
train
233,728
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
check_type_of_nest_spec_keys_and_values
def check_type_of_nest_spec_keys_and_values(nest_spec): """ Ensures that the keys and values of `nest_spec` are strings and lists. Raises a helpful ValueError if they are. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Default == None. Returns ------- None. """ 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
python
def check_type_of_nest_spec_keys_and_values(nest_spec): """ Ensures that the keys and values of `nest_spec` are strings and lists. Raises a helpful ValueError if they are. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Default == None. Returns ------- None. """ 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
[ "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. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Default == None. Returns ------- None.
[ "Ensures", "that", "the", "keys", "and", "values", "of", "nest_spec", "are", "strings", "and", "lists", ".", "Raises", "a", "helpful", "ValueError", "if", "they", "are", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L183-L207
train
233,729
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
check_for_empty_nests_in_nest_spec
def check_for_empty_nests_in_nest_spec(nest_spec): """ Ensures that the values of `nest_spec` are not empty lists. Raises a helpful ValueError if they are. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Default == None. Returns ------- None. """ 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
python
def check_for_empty_nests_in_nest_spec(nest_spec): """ Ensures that the values of `nest_spec` are not empty lists. Raises a helpful ValueError if they are. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Default == None. Returns ------- None. """ 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
[ "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. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Default == None. Returns ------- None.
[ "Ensures", "that", "the", "values", "of", "nest_spec", "are", "not", "empty", "lists", ".", "Raises", "a", "helpful", "ValueError", "if", "they", "are", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L210-L235
train
233,730
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
ensure_alt_ids_in_nest_spec_are_ints
def ensure_alt_ids_in_nest_spec_are_ints(nest_spec, list_elements): """ Ensures that the alternative id's in `nest_spec` are integers. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Default == None. list_elements : list of lists of ints. Each element should correspond to one of the alternatives identified as belonging to a nest. Returns ------- None. """ 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
python
def ensure_alt_ids_in_nest_spec_are_ints(nest_spec, list_elements): """ Ensures that the alternative id's in `nest_spec` are integers. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Default == None. list_elements : list of lists of ints. Each element should correspond to one of the alternatives identified as belonging to a nest. Returns ------- None. """ 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
[ "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. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Default == None. list_elements : list of lists of ints. Each element should correspond to one of the alternatives identified as belonging to a nest. Returns ------- None.
[ "Ensures", "that", "the", "alternative", "id", "s", "in", "nest_spec", "are", "integers", ".", "Raises", "a", "helpful", "ValueError", "if", "they", "are", "not", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L238-L264
train
233,731
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
ensure_alt_ids_are_only_in_one_nest
def ensure_alt_ids_are_only_in_one_nest(nest_spec, list_elements): """ Ensures that the alternative id's in `nest_spec` are only associated with a single nest. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Default == None. list_elements : list of ints. Each element should correspond to one of the alternatives identified as belonging to a nest. Returns ------- None. """ 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
python
def ensure_alt_ids_are_only_in_one_nest(nest_spec, list_elements): """ Ensures that the alternative id's in `nest_spec` are only associated with a single nest. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Default == None. list_elements : list of ints. Each element should correspond to one of the alternatives identified as belonging to a nest. Returns ------- None. """ 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
[ "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. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Default == None. list_elements : list of ints. Each element should correspond to one of the alternatives identified as belonging to a nest. Returns ------- 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", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L267-L293
train
233,732
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
ensure_all_alt_ids_have_a_nest
def ensure_all_alt_ids_have_a_nest(nest_spec, list_elements, all_ids): """ Ensures that the alternative id's in `nest_spec` are all associated with a nest. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Default == None. list_elements : list of ints. Each element should correspond to one of the alternatives identified as belonging to a nest. all_ids : list of ints. Each element should correspond to one of the alternatives that is present in the universal choice set for this model. Returns ------- None. """ 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.format(unaccounted_alt_ids)) return None
python
def ensure_all_alt_ids_have_a_nest(nest_spec, list_elements, all_ids): """ Ensures that the alternative id's in `nest_spec` are all associated with a nest. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Default == None. list_elements : list of ints. Each element should correspond to one of the alternatives identified as belonging to a nest. all_ids : list of ints. Each element should correspond to one of the alternatives that is present in the universal choice set for this model. Returns ------- None. """ 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.format(unaccounted_alt_ids)) return None
[ "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", ".", "format", "(", "unaccounted_alt_ids", ")", ")", "return", "None" ]
Ensures that the alternative id's in `nest_spec` are all associated with a nest. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Default == None. list_elements : list of ints. Each element should correspond to one of the alternatives identified as belonging to a nest. all_ids : list of ints. Each element should correspond to one of the alternatives that is present in the universal choice set for this model. Returns ------- None.
[ "Ensures", "that", "the", "alternative", "id", "s", "in", "nest_spec", "are", "all", "associated", "with", "a", "nest", ".", "Raises", "a", "helpful", "ValueError", "if", "they", "are", "not", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L296-L327
train
233,733
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
ensure_nest_alts_are_valid_alts
def ensure_nest_alts_are_valid_alts(nest_spec, list_elements, all_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. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Default == None. list_elements : list of ints. Each element should correspond to one of the alternatives identified as belonging to a nest. all_ids : list of ints. Each element should correspond to one of the alternatives that is present in the universal choice set for this model. Returns ------- None. """ 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)) return None
python
def ensure_nest_alts_are_valid_alts(nest_spec, list_elements, all_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. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Default == None. list_elements : list of ints. Each element should correspond to one of the alternatives identified as belonging to a nest. all_ids : list of ints. Each element should correspond to one of the alternatives that is present in the universal choice set for this model. Returns ------- None. """ 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)) return None
[ "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", ")", ")", "return", "None" ]
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. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Default == None. list_elements : list of ints. Each element should correspond to one of the alternatives identified as belonging to a nest. all_ids : list of ints. Each element should correspond to one of the alternatives that is present in the universal choice set for this model. Returns ------- None.
[ "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", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L330-L361
train
233,734
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
check_type_and_size_of_param_list
def check_type_and_size_of_param_list(param_list, expected_length): """ Ensure that param_list is a list with the expected length. Raises a helpful ValueError if this is not the case. """ 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
python
def check_type_and_size_of_param_list(param_list, expected_length): """ Ensure that param_list is a list with the expected length. Raises a helpful ValueError if this is not the case. """ 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
[ "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.
[ "Ensure", "that", "param_list", "is", "a", "list", "with", "the", "expected", "length", ".", "Raises", "a", "helpful", "ValueError", "if", "this", "is", "not", "the", "case", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L410-L422
train
233,735
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
check_type_of_param_list_elements
def check_type_of_param_list_elements(param_list): """ Ensures that all elements of param_list are ndarrays or None. Raises a helpful ValueError if otherwise. """ 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 or None." total_msg = msg + "\n" + msg_2 raise TypeError(total_msg) return None
python
def check_type_of_param_list_elements(param_list): """ Ensures that all elements of param_list are ndarrays or None. Raises a helpful ValueError if otherwise. """ 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 or None." total_msg = msg + "\n" + msg_2 raise TypeError(total_msg) return None
[ "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 or None.\"", "total_msg", "=", "msg", "+", "\"\\n\"", "+", "msg_2", "raise", "TypeError", "(", "total_msg", ")", "return", "None" ]
Ensures that all elements of param_list are ndarrays or None. Raises a helpful ValueError if otherwise.
[ "Ensures", "that", "all", "elements", "of", "param_list", "are", "ndarrays", "or", "None", ".", "Raises", "a", "helpful", "ValueError", "if", "otherwise", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L425-L440
train
233,736
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
check_num_columns_in_param_list_arrays
def check_num_columns_in_param_list_arrays(param_list): """ Ensure that each array in param_list, that is not None, has the same number of columns. Raises a helpful ValueError if otherwise. Parameters ---------- param_list : list of ndarrays or None. Returns ------- None. """ 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 None
python
def check_num_columns_in_param_list_arrays(param_list): """ Ensure that each array in param_list, that is not None, has the same number of columns. Raises a helpful ValueError if otherwise. Parameters ---------- param_list : list of ndarrays or None. Returns ------- None. """ 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 None
[ "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", "None" ]
Ensure that each array in param_list, that is not None, has the same number of columns. Raises a helpful ValueError if otherwise. Parameters ---------- param_list : list of ndarrays or None. Returns ------- None.
[ "Ensure", "that", "each", "array", "in", "param_list", "that", "is", "not", "None", "has", "the", "same", "number", "of", "columns", ".", "Raises", "a", "helpful", "ValueError", "if", "otherwise", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L443-L464
train
233,737
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
ensure_all_mixing_vars_are_in_the_name_dict
def ensure_all_mixing_vars_are_in_the_name_dict(mixing_vars, name_dict, ind_var_names): """ Ensures that all of the variables listed in `mixing_vars` are present in `ind_var_names`. Raises a helpful ValueError if otherwise. Parameters ---------- mixing_vars : list of strings, or None. Each string denotes a parameter to be treated as a random variable. name_dict : OrderedDict or None. Contains the specification relating column headers in one's data (i.e. the keys of the OrderedDict) to the index coefficients to be estimated based on this data (i.e. the values of each key). ind_var_names : list of strings. Each string denotes an index coefficient (i.e. a beta) to be estimated. Returns ------- None. """ if mixing_vars is None: return None # Determine the strings in mixing_vars that are missing from ind_var_names problem_names = [variable_name for variable_name in mixing_vars if variable_name not in ind_var_names] # Create error messages for the case where we have a name dictionary and # the case where we do not have a name dictionary. msg_0 = "The following parameter names were not in the values of the " msg_1 = "passed name dictionary: \n{}" msg_with_name_dict = msg_0 + msg_1.format(problem_names) msg_2 = "The following paramter names did not match any of the default " msg_3 = "names generated for the parameters to be estimated: \n{}" msg_4 = "The default names that were generated were: \n{}" msg_without_name_dict = (msg_2 + msg_3.format(problem_names) + msg_4.format(ind_var_names)) # Raise a helpful ValueError if any mixing_vars were missing from # ind_var_names if problem_names != []: if name_dict: raise ValueError(msg_with_name_dict) else: raise ValueError(msg_without_name_dict) return None
python
def ensure_all_mixing_vars_are_in_the_name_dict(mixing_vars, name_dict, ind_var_names): """ Ensures that all of the variables listed in `mixing_vars` are present in `ind_var_names`. Raises a helpful ValueError if otherwise. Parameters ---------- mixing_vars : list of strings, or None. Each string denotes a parameter to be treated as a random variable. name_dict : OrderedDict or None. Contains the specification relating column headers in one's data (i.e. the keys of the OrderedDict) to the index coefficients to be estimated based on this data (i.e. the values of each key). ind_var_names : list of strings. Each string denotes an index coefficient (i.e. a beta) to be estimated. Returns ------- None. """ if mixing_vars is None: return None # Determine the strings in mixing_vars that are missing from ind_var_names problem_names = [variable_name for variable_name in mixing_vars if variable_name not in ind_var_names] # Create error messages for the case where we have a name dictionary and # the case where we do not have a name dictionary. msg_0 = "The following parameter names were not in the values of the " msg_1 = "passed name dictionary: \n{}" msg_with_name_dict = msg_0 + msg_1.format(problem_names) msg_2 = "The following paramter names did not match any of the default " msg_3 = "names generated for the parameters to be estimated: \n{}" msg_4 = "The default names that were generated were: \n{}" msg_without_name_dict = (msg_2 + msg_3.format(problem_names) + msg_4.format(ind_var_names)) # Raise a helpful ValueError if any mixing_vars were missing from # ind_var_names if problem_names != []: if name_dict: raise ValueError(msg_with_name_dict) else: raise ValueError(msg_without_name_dict) return None
[ "def", "ensure_all_mixing_vars_are_in_the_name_dict", "(", "mixing_vars", ",", "name_dict", ",", "ind_var_names", ")", ":", "if", "mixing_vars", "is", "None", ":", "return", "None", "# Determine the strings in mixing_vars that are missing from ind_var_names", "problem_names", "=", "[", "variable_name", "for", "variable_name", "in", "mixing_vars", "if", "variable_name", "not", "in", "ind_var_names", "]", "# Create error messages for the case where we have a name dictionary and", "# the case where we do not have a name dictionary.", "msg_0", "=", "\"The following parameter names were not in the values of the \"", "msg_1", "=", "\"passed name dictionary: \\n{}\"", "msg_with_name_dict", "=", "msg_0", "+", "msg_1", ".", "format", "(", "problem_names", ")", "msg_2", "=", "\"The following paramter names did not match any of the default \"", "msg_3", "=", "\"names generated for the parameters to be estimated: \\n{}\"", "msg_4", "=", "\"The default names that were generated were: \\n{}\"", "msg_without_name_dict", "=", "(", "msg_2", "+", "msg_3", ".", "format", "(", "problem_names", ")", "+", "msg_4", ".", "format", "(", "ind_var_names", ")", ")", "# Raise a helpful ValueError if any mixing_vars were missing from", "# ind_var_names", "if", "problem_names", "!=", "[", "]", ":", "if", "name_dict", ":", "raise", "ValueError", "(", "msg_with_name_dict", ")", "else", ":", "raise", "ValueError", "(", "msg_without_name_dict", ")", "return", "None" ]
Ensures that all of the variables listed in `mixing_vars` are present in `ind_var_names`. Raises a helpful ValueError if otherwise. Parameters ---------- mixing_vars : list of strings, or None. Each string denotes a parameter to be treated as a random variable. name_dict : OrderedDict or None. Contains the specification relating column headers in one's data (i.e. the keys of the OrderedDict) to the index coefficients to be estimated based on this data (i.e. the values of each key). ind_var_names : list of strings. Each string denotes an index coefficient (i.e. a beta) to be estimated. Returns ------- None.
[ "Ensures", "that", "all", "of", "the", "variables", "listed", "in", "mixing_vars", "are", "present", "in", "ind_var_names", ".", "Raises", "a", "helpful", "ValueError", "if", "otherwise", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L524-L574
train
233,738
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
compute_aic
def compute_aic(model_object): """ Compute the Akaike Information Criteria for an estimated model. Parameters ---------- model_object : an MNDC_Model (multinomial discrete choice model) instance. The model should have already been estimated. `model_object.log_likelihood` should be a number, and `model_object.params` should be a pandas Series. Returns ------- aic : float. The AIC for the estimated model. Notes ----- aic = -2 * log_likelihood + 2 * num_estimated_parameters References ---------- Akaike, H. (1974). 'A new look at the statistical identification model', IEEE Transactions on Automatic Control 19, 6: 716-723. """ 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
python
def compute_aic(model_object): """ Compute the Akaike Information Criteria for an estimated model. Parameters ---------- model_object : an MNDC_Model (multinomial discrete choice model) instance. The model should have already been estimated. `model_object.log_likelihood` should be a number, and `model_object.params` should be a pandas Series. Returns ------- aic : float. The AIC for the estimated model. Notes ----- aic = -2 * log_likelihood + 2 * num_estimated_parameters References ---------- Akaike, H. (1974). 'A new look at the statistical identification model', IEEE Transactions on Automatic Control 19, 6: 716-723. """ 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
[ "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. Parameters ---------- model_object : an MNDC_Model (multinomial discrete choice model) instance. The model should have already been estimated. `model_object.log_likelihood` should be a number, and `model_object.params` should be a pandas Series. Returns ------- aic : float. The AIC for the estimated model. Notes ----- aic = -2 * log_likelihood + 2 * num_estimated_parameters References ---------- Akaike, H. (1974). 'A new look at the statistical identification model', IEEE Transactions on Automatic Control 19, 6: 716-723.
[ "Compute", "the", "Akaike", "Information", "Criteria", "for", "an", "estimated", "model", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L611-L639
train
233,739
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
compute_bic
def compute_bic(model_object): """ Compute the Bayesian Information Criteria for an estimated model. Parameters ---------- model_object : an MNDC_Model (multinomial discrete choice model) instance. The model should have already been estimated. `model_object.log_likelihood` and `model_object.nobs` should be a number, and `model_object.params` should be a pandas Series. Returns ------- bic : float. The BIC for the estimated model. Notes ----- bic = -2 * log_likelihood + log(num_observations) * num_parameters The original BIC was introduced as (-1 / 2) times the formula above. However, for model comparison purposes, it does not matter if the goodness-of-fit measure is multiplied by a constant across all models being compared. Moreover, the formula used above allows for a common scale between measures such as the AIC, BIC, DIC, etc. References ---------- Schwarz, G. (1978), 'Estimating the dimension of a model', The Annals of Statistics 6, 2: 461–464. """ 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.size return -2 * log_likelihood + np.log(num_obs) * num_params
python
def compute_bic(model_object): """ Compute the Bayesian Information Criteria for an estimated model. Parameters ---------- model_object : an MNDC_Model (multinomial discrete choice model) instance. The model should have already been estimated. `model_object.log_likelihood` and `model_object.nobs` should be a number, and `model_object.params` should be a pandas Series. Returns ------- bic : float. The BIC for the estimated model. Notes ----- bic = -2 * log_likelihood + log(num_observations) * num_parameters The original BIC was introduced as (-1 / 2) times the formula above. However, for model comparison purposes, it does not matter if the goodness-of-fit measure is multiplied by a constant across all models being compared. Moreover, the formula used above allows for a common scale between measures such as the AIC, BIC, DIC, etc. References ---------- Schwarz, G. (1978), 'Estimating the dimension of a model', The Annals of Statistics 6, 2: 461–464. """ 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.size return -2 * log_likelihood + np.log(num_obs) * num_params
[ "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", ".", "size", "return", "-", "2", "*", "log_likelihood", "+", "np", ".", "log", "(", "num_obs", ")", "*", "num_params" ]
Compute the Bayesian Information Criteria for an estimated model. Parameters ---------- model_object : an MNDC_Model (multinomial discrete choice model) instance. The model should have already been estimated. `model_object.log_likelihood` and `model_object.nobs` should be a number, and `model_object.params` should be a pandas Series. Returns ------- bic : float. The BIC for the estimated model. Notes ----- bic = -2 * log_likelihood + log(num_observations) * num_parameters The original BIC was introduced as (-1 / 2) times the formula above. However, for model comparison purposes, it does not matter if the goodness-of-fit measure is multiplied by a constant across all models being compared. Moreover, the formula used above allows for a common scale between measures such as the AIC, BIC, DIC, etc. References ---------- Schwarz, G. (1978), 'Estimating the dimension of a model', The Annals of Statistics 6, 2: 461–464.
[ "Compute", "the", "Bayesian", "Information", "Criteria", "for", "an", "estimated", "model", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L642-L681
train
233,740
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
MNDC_Model._create_results_summary
def _create_results_summary(self): """ Create the dataframe that displays the estimation results, and store it on the model instance. Returns ------- None. """ # Make sure we have all attributes needed to create the results summary 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) for attr in needed_attributes]) except AssertionError: msg = "Call this function only after setting/calculating all other" msg_2 = " estimation results attributes" raise NotImplementedError(msg + msg_2) self.summary = pd.concat((self.params, self.standard_errors, self.tvalues, self.pvalues, self.robust_std_errs, self.robust_t_stats, self.robust_p_vals), axis=1) return None
python
def _create_results_summary(self): """ Create the dataframe that displays the estimation results, and store it on the model instance. Returns ------- None. """ # Make sure we have all attributes needed to create the results summary 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) for attr in needed_attributes]) except AssertionError: msg = "Call this function only after setting/calculating all other" msg_2 = " estimation results attributes" raise NotImplementedError(msg + msg_2) self.summary = pd.concat((self.params, self.standard_errors, self.tvalues, self.pvalues, self.robust_std_errs, self.robust_t_stats, self.robust_p_vals), axis=1) return None
[ "def", "_create_results_summary", "(", "self", ")", ":", "# Make sure we have all attributes needed to create the results summary", "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", ")", "for", "attr", "in", "needed_attributes", "]", ")", "except", "AssertionError", ":", "msg", "=", "\"Call this function only after setting/calculating all other\"", "msg_2", "=", "\" estimation results attributes\"", "raise", "NotImplementedError", "(", "msg", "+", "msg_2", ")", "self", ".", "summary", "=", "pd", ".", "concat", "(", "(", "self", ".", "params", ",", "self", ".", "standard_errors", ",", "self", ".", "tvalues", ",", "self", ".", "pvalues", ",", "self", ".", "robust_std_errs", ",", "self", ".", "robust_t_stats", ",", "self", ".", "robust_p_vals", ")", ",", "axis", "=", "1", ")", "return", "None" ]
Create the dataframe that displays the estimation results, and store it on the model instance. Returns ------- None.
[ "Create", "the", "dataframe", "that", "displays", "the", "estimation", "results", "and", "store", "it", "on", "the", "model", "instance", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L995-L1029
train
233,741
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
MNDC_Model._record_values_for_fit_summary_and_statsmodels
def _record_values_for_fit_summary_and_statsmodels(self): """ 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. Returns ------- None. """ # Make sure we have all attributes needed to create the results summary 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]) except AssertionError: msg = "Call this function only after setting/calculating all other" msg_2 = " estimation results attributes" raise NotImplementedError(msg + msg_2) # Record the number of observations self.nobs = self.fitted_probs.shape[0] # This is the number of estimated parameters self.df_model = self.params.shape[0] # The number of observations minus the number of estimated parameters self.df_resid = self.nobs - self.df_model # This is just the log-likelihood. The opaque name is used for # conformance with statsmodels self.llf = self.log_likelihood # This is just a repeat of the standard errors self.bse = self.standard_errors # These are the penalized measures of fit used for model comparison self.aic = compute_aic(self) self.bic = compute_bic(self) return None
python
def _record_values_for_fit_summary_and_statsmodels(self): """ 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. Returns ------- None. """ # Make sure we have all attributes needed to create the results summary 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]) except AssertionError: msg = "Call this function only after setting/calculating all other" msg_2 = " estimation results attributes" raise NotImplementedError(msg + msg_2) # Record the number of observations self.nobs = self.fitted_probs.shape[0] # This is the number of estimated parameters self.df_model = self.params.shape[0] # The number of observations minus the number of estimated parameters self.df_resid = self.nobs - self.df_model # This is just the log-likelihood. The opaque name is used for # conformance with statsmodels self.llf = self.log_likelihood # This is just a repeat of the standard errors self.bse = self.standard_errors # These are the penalized measures of fit used for model comparison self.aic = compute_aic(self) self.bic = compute_bic(self) return None
[ "def", "_record_values_for_fit_summary_and_statsmodels", "(", "self", ")", ":", "# Make sure we have all attributes needed to create the results summary", "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", "]", ")", "except", "AssertionError", ":", "msg", "=", "\"Call this function only after setting/calculating all other\"", "msg_2", "=", "\" estimation results attributes\"", "raise", "NotImplementedError", "(", "msg", "+", "msg_2", ")", "# Record the number of observations", "self", ".", "nobs", "=", "self", ".", "fitted_probs", ".", "shape", "[", "0", "]", "# This is the number of estimated parameters", "self", ".", "df_model", "=", "self", ".", "params", ".", "shape", "[", "0", "]", "# The number of observations minus the number of estimated parameters", "self", ".", "df_resid", "=", "self", ".", "nobs", "-", "self", ".", "df_model", "# This is just the log-likelihood. The opaque name is used for", "# conformance with statsmodels", "self", ".", "llf", "=", "self", ".", "log_likelihood", "# This is just a repeat of the standard errors", "self", ".", "bse", "=", "self", ".", "standard_errors", "# These are the penalized measures of fit used for model comparison", "self", ".", "aic", "=", "compute_aic", "(", "self", ")", "self", ".", "bic", "=", "compute_bic", "(", "self", ")", "return", "None" ]
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. Returns ------- None.
[ "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", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L1031-L1071
train
233,742
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
MNDC_Model._store_inferential_results
def _store_inferential_results(self, value_array, index_names, attribute_name, series_name=None, column_names=None): """ Store the estimation results that relate to statistical inference, such as parameter estimates, standard errors, p-values, etc. Parameters ---------- value_array : 1D or 2D ndarray. Contains the values that are to be stored on the model instance. index_names : list of strings. Contains the names that are to be displayed on the 'rows' for each value being stored. There should be one element for each value of `value_array.` series_name : string or None, optional. The name of the pandas series being created for `value_array.` This kwarg should be None when `value_array` is a 1D ndarray. attribute_name : string. The attribute name that will be exposed on the model instance and related to the passed `value_array.` column_names : list of strings, or None, optional. Same as `index_names` except that it pertains to the columns of a 2D ndarray. When `value_array` is a 2D ndarray, There should be one element for each column of `value_array.` This kwarg should be None otherwise. Returns ------- None. Stores a pandas series or dataframe on the model instance. """ 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.shape) == 2: assert column_names is not None new_attribute_value = pd.DataFrame(value_array, index=index_names, columns=column_names) setattr(self, attribute_name, new_attribute_value) return None
python
def _store_inferential_results(self, value_array, index_names, attribute_name, series_name=None, column_names=None): """ Store the estimation results that relate to statistical inference, such as parameter estimates, standard errors, p-values, etc. Parameters ---------- value_array : 1D or 2D ndarray. Contains the values that are to be stored on the model instance. index_names : list of strings. Contains the names that are to be displayed on the 'rows' for each value being stored. There should be one element for each value of `value_array.` series_name : string or None, optional. The name of the pandas series being created for `value_array.` This kwarg should be None when `value_array` is a 1D ndarray. attribute_name : string. The attribute name that will be exposed on the model instance and related to the passed `value_array.` column_names : list of strings, or None, optional. Same as `index_names` except that it pertains to the columns of a 2D ndarray. When `value_array` is a 2D ndarray, There should be one element for each column of `value_array.` This kwarg should be None otherwise. Returns ------- None. Stores a pandas series or dataframe on the model instance. """ 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.shape) == 2: assert column_names is not None new_attribute_value = pd.DataFrame(value_array, index=index_names, columns=column_names) setattr(self, attribute_name, new_attribute_value) return None
[ "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", ".", "shape", ")", "==", "2", ":", "assert", "column_names", "is", "not", "None", "new_attribute_value", "=", "pd", ".", "DataFrame", "(", "value_array", ",", "index", "=", "index_names", ",", "columns", "=", "column_names", ")", "setattr", "(", "self", ",", "attribute_name", ",", "new_attribute_value", ")", "return", "None" ]
Store the estimation results that relate to statistical inference, such as parameter estimates, standard errors, p-values, etc. Parameters ---------- value_array : 1D or 2D ndarray. Contains the values that are to be stored on the model instance. index_names : list of strings. Contains the names that are to be displayed on the 'rows' for each value being stored. There should be one element for each value of `value_array.` series_name : string or None, optional. The name of the pandas series being created for `value_array.` This kwarg should be None when `value_array` is a 1D ndarray. attribute_name : string. The attribute name that will be exposed on the model instance and related to the passed `value_array.` column_names : list of strings, or None, optional. Same as `index_names` except that it pertains to the columns of a 2D ndarray. When `value_array` is a 2D ndarray, There should be one element for each column of `value_array.` This kwarg should be None otherwise. Returns ------- None. Stores a pandas series or dataframe on the model instance.
[ "Store", "the", "estimation", "results", "that", "relate", "to", "statistical", "inference", "such", "as", "parameter", "estimates", "standard", "errors", "p", "-", "values", "etc", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L1117-L1164
train
233,743
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
MNDC_Model._store_generic_inference_results
def _store_generic_inference_results(self, results_dict, all_params, all_names): """ 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. Parameters ---------- results_dict : dict. The estimation result dictionary that is output from scipy.optimize.minimize. In addition to the standard keys which are included, it should also contain the following keys: `["utility_coefs", "final_gradient", "final_hessian", "fisher_info"]`. The "final_gradient", "final_hessian", and "fisher_info" values should be the gradient, hessian, and Fisher-Information Matrix of the log likelihood, evaluated at the final parameter vector. all_params : list of 1D ndarrays. Should contain the various types of parameters that were actually estimated. all_names : list of strings. Should contain names of each estimated parameter. Returns ------- None. Stores all results on the model instance. """ # Store the utility coefficients self._store_inferential_results(results_dict["utility_coefs"], index_names=self.ind_var_names, attribute_name="coefs", series_name="coefficients") # Store the gradient self._store_inferential_results(results_dict["final_gradient"], index_names=all_names, attribute_name="gradient", series_name="gradient") # Store the hessian self._store_inferential_results(results_dict["final_hessian"], index_names=all_names, attribute_name="hessian", column_names=all_names) # Store the variance-covariance matrix self._store_inferential_results(-1 * scipy.linalg.inv(self.hessian), index_names=all_names, attribute_name="cov", column_names=all_names) # Store ALL of the estimated parameters self._store_inferential_results(np.concatenate(all_params, axis=0), index_names=all_names, attribute_name="params", series_name="parameters") # Store the standard errors self._store_inferential_results(np.sqrt(np.diag(self.cov)), index_names=all_names, attribute_name="standard_errors", series_name="std_err") # Store the t-stats of the estimated parameters self.tvalues = self.params / self.standard_errors self.tvalues.name = "t_stats" # Store the p-values p_vals = 2 * scipy.stats.norm.sf(np.abs(self.tvalues)) self._store_inferential_results(p_vals, index_names=all_names, attribute_name="pvalues", series_name="p_values") # Store the fischer information matrix of estimated coefficients self._store_inferential_results(results_dict["fisher_info"], index_names=all_names, attribute_name="fisher_information", column_names=all_names) # Store the 'robust' variance-covariance matrix robust_covariance = calc_asymptotic_covariance(self.hessian, self.fisher_information) self._store_inferential_results(robust_covariance, index_names=all_names, attribute_name="robust_cov", column_names=all_names) # Store the 'robust' standard errors self._store_inferential_results(np.sqrt(np.diag(self.robust_cov)), index_names=all_names, attribute_name="robust_std_errs", series_name="robust_std_err") # Store the 'robust' t-stats of the estimated coefficients self.robust_t_stats = self.params / self.robust_std_errs self.robust_t_stats.name = "robust_t_stats" # Store the 'robust' p-values one_sided_p_vals = scipy.stats.norm.sf(np.abs(self.robust_t_stats)) self._store_inferential_results(2 * one_sided_p_vals, index_names=all_names, attribute_name="robust_p_vals", series_name="robust_p_values") return None
python
def _store_generic_inference_results(self, results_dict, all_params, all_names): """ 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. Parameters ---------- results_dict : dict. The estimation result dictionary that is output from scipy.optimize.minimize. In addition to the standard keys which are included, it should also contain the following keys: `["utility_coefs", "final_gradient", "final_hessian", "fisher_info"]`. The "final_gradient", "final_hessian", and "fisher_info" values should be the gradient, hessian, and Fisher-Information Matrix of the log likelihood, evaluated at the final parameter vector. all_params : list of 1D ndarrays. Should contain the various types of parameters that were actually estimated. all_names : list of strings. Should contain names of each estimated parameter. Returns ------- None. Stores all results on the model instance. """ # Store the utility coefficients self._store_inferential_results(results_dict["utility_coefs"], index_names=self.ind_var_names, attribute_name="coefs", series_name="coefficients") # Store the gradient self._store_inferential_results(results_dict["final_gradient"], index_names=all_names, attribute_name="gradient", series_name="gradient") # Store the hessian self._store_inferential_results(results_dict["final_hessian"], index_names=all_names, attribute_name="hessian", column_names=all_names) # Store the variance-covariance matrix self._store_inferential_results(-1 * scipy.linalg.inv(self.hessian), index_names=all_names, attribute_name="cov", column_names=all_names) # Store ALL of the estimated parameters self._store_inferential_results(np.concatenate(all_params, axis=0), index_names=all_names, attribute_name="params", series_name="parameters") # Store the standard errors self._store_inferential_results(np.sqrt(np.diag(self.cov)), index_names=all_names, attribute_name="standard_errors", series_name="std_err") # Store the t-stats of the estimated parameters self.tvalues = self.params / self.standard_errors self.tvalues.name = "t_stats" # Store the p-values p_vals = 2 * scipy.stats.norm.sf(np.abs(self.tvalues)) self._store_inferential_results(p_vals, index_names=all_names, attribute_name="pvalues", series_name="p_values") # Store the fischer information matrix of estimated coefficients self._store_inferential_results(results_dict["fisher_info"], index_names=all_names, attribute_name="fisher_information", column_names=all_names) # Store the 'robust' variance-covariance matrix robust_covariance = calc_asymptotic_covariance(self.hessian, self.fisher_information) self._store_inferential_results(robust_covariance, index_names=all_names, attribute_name="robust_cov", column_names=all_names) # Store the 'robust' standard errors self._store_inferential_results(np.sqrt(np.diag(self.robust_cov)), index_names=all_names, attribute_name="robust_std_errs", series_name="robust_std_err") # Store the 'robust' t-stats of the estimated coefficients self.robust_t_stats = self.params / self.robust_std_errs self.robust_t_stats.name = "robust_t_stats" # Store the 'robust' p-values one_sided_p_vals = scipy.stats.norm.sf(np.abs(self.robust_t_stats)) self._store_inferential_results(2 * one_sided_p_vals, index_names=all_names, attribute_name="robust_p_vals", series_name="robust_p_values") return None
[ "def", "_store_generic_inference_results", "(", "self", ",", "results_dict", ",", "all_params", ",", "all_names", ")", ":", "# Store the utility coefficients", "self", ".", "_store_inferential_results", "(", "results_dict", "[", "\"utility_coefs\"", "]", ",", "index_names", "=", "self", ".", "ind_var_names", ",", "attribute_name", "=", "\"coefs\"", ",", "series_name", "=", "\"coefficients\"", ")", "# Store the gradient", "self", ".", "_store_inferential_results", "(", "results_dict", "[", "\"final_gradient\"", "]", ",", "index_names", "=", "all_names", ",", "attribute_name", "=", "\"gradient\"", ",", "series_name", "=", "\"gradient\"", ")", "# Store the hessian", "self", ".", "_store_inferential_results", "(", "results_dict", "[", "\"final_hessian\"", "]", ",", "index_names", "=", "all_names", ",", "attribute_name", "=", "\"hessian\"", ",", "column_names", "=", "all_names", ")", "# Store the variance-covariance matrix", "self", ".", "_store_inferential_results", "(", "-", "1", "*", "scipy", ".", "linalg", ".", "inv", "(", "self", ".", "hessian", ")", ",", "index_names", "=", "all_names", ",", "attribute_name", "=", "\"cov\"", ",", "column_names", "=", "all_names", ")", "# Store ALL of the estimated parameters", "self", ".", "_store_inferential_results", "(", "np", ".", "concatenate", "(", "all_params", ",", "axis", "=", "0", ")", ",", "index_names", "=", "all_names", ",", "attribute_name", "=", "\"params\"", ",", "series_name", "=", "\"parameters\"", ")", "# Store the standard errors", "self", ".", "_store_inferential_results", "(", "np", ".", "sqrt", "(", "np", ".", "diag", "(", "self", ".", "cov", ")", ")", ",", "index_names", "=", "all_names", ",", "attribute_name", "=", "\"standard_errors\"", ",", "series_name", "=", "\"std_err\"", ")", "# Store the t-stats of the estimated parameters", "self", ".", "tvalues", "=", "self", ".", "params", "/", "self", ".", "standard_errors", "self", ".", "tvalues", ".", "name", "=", "\"t_stats\"", "# Store the p-values", "p_vals", "=", "2", "*", "scipy", ".", "stats", ".", "norm", ".", "sf", "(", "np", ".", "abs", "(", "self", ".", "tvalues", ")", ")", "self", ".", "_store_inferential_results", "(", "p_vals", ",", "index_names", "=", "all_names", ",", "attribute_name", "=", "\"pvalues\"", ",", "series_name", "=", "\"p_values\"", ")", "# Store the fischer information matrix of estimated coefficients", "self", ".", "_store_inferential_results", "(", "results_dict", "[", "\"fisher_info\"", "]", ",", "index_names", "=", "all_names", ",", "attribute_name", "=", "\"fisher_information\"", ",", "column_names", "=", "all_names", ")", "# Store the 'robust' variance-covariance matrix", "robust_covariance", "=", "calc_asymptotic_covariance", "(", "self", ".", "hessian", ",", "self", ".", "fisher_information", ")", "self", ".", "_store_inferential_results", "(", "robust_covariance", ",", "index_names", "=", "all_names", ",", "attribute_name", "=", "\"robust_cov\"", ",", "column_names", "=", "all_names", ")", "# Store the 'robust' standard errors", "self", ".", "_store_inferential_results", "(", "np", ".", "sqrt", "(", "np", ".", "diag", "(", "self", ".", "robust_cov", ")", ")", ",", "index_names", "=", "all_names", ",", "attribute_name", "=", "\"robust_std_errs\"", ",", "series_name", "=", "\"robust_std_err\"", ")", "# Store the 'robust' t-stats of the estimated coefficients", "self", ".", "robust_t_stats", "=", "self", ".", "params", "/", "self", ".", "robust_std_errs", "self", ".", "robust_t_stats", ".", "name", "=", "\"robust_t_stats\"", "# Store the 'robust' p-values", "one_sided_p_vals", "=", "scipy", ".", "stats", ".", "norm", ".", "sf", "(", "np", ".", "abs", "(", "self", ".", "robust_t_stats", ")", ")", "self", ".", "_store_inferential_results", "(", "2", "*", "one_sided_p_vals", ",", "index_names", "=", "all_names", ",", "attribute_name", "=", "\"robust_p_vals\"", ",", "series_name", "=", "\"robust_p_values\"", ")", "return", "None" ]
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. Parameters ---------- results_dict : dict. The estimation result dictionary that is output from scipy.optimize.minimize. In addition to the standard keys which are included, it should also contain the following keys: `["utility_coefs", "final_gradient", "final_hessian", "fisher_info"]`. The "final_gradient", "final_hessian", and "fisher_info" values should be the gradient, hessian, and Fisher-Information Matrix of the log likelihood, evaluated at the final parameter vector. all_params : list of 1D ndarrays. Should contain the various types of parameters that were actually estimated. all_names : list of strings. Should contain names of each estimated parameter. Returns ------- None. Stores all results on the model instance.
[ "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", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L1166-L1275
train
233,744
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
MNDC_Model._store_optional_parameters
def _store_optional_parameters(self, optional_params, name_list_attr, default_name_str, all_names, all_params, param_attr_name, series_name): """ 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. Parameters ---------- optional_params : 1D ndarray. The optional parameters whose values and names should be stored. name_list_attr : str. The attribute name on the model object where the names of the optional estimated parameters will be stored (if they exist). default_name_str : str. The name string that will be used to create generic names for the estimated parameters, in the event that the estimated parameters do not have names that were specified by the user. Should contain empty curly braces for use with python string formatting. all_names : list of strings. The current list of the names of the estimated parameters. The names of these optional parameters will be added to the beginning of this list. all_params : list of 1D ndarrays. Each array is a set of estimated parameters. The current optional parameters will be added to the beginning of this list. param_attr_name : str. The attribute name that will be used to store the optional parameter values on the model object. series_name : str. The string that will be used as the name of the series that contains the optional parameters. Returns ------- (all_names, all_params) : tuple. """ # Identify the number of optional parameters num_elements = optional_params.shape[0] # Get the names of the optional parameters parameter_names = getattr(self, name_list_attr) if parameter_names is None: parameter_names = [default_name_str.format(x) for x in range(1, num_elements + 1)] # Store the names of the optional parameters in all_names all_names = list(parameter_names) + list(all_names) # Store the values of the optional parameters in all_params all_params.insert(0, optional_params) # Store the optional parameters on the model object self._store_inferential_results(optional_params, index_names=parameter_names, attribute_name=param_attr_name, series_name=series_name) return all_names, all_params
python
def _store_optional_parameters(self, optional_params, name_list_attr, default_name_str, all_names, all_params, param_attr_name, series_name): """ 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. Parameters ---------- optional_params : 1D ndarray. The optional parameters whose values and names should be stored. name_list_attr : str. The attribute name on the model object where the names of the optional estimated parameters will be stored (if they exist). default_name_str : str. The name string that will be used to create generic names for the estimated parameters, in the event that the estimated parameters do not have names that were specified by the user. Should contain empty curly braces for use with python string formatting. all_names : list of strings. The current list of the names of the estimated parameters. The names of these optional parameters will be added to the beginning of this list. all_params : list of 1D ndarrays. Each array is a set of estimated parameters. The current optional parameters will be added to the beginning of this list. param_attr_name : str. The attribute name that will be used to store the optional parameter values on the model object. series_name : str. The string that will be used as the name of the series that contains the optional parameters. Returns ------- (all_names, all_params) : tuple. """ # Identify the number of optional parameters num_elements = optional_params.shape[0] # Get the names of the optional parameters parameter_names = getattr(self, name_list_attr) if parameter_names is None: parameter_names = [default_name_str.format(x) for x in range(1, num_elements + 1)] # Store the names of the optional parameters in all_names all_names = list(parameter_names) + list(all_names) # Store the values of the optional parameters in all_params all_params.insert(0, optional_params) # Store the optional parameters on the model object self._store_inferential_results(optional_params, index_names=parameter_names, attribute_name=param_attr_name, series_name=series_name) return all_names, all_params
[ "def", "_store_optional_parameters", "(", "self", ",", "optional_params", ",", "name_list_attr", ",", "default_name_str", ",", "all_names", ",", "all_params", ",", "param_attr_name", ",", "series_name", ")", ":", "# Identify the number of optional parameters", "num_elements", "=", "optional_params", ".", "shape", "[", "0", "]", "# Get the names of the optional parameters", "parameter_names", "=", "getattr", "(", "self", ",", "name_list_attr", ")", "if", "parameter_names", "is", "None", ":", "parameter_names", "=", "[", "default_name_str", ".", "format", "(", "x", ")", "for", "x", "in", "range", "(", "1", ",", "num_elements", "+", "1", ")", "]", "# Store the names of the optional parameters in all_names", "all_names", "=", "list", "(", "parameter_names", ")", "+", "list", "(", "all_names", ")", "# Store the values of the optional parameters in all_params", "all_params", ".", "insert", "(", "0", ",", "optional_params", ")", "# Store the optional parameters on the model object", "self", ".", "_store_inferential_results", "(", "optional_params", ",", "index_names", "=", "parameter_names", ",", "attribute_name", "=", "param_attr_name", ",", "series_name", "=", "series_name", ")", "return", "all_names", ",", "all_params" ]
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. Parameters ---------- optional_params : 1D ndarray. The optional parameters whose values and names should be stored. name_list_attr : str. The attribute name on the model object where the names of the optional estimated parameters will be stored (if they exist). default_name_str : str. The name string that will be used to create generic names for the estimated parameters, in the event that the estimated parameters do not have names that were specified by the user. Should contain empty curly braces for use with python string formatting. all_names : list of strings. The current list of the names of the estimated parameters. The names of these optional parameters will be added to the beginning of this list. all_params : list of 1D ndarrays. Each array is a set of estimated parameters. The current optional parameters will be added to the beginning of this list. param_attr_name : str. The attribute name that will be used to store the optional parameter values on the model object. series_name : str. The string that will be used as the name of the series that contains the optional parameters. Returns ------- (all_names, all_params) : tuple.
[ "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", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L1277-L1339
train
233,745
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
MNDC_Model._adjust_inferential_results_for_parameter_constraints
def _adjust_inferential_results_for_parameter_constraints(self, constraints): """ Ensure that parameters that were constrained during estimation do not have any values showed for inferential results. After all, no inference was performed. Parameters ---------- constraints : list of ints, or None. If list, should contain the positions in the array of all estimated parameters that were constrained to their initial values. Returns ------- None. """ if constraints is not None: # Ensure the model object has inferential results 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 hasattr(self, "params") all_names = self.params.index.tolist() for series in [getattr(self, x) for x in inferential_attributes]: for pos in constraints: series.loc[all_names[pos]] = np.nan return None
python
def _adjust_inferential_results_for_parameter_constraints(self, constraints): """ Ensure that parameters that were constrained during estimation do not have any values showed for inferential results. After all, no inference was performed. Parameters ---------- constraints : list of ints, or None. If list, should contain the positions in the array of all estimated parameters that were constrained to their initial values. Returns ------- None. """ if constraints is not None: # Ensure the model object has inferential results 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 hasattr(self, "params") all_names = self.params.index.tolist() for series in [getattr(self, x) for x in inferential_attributes]: for pos in constraints: series.loc[all_names[pos]] = np.nan return None
[ "def", "_adjust_inferential_results_for_parameter_constraints", "(", "self", ",", "constraints", ")", ":", "if", "constraints", "is", "not", "None", ":", "# Ensure the model object has inferential results", "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", "hasattr", "(", "self", ",", "\"params\"", ")", "all_names", "=", "self", ".", "params", ".", "index", ".", "tolist", "(", ")", "for", "series", "in", "[", "getattr", "(", "self", ",", "x", ")", "for", "x", "in", "inferential_attributes", "]", ":", "for", "pos", "in", "constraints", ":", "series", ".", "loc", "[", "all_names", "[", "pos", "]", "]", "=", "np", ".", "nan", "return", "None" ]
Ensure that parameters that were constrained during estimation do not have any values showed for inferential results. After all, no inference was performed. Parameters ---------- constraints : list of ints, or None. If list, should contain the positions in the array of all estimated parameters that were constrained to their initial values. Returns ------- None.
[ "Ensure", "that", "parameters", "that", "were", "constrained", "during", "estimation", "do", "not", "have", "any", "values", "showed", "for", "inferential", "results", ".", "After", "all", "no", "inference", "was", "performed", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L1341-L1375
train
233,746
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
MNDC_Model._check_result_dict_for_needed_keys
def _check_result_dict_for_needed_keys(self, results_dict): """ Ensure that `results_dict` has the needed keys to store all the estimation results. Raise a helpful ValueError otherwise. """ 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
python
def _check_result_dict_for_needed_keys(self, results_dict): """ Ensure that `results_dict` has the needed keys to store all the estimation results. Raise a helpful ValueError otherwise. """ 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
[ "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.
[ "Ensure", "that", "results_dict", "has", "the", "needed", "keys", "to", "store", "all", "the", "estimation", "results", ".", "Raise", "a", "helpful", "ValueError", "otherwise", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L1377-L1386
train
233,747
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
MNDC_Model._add_mixing_variable_names_to_individual_vars
def _add_mixing_variable_names_to_individual_vars(self): """ Ensure that the model objects mixing variables are added to its list of individual variables. """ assert isinstance(self.ind_var_names, list) # Note that if one estimates a mixed logit model, then the mixing # variables will be added to individual vars. And if one estimates # the model again (perhaps from different starting values), then # an error will be raised when creating the coefs series because we # will have added the mixing variables twice. The condition below # should prevent this error. 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.ind_var_names += new_ind_var_names return None
python
def _add_mixing_variable_names_to_individual_vars(self): """ Ensure that the model objects mixing variables are added to its list of individual variables. """ assert isinstance(self.ind_var_names, list) # Note that if one estimates a mixed logit model, then the mixing # variables will be added to individual vars. And if one estimates # the model again (perhaps from different starting values), then # an error will be raised when creating the coefs series because we # will have added the mixing variables twice. The condition below # should prevent this error. 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.ind_var_names += new_ind_var_names return None
[ "def", "_add_mixing_variable_names_to_individual_vars", "(", "self", ")", ":", "assert", "isinstance", "(", "self", ".", "ind_var_names", ",", "list", ")", "# Note that if one estimates a mixed logit model, then the mixing", "# variables will be added to individual vars. And if one estimates", "# the model again (perhaps from different starting values), then", "# an error will be raised when creating the coefs series because we", "# will have added the mixing variables twice. The condition below", "# should prevent this error.", "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", ".", "ind_var_names", "+=", "new_ind_var_names", "return", "None" ]
Ensure that the model objects mixing variables are added to its list of individual variables.
[ "Ensure", "that", "the", "model", "objects", "mixing", "variables", "are", "added", "to", "its", "list", "of", "individual", "variables", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L1388-L1405
train
233,748
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
MNDC_Model.print_summaries
def print_summaries(self): """ Returns None. Will print the measures of fit and the estimation results for the model. """ 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 NotImplementedError(msg.format(self.model_type) + msg_2) return None
python
def print_summaries(self): """ Returns None. Will print the measures of fit and the estimation results for the model. """ 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 NotImplementedError(msg.format(self.model_type) + msg_2) return None
[ "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", "NotImplementedError", "(", "msg", ".", "format", "(", "self", ".", "model_type", ")", "+", "msg_2", ")", "return", "None" ]
Returns None. Will print the measures of fit and the estimation results for the model.
[ "Returns", "None", ".", "Will", "print", "the", "measures", "of", "fit", "and", "the", "estimation", "results", "for", "the", "model", "." ]
f83b0fd6debaa7358d87c3828428f6d4ead71357
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L1556-L1572
train
233,749
taskcluster/json-e
jsone/prattparser.py
prefix
def prefix(*kinds): """Decorate a method as handling prefix tokens of the given kinds""" def wrap(fn): try: fn.prefix_kinds.extend(kinds) except AttributeError: fn.prefix_kinds = list(kinds) return fn return wrap
python
def prefix(*kinds): """Decorate a method as handling prefix tokens of the given kinds""" def wrap(fn): try: fn.prefix_kinds.extend(kinds) except AttributeError: fn.prefix_kinds = list(kinds) return fn return wrap
[ "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
[ "Decorate", "a", "method", "as", "handling", "prefix", "tokens", "of", "the", "given", "kinds" ]
ac0c9fba1de3ed619f05a64dae929f6687789cbc
https://github.com/taskcluster/json-e/blob/ac0c9fba1de3ed619f05a64dae929f6687789cbc/jsone/prattparser.py#L20-L28
train
233,750
taskcluster/json-e
jsone/prattparser.py
infix
def infix(*kinds): """Decorate a method as handling infix tokens of the given kinds""" def wrap(fn): try: fn.infix_kinds.extend(kinds) except AttributeError: fn.infix_kinds = list(kinds) return fn return wrap
python
def infix(*kinds): """Decorate a method as handling infix tokens of the given kinds""" def wrap(fn): try: fn.infix_kinds.extend(kinds) except AttributeError: fn.infix_kinds = list(kinds) return fn return wrap
[ "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
[ "Decorate", "a", "method", "as", "handling", "infix", "tokens", "of", "the", "given", "kinds" ]
ac0c9fba1de3ed619f05a64dae929f6687789cbc
https://github.com/taskcluster/json-e/blob/ac0c9fba1de3ed619f05a64dae929f6687789cbc/jsone/prattparser.py#L31-L39
train
233,751
taskcluster/json-e
jsone/prattparser.py
ParseContext.attempt
def attempt(self, *kinds): """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.""" 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
python
def attempt(self, *kinds): """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.""" 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
[ "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.
[ "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", "." ]
ac0c9fba1de3ed619f05a64dae929f6687789cbc
https://github.com/taskcluster/json-e/blob/ac0c9fba1de3ed619f05a64dae929f6687789cbc/jsone/prattparser.py#L150-L162
train
233,752
taskcluster/json-e
jsone/prattparser.py
ParseContext.require
def require(self, *kinds): """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.""" 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
python
def require(self, *kinds): """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.""" 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
[ "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.
[ "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", "." ]
ac0c9fba1de3ed619f05a64dae929f6687789cbc
https://github.com/taskcluster/json-e/blob/ac0c9fba1de3ed619f05a64dae929f6687789cbc/jsone/prattparser.py#L164-L173
train
233,753
amzn/ion-python
amazon/ion/symbols.py
local_symbol_table
def local_symbol_table(imports=None, symbols=()): """Constructs a local symbol table. Args: imports (Optional[SymbolTable]): Shared symbol tables to import. symbols (Optional[Iterable[Unicode]]): Initial local symbols to add. Returns: SymbolTable: A mutable local symbol table with the seeded local symbols. """ return SymbolTable( table_type=LOCAL_TABLE_TYPE, symbols=symbols, imports=imports )
python
def local_symbol_table(imports=None, symbols=()): """Constructs a local symbol table. Args: imports (Optional[SymbolTable]): Shared symbol tables to import. symbols (Optional[Iterable[Unicode]]): Initial local symbols to add. Returns: SymbolTable: A mutable local symbol table with the seeded local symbols. """ return SymbolTable( table_type=LOCAL_TABLE_TYPE, symbols=symbols, imports=imports )
[ "def", "local_symbol_table", "(", "imports", "=", "None", ",", "symbols", "=", "(", ")", ")", ":", "return", "SymbolTable", "(", "table_type", "=", "LOCAL_TABLE_TYPE", ",", "symbols", "=", "symbols", ",", "imports", "=", "imports", ")" ]
Constructs a local symbol table. Args: imports (Optional[SymbolTable]): Shared symbol tables to import. symbols (Optional[Iterable[Unicode]]): Initial local symbols to add. Returns: SymbolTable: A mutable local symbol table with the seeded local symbols.
[ "Constructs", "a", "local", "symbol", "table", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L380-L394
train
233,754
amzn/ion-python
amazon/ion/symbols.py
shared_symbol_table
def shared_symbol_table(name, version, symbols, imports=None): """Constructs a shared symbol table. Args: name (unicode): The name of the shared symbol table. version (int): The version of the shared symbol table. symbols (Iterable[unicode]): The symbols to associate with the table. imports (Optional[Iterable[SymbolTable]): The shared symbol tables to inject into this one. Returns: SymbolTable: The constructed table. """ return SymbolTable( table_type=SHARED_TABLE_TYPE, symbols=symbols, name=name, version=version, imports=imports )
python
def shared_symbol_table(name, version, symbols, imports=None): """Constructs a shared symbol table. Args: name (unicode): The name of the shared symbol table. version (int): The version of the shared symbol table. symbols (Iterable[unicode]): The symbols to associate with the table. imports (Optional[Iterable[SymbolTable]): The shared symbol tables to inject into this one. Returns: SymbolTable: The constructed table. """ return SymbolTable( table_type=SHARED_TABLE_TYPE, symbols=symbols, name=name, version=version, imports=imports )
[ "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. Args: name (unicode): The name of the shared symbol table. version (int): The version of the shared symbol table. symbols (Iterable[unicode]): The symbols to associate with the table. imports (Optional[Iterable[SymbolTable]): The shared symbol tables to inject into this one. Returns: SymbolTable: The constructed table.
[ "Constructs", "a", "shared", "symbol", "table", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L397-L415
train
233,755
amzn/ion-python
amazon/ion/symbols.py
placeholder_symbol_table
def placeholder_symbol_table(name, version, max_id): """Constructs a shared symbol table that consists symbols that all have no known text. This is generally used for cases where a shared symbol table is not available by the application. Args: name (unicode): The name of the shared symbol table. version (int): The version of the shared symbol table. max_id (int): The maximum ID allocated by this symbol table, must be ``>= 0`` Returns: SymbolTable: The synthesized 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 must be zero or positive: %s' % max_id) return SymbolTable( table_type=SHARED_TABLE_TYPE, symbols=repeat(None, max_id), name=name, version=version, is_substitute=True )
python
def placeholder_symbol_table(name, version, max_id): """Constructs a shared symbol table that consists symbols that all have no known text. This is generally used for cases where a shared symbol table is not available by the application. Args: name (unicode): The name of the shared symbol table. version (int): The version of the shared symbol table. max_id (int): The maximum ID allocated by this symbol table, must be ``>= 0`` Returns: SymbolTable: The synthesized 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 must be zero or positive: %s' % max_id) return SymbolTable( table_type=SHARED_TABLE_TYPE, symbols=repeat(None, max_id), name=name, version=version, is_substitute=True )
[ "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", ",", "max_id", ")", ",", "name", "=", "name", ",", "version", "=", "version", ",", "is_substitute", "=", "True", ")" ]
Constructs a shared symbol table that consists symbols that all have no known text. This is generally used for cases where a shared symbol table is not available by the application. Args: name (unicode): The name of the shared symbol table. version (int): The version of the shared symbol table. max_id (int): The maximum ID allocated by this symbol table, must be ``>= 0`` Returns: SymbolTable: The synthesized table.
[ "Constructs", "a", "shared", "symbol", "table", "that", "consists", "symbols", "that", "all", "have", "no", "known", "text", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L418-L443
train
233,756
amzn/ion-python
amazon/ion/symbols.py
substitute_symbol_table
def substitute_symbol_table(table, version, max_id): """Substitutes a given shared symbol table for another version. * If the given table has **more** symbols than the requested substitute, then the generated symbol table will be a subset of the given table. * If the given table has **less** symbols than the requested substitute, then the generated symbol table will have symbols with unknown text generated for the difference. Args: table (SymbolTable): The shared table to derive from. version (int): The version to target. max_id (int): The maximum ID allocated by the substitute, must be ``>= 0``. Returns: SymbolTable: The synthesized table. """ 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 must be zero or positive: %s' % max_id) # TODO Recycle the symbol tokens from the source table into the substitute. if max_id <= table.max_id: symbols = (token.text for token in islice(table, max_id)) else: symbols = chain( (token.text for token in table), repeat(None, max_id - table.max_id) ) return SymbolTable( table_type=SHARED_TABLE_TYPE, symbols=symbols, name=table.name, version=version, is_substitute=True )
python
def substitute_symbol_table(table, version, max_id): """Substitutes a given shared symbol table for another version. * If the given table has **more** symbols than the requested substitute, then the generated symbol table will be a subset of the given table. * If the given table has **less** symbols than the requested substitute, then the generated symbol table will have symbols with unknown text generated for the difference. Args: table (SymbolTable): The shared table to derive from. version (int): The version to target. max_id (int): The maximum ID allocated by the substitute, must be ``>= 0``. Returns: SymbolTable: The synthesized table. """ 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 must be zero or positive: %s' % max_id) # TODO Recycle the symbol tokens from the source table into the substitute. if max_id <= table.max_id: symbols = (token.text for token in islice(table, max_id)) else: symbols = chain( (token.text for token in table), repeat(None, max_id - table.max_id) ) return SymbolTable( table_type=SHARED_TABLE_TYPE, symbols=symbols, name=table.name, version=version, is_substitute=True )
[ "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 must be zero or positive: %s'", "%", "max_id", ")", "# TODO Recycle the symbol tokens from the source table into the substitute.", "if", "max_id", "<=", "table", ".", "max_id", ":", "symbols", "=", "(", "token", ".", "text", "for", "token", "in", "islice", "(", "table", ",", "max_id", ")", ")", "else", ":", "symbols", "=", "chain", "(", "(", "token", ".", "text", "for", "token", "in", "table", ")", ",", "repeat", "(", "None", ",", "max_id", "-", "table", ".", "max_id", ")", ")", "return", "SymbolTable", "(", "table_type", "=", "SHARED_TABLE_TYPE", ",", "symbols", "=", "symbols", ",", "name", "=", "table", ".", "name", ",", "version", "=", "version", ",", "is_substitute", "=", "True", ")" ]
Substitutes a given shared symbol table for another version. * If the given table has **more** symbols than the requested substitute, then the generated symbol table will be a subset of the given table. * If the given table has **less** symbols than the requested substitute, then the generated symbol table will have symbols with unknown text generated for the difference. Args: table (SymbolTable): The shared table to derive from. version (int): The version to target. max_id (int): The maximum ID allocated by the substitute, must be ``>= 0``. Returns: SymbolTable: The synthesized table.
[ "Substitutes", "a", "given", "shared", "symbol", "table", "for", "another", "version", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L446-L484
train
233,757
amzn/ion-python
amazon/ion/symbols.py
SymbolTable.__add
def __add(self, token): """Unconditionally adds a token to the table.""" self.__symbols.append(token) text = token.text if text is not None and text not in self.__mapping: self.__mapping[text] = token
python
def __add(self, token): """Unconditionally adds a token to the table.""" self.__symbols.append(token) text = token.text if text is not None and text not in self.__mapping: self.__mapping[text] = token
[ "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.
[ "Unconditionally", "adds", "a", "token", "to", "the", "table", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L213-L218
train
233,758
amzn/ion-python
amazon/ion/symbols.py
SymbolTable.__add_shared
def __add_shared(self, original_token): """Adds a token, normalizing the SID and import reference to this table.""" sid = self.__new_sid() token = SymbolToken(original_token.text, sid, self.__import_location(sid)) self.__add(token) return token
python
def __add_shared(self, original_token): """Adds a token, normalizing the SID and import reference to this table.""" sid = self.__new_sid() token = SymbolToken(original_token.text, sid, self.__import_location(sid)) self.__add(token) return token
[ "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.
[ "Adds", "a", "token", "normalizing", "the", "SID", "and", "import", "reference", "to", "this", "table", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L220-L225
train
233,759
amzn/ion-python
amazon/ion/symbols.py
SymbolTable.__add_import
def __add_import(self, original_token): """Adds a token, normalizing only the SID""" sid = self.__new_sid() token = SymbolToken(original_token.text, sid, original_token.location) self.__add(token) return token
python
def __add_import(self, original_token): """Adds a token, normalizing only the SID""" sid = self.__new_sid() token = SymbolToken(original_token.text, sid, original_token.location) self.__add(token) return token
[ "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
[ "Adds", "a", "token", "normalizing", "only", "the", "SID" ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L227-L232
train
233,760
amzn/ion-python
amazon/ion/symbols.py
SymbolTable.__add_text
def __add_text(self, text): """Adds the given Unicode text as a locally defined symbol.""" 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 = SymbolToken(text, sid, location) self.__add(token) return token
python
def __add_text(self, text): """Adds the given Unicode text as a locally defined symbol.""" 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 = SymbolToken(text, sid, location) self.__add(token) return token
[ "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", "=", "SymbolToken", "(", "text", ",", "sid", ",", "location", ")", "self", ".", "__add", "(", "token", ")", "return", "token" ]
Adds the given Unicode text as a locally defined symbol.
[ "Adds", "the", "given", "Unicode", "text", "as", "a", "locally", "defined", "symbol", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L234-L244
train
233,761
amzn/ion-python
amazon/ion/symbols.py
SymbolTable.intern
def intern(self, text): """Interns the given Unicode sequence into the symbol table. Note: This operation is only valid on local symbol tables. Args: text (unicode): The target to intern. Returns: SymbolToken: The mapped symbol token which may already exist in the table. """ 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.__add_text(text) return token
python
def intern(self, text): """Interns the given Unicode sequence into the symbol table. Note: This operation is only valid on local symbol tables. Args: text (unicode): The target to intern. Returns: SymbolToken: The mapped symbol token which may already exist in the table. """ 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.__add_text(text) return token
[ "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", ".", "__add_text", "(", "text", ")", "return", "token" ]
Interns the given Unicode sequence into the symbol table. Note: This operation is only valid on local symbol tables. Args: text (unicode): The target to intern. Returns: SymbolToken: The mapped symbol token which may already exist in the table.
[ "Interns", "the", "given", "Unicode", "sequence", "into", "the", "symbol", "table", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L246-L266
train
233,762
amzn/ion-python
amazon/ion/symbols.py
SymbolTable.get
def get(self, key, default=None): """Returns a token by text or local ID, with a default. A given text image may be associated with more than one symbol ID. This will return the first definition. Note: User defined symbol IDs are always one-based. Symbol zero is a special symbol that always has no text. Args: key (unicode | int): The key to lookup. default(Optional[SymbolToken]): The default to return if the key is not found Returns: SymbolToken: The token associated with the key or the default if it doesn't exist. """ 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.') # TODO determine if $0 should be returned for all symbol tables. if key == 0: return SYMBOL_ZERO_TOKEN # Translate one-based SID to zero-based intern table index = key - 1 if index < 0 or key > len(self): return default return self.__symbols[index]
python
def get(self, key, default=None): """Returns a token by text or local ID, with a default. A given text image may be associated with more than one symbol ID. This will return the first definition. Note: User defined symbol IDs are always one-based. Symbol zero is a special symbol that always has no text. Args: key (unicode | int): The key to lookup. default(Optional[SymbolToken]): The default to return if the key is not found Returns: SymbolToken: The token associated with the key or the default if it doesn't exist. """ 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.') # TODO determine if $0 should be returned for all symbol tables. if key == 0: return SYMBOL_ZERO_TOKEN # Translate one-based SID to zero-based intern table index = key - 1 if index < 0 or key > len(self): return default return self.__symbols[index]
[ "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.'", ")", "# TODO determine if $0 should be returned for all symbol tables.", "if", "key", "==", "0", ":", "return", "SYMBOL_ZERO_TOKEN", "# Translate one-based SID to zero-based intern table", "index", "=", "key", "-", "1", "if", "index", "<", "0", "or", "key", ">", "len", "(", "self", ")", ":", "return", "default", "return", "self", ".", "__symbols", "[", "index", "]" ]
Returns a token by text or local ID, with a default. A given text image may be associated with more than one symbol ID. This will return the first definition. Note: User defined symbol IDs are always one-based. Symbol zero is a special symbol that always has no text. Args: key (unicode | int): The key to lookup. default(Optional[SymbolToken]): The default to return if the key is not found Returns: SymbolToken: The token associated with the key or the default if it doesn't exist.
[ "Returns", "a", "token", "by", "text", "or", "local", "ID", "with", "a", "default", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L268-L297
train
233,763
amzn/ion-python
amazon/ion/symbols.py
SymbolTableCatalog.register
def register(self, table): """Adds a shared table to the catalog. Args: table (SymbolTable): A non-system, shared symbol 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 = self.__tables.get(table.name) if versions is None: versions = {} self.__tables[table.name] = versions versions[table.version] = table
python
def register(self, table): """Adds a shared table to the catalog. Args: table (SymbolTable): A non-system, shared symbol 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 = self.__tables.get(table.name) if versions is None: versions = {} self.__tables[table.name] = versions versions[table.version] = table
[ "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", "=", "self", ".", "__tables", ".", "get", "(", "table", ".", "name", ")", "if", "versions", "is", "None", ":", "versions", "=", "{", "}", "self", ".", "__tables", "[", "table", ".", "name", "]", "=", "versions", "versions", "[", "table", ".", "version", "]", "=", "table" ]
Adds a shared table to the catalog. Args: table (SymbolTable): A non-system, shared symbol table.
[ "Adds", "a", "shared", "table", "to", "the", "catalog", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L499-L516
train
233,764
amzn/ion-python
amazon/ion/symbols.py
SymbolTableCatalog.resolve
def resolve(self, name, version, max_id): """Resolves the table for a given name and version. Args: name (unicode): The name of the table to resolve. version (int): The version of the table to resolve. max_id (Optional[int]): The maximum ID of the table requested. May be ``None`` in which case an exact match on ``name`` and ``version`` is required. Returns: SymbolTable: The *closest* matching symbol table. This is either an exact match, a placeholder, or a derived substitute depending on what tables are registered. """ 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: %s' % version) if max_id is not None and max_id < 0: raise ValueError('Max ID must be zero or positive: %s' % max_id) versions = self.__tables.get(name) if versions is None: if max_id is None: raise CannotSubstituteTable( 'Found no table for %s, but no max_id' % name ) return placeholder_symbol_table(name, version, max_id) table = versions.get(version) if table is None: # TODO Replace the keys map with a search tree based dictionary. keys = list(versions) keys.sort() table = versions[keys[-1]] if table.version == version and (max_id is None or table.max_id == max_id): return table if max_id is None: raise CannotSubstituteTable( 'Found match for %s, but not version %d, and no max_id' % (name, version) ) return substitute_symbol_table(table, version, max_id)
python
def resolve(self, name, version, max_id): """Resolves the table for a given name and version. Args: name (unicode): The name of the table to resolve. version (int): The version of the table to resolve. max_id (Optional[int]): The maximum ID of the table requested. May be ``None`` in which case an exact match on ``name`` and ``version`` is required. Returns: SymbolTable: The *closest* matching symbol table. This is either an exact match, a placeholder, or a derived substitute depending on what tables are registered. """ 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: %s' % version) if max_id is not None and max_id < 0: raise ValueError('Max ID must be zero or positive: %s' % max_id) versions = self.__tables.get(name) if versions is None: if max_id is None: raise CannotSubstituteTable( 'Found no table for %s, but no max_id' % name ) return placeholder_symbol_table(name, version, max_id) table = versions.get(version) if table is None: # TODO Replace the keys map with a search tree based dictionary. keys = list(versions) keys.sort() table = versions[keys[-1]] if table.version == version and (max_id is None or table.max_id == max_id): return table if max_id is None: raise CannotSubstituteTable( 'Found match for %s, but not version %d, and no max_id' % (name, version) ) return substitute_symbol_table(table, version, max_id)
[ "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: %s'", "%", "version", ")", "if", "max_id", "is", "not", "None", "and", "max_id", "<", "0", ":", "raise", "ValueError", "(", "'Max ID must be zero or positive: %s'", "%", "max_id", ")", "versions", "=", "self", ".", "__tables", ".", "get", "(", "name", ")", "if", "versions", "is", "None", ":", "if", "max_id", "is", "None", ":", "raise", "CannotSubstituteTable", "(", "'Found no table for %s, but no max_id'", "%", "name", ")", "return", "placeholder_symbol_table", "(", "name", ",", "version", ",", "max_id", ")", "table", "=", "versions", ".", "get", "(", "version", ")", "if", "table", "is", "None", ":", "# TODO Replace the keys map with a search tree based dictionary.", "keys", "=", "list", "(", "versions", ")", "keys", ".", "sort", "(", ")", "table", "=", "versions", "[", "keys", "[", "-", "1", "]", "]", "if", "table", ".", "version", "==", "version", "and", "(", "max_id", "is", "None", "or", "table", ".", "max_id", "==", "max_id", ")", ":", "return", "table", "if", "max_id", "is", "None", ":", "raise", "CannotSubstituteTable", "(", "'Found match for %s, but not version %d, and no max_id'", "%", "(", "name", ",", "version", ")", ")", "return", "substitute_symbol_table", "(", "table", ",", "version", ",", "max_id", ")" ]
Resolves the table for a given name and version. Args: name (unicode): The name of the table to resolve. version (int): The version of the table to resolve. max_id (Optional[int]): The maximum ID of the table requested. May be ``None`` in which case an exact match on ``name`` and ``version`` is required. Returns: SymbolTable: The *closest* matching symbol table. This is either an exact match, a placeholder, or a derived substitute depending on what tables are registered.
[ "Resolves", "the", "table", "for", "a", "given", "name", "and", "version", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L518-L564
train
233,765
amzn/ion-python
amazon/ion/writer_buffer.py
BufferTree.start_container
def start_container(self): """Add a node to the tree that represents the start of a container. Until end_container is called, any nodes added through add_scalar_value or start_container will be children of this new node. """ 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_container_node
python
def start_container(self): """Add a node to the tree that represents the start of a container. Until end_container is called, any nodes added through add_scalar_value or start_container will be children of this new node. """ 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_container_node
[ "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_container_node" ]
Add a node to the tree that represents the start of a container. Until end_container is called, any nodes added through add_scalar_value or start_container will be children of this new node.
[ "Add", "a", "node", "to", "the", "tree", "that", "represents", "the", "start", "of", "a", "container", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/writer_buffer.py#L91-L102
train
233,766
amzn/ion-python
amazon/ion/writer_buffer.py
BufferTree.end_container
def end_container(self, header_buf): """Add a node containing the container's header to the current subtree. This node will be added as the leftmost leaf of the subtree that was started by the matching call to start_container. Args: header_buf (bytearray): bytearray containing the container header. """ if not self.__container_nodes: raise ValueError("Attempted to end container with none active.") # Header needs to be the first node visited on this subtree. self.__container_node.add_leaf(_Node(header_buf)) self.__container_node = self.__container_nodes.pop() parent_container_length = self.__container_lengths.pop() self.current_container_length = \ parent_container_length + self.current_container_length + len(header_buf)
python
def end_container(self, header_buf): """Add a node containing the container's header to the current subtree. This node will be added as the leftmost leaf of the subtree that was started by the matching call to start_container. Args: header_buf (bytearray): bytearray containing the container header. """ if not self.__container_nodes: raise ValueError("Attempted to end container with none active.") # Header needs to be the first node visited on this subtree. self.__container_node.add_leaf(_Node(header_buf)) self.__container_node = self.__container_nodes.pop() parent_container_length = self.__container_lengths.pop() self.current_container_length = \ parent_container_length + self.current_container_length + len(header_buf)
[ "def", "end_container", "(", "self", ",", "header_buf", ")", ":", "if", "not", "self", ".", "__container_nodes", ":", "raise", "ValueError", "(", "\"Attempted to end container with none active.\"", ")", "# Header needs to be the first node visited on this subtree.", "self", ".", "__container_node", ".", "add_leaf", "(", "_Node", "(", "header_buf", ")", ")", "self", ".", "__container_node", "=", "self", ".", "__container_nodes", ".", "pop", "(", ")", "parent_container_length", "=", "self", ".", "__container_lengths", ".", "pop", "(", ")", "self", ".", "current_container_length", "=", "parent_container_length", "+", "self", ".", "current_container_length", "+", "len", "(", "header_buf", ")" ]
Add a node containing the container's header to the current subtree. This node will be added as the leftmost leaf of the subtree that was started by the matching call to start_container. Args: header_buf (bytearray): bytearray containing the container header.
[ "Add", "a", "node", "containing", "the", "container", "s", "header", "to", "the", "current", "subtree", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/writer_buffer.py#L104-L120
train
233,767
amzn/ion-python
amazon/ion/writer_buffer.py
BufferTree.add_scalar_value
def add_scalar_value(self, value_buf): """Add a node to the tree containing a scalar value. Args: value_buf (bytearray): bytearray containing the scalar value. """ self.__container_node.add_child(_Node(value_buf)) self.current_container_length += len(value_buf)
python
def add_scalar_value(self, value_buf): """Add a node to the tree containing a scalar value. Args: value_buf (bytearray): bytearray containing the scalar value. """ self.__container_node.add_child(_Node(value_buf)) self.current_container_length += len(value_buf)
[ "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. Args: value_buf (bytearray): bytearray containing the scalar value.
[ "Add", "a", "node", "to", "the", "tree", "containing", "a", "scalar", "value", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/writer_buffer.py#L122-L129
train
233,768
amzn/ion-python
amazon/ion/writer_buffer.py
BufferTree.drain
def drain(self): """Walk the BufferTree and reset it when finished. Yields: any: The current node's value. """ 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()
python
def drain(self): """Walk the BufferTree and reset it when finished. Yields: any: The current node's value. """ 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()
[ "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. Yields: any: The current node's value.
[ "Walk", "the", "BufferTree", "and", "reset", "it", "when", "finished", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/writer_buffer.py#L131-L142
train
233,769
amzn/ion-python
amazon/ion/equivalence.py
ion_equals
def ion_equals(a, b, timestamps_instants_only=False): """Tests two objects for equivalence under the Ion data model. There are three important cases: * When neither operand specifies its `ion_type` or `annotations`, this method will only return True when the values of both operands are equivalent under the Ion data model. * When only one of the operands specifies its `ion_type` and `annotations`, this method will only return True when that operand has no annotations and has a value equivalent to the other operand under the Ion data model. * When both operands specify `ion_type` and `annotations`, this method will only return True when the ion_type and annotations of both are the same and their values are equivalent under the Ion data model. Note that the order of the operands does not matter. Args: a (object): The first operand. b (object): The second operand. timestamps_instants_only (Optional[bool]): False if timestamp objects (datetime and its subclasses) should be compared according to the Ion data model (where the instant, precision, and offset must be equal); True if these objects should be considered equivalent if they simply represent the same instant. """ if timestamps_instants_only: return _ion_equals_timestamps_instants(a, b) return _ion_equals_timestamps_data_model(a, b)
python
def ion_equals(a, b, timestamps_instants_only=False): """Tests two objects for equivalence under the Ion data model. There are three important cases: * When neither operand specifies its `ion_type` or `annotations`, this method will only return True when the values of both operands are equivalent under the Ion data model. * When only one of the operands specifies its `ion_type` and `annotations`, this method will only return True when that operand has no annotations and has a value equivalent to the other operand under the Ion data model. * When both operands specify `ion_type` and `annotations`, this method will only return True when the ion_type and annotations of both are the same and their values are equivalent under the Ion data model. Note that the order of the operands does not matter. Args: a (object): The first operand. b (object): The second operand. timestamps_instants_only (Optional[bool]): False if timestamp objects (datetime and its subclasses) should be compared according to the Ion data model (where the instant, precision, and offset must be equal); True if these objects should be considered equivalent if they simply represent the same instant. """ if timestamps_instants_only: return _ion_equals_timestamps_instants(a, b) return _ion_equals_timestamps_data_model(a, b)
[ "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. There are three important cases: * When neither operand specifies its `ion_type` or `annotations`, this method will only return True when the values of both operands are equivalent under the Ion data model. * When only one of the operands specifies its `ion_type` and `annotations`, this method will only return True when that operand has no annotations and has a value equivalent to the other operand under the Ion data model. * When both operands specify `ion_type` and `annotations`, this method will only return True when the ion_type and annotations of both are the same and their values are equivalent under the Ion data model. Note that the order of the operands does not matter. Args: a (object): The first operand. b (object): The second operand. timestamps_instants_only (Optional[bool]): False if timestamp objects (datetime and its subclasses) should be compared according to the Ion data model (where the instant, precision, and offset must be equal); True if these objects should be considered equivalent if they simply represent the same instant.
[ "Tests", "two", "objects", "for", "equivalence", "under", "the", "Ion", "data", "model", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/equivalence.py#L35-L57
train
233,770
amzn/ion-python
amazon/ion/equivalence.py
_ion_equals
def _ion_equals(a, b, timestamp_comparison_func, recursive_comparison_func): """Compares a and b according to the description of the ion_equals method.""" for a, b in ((a, b), (b, a)): # Ensures that operand order does not matter. if isinstance(a, _IonNature): if isinstance(b, _IonNature): # Both operands have _IonNature. Their IonTypes and annotations must be equivalent. eq = a.ion_type is b.ion_type and _annotations_eq(a, b) else: # Only one operand has _IonNature. It cannot be equivalent to the other operand if it has annotations. eq = not a.ion_annotations if eq: if isinstance(a, IonPyList): return _sequences_eq(a, b, recursive_comparison_func) elif isinstance(a, IonPyDict): return _structs_eq(a, b, recursive_comparison_func) elif isinstance(a, IonPyTimestamp): return timestamp_comparison_func(a, b) elif isinstance(a, IonPyNull): return isinstance(b, IonPyNull) or (b is None and a.ion_type is IonType.NULL) elif isinstance(a, IonPySymbol) or (isinstance(a, IonPyText) and a.ion_type is IonType.SYMBOL): return _symbols_eq(a, b) elif isinstance(a, IonPyDecimal): return _decimals_eq(a, b) elif isinstance(a, IonPyFloat): return _floats_eq(a, b) else: return a == b return False # Reaching this point means that neither operand has _IonNature. for a, b in ((a, b), (b, a)): # Ensures that operand order does not matter. if isinstance(a, list): return _sequences_eq(a, b, recursive_comparison_func) elif isinstance(a, dict): return _structs_eq(a, b, recursive_comparison_func) elif isinstance(a, datetime): return timestamp_comparison_func(a, b) elif isinstance(a, SymbolToken): return _symbols_eq(a, b) elif isinstance(a, Decimal): return _decimals_eq(a, b) elif isinstance(a, float): return _floats_eq(a, b) return a == b
python
def _ion_equals(a, b, timestamp_comparison_func, recursive_comparison_func): """Compares a and b according to the description of the ion_equals method.""" for a, b in ((a, b), (b, a)): # Ensures that operand order does not matter. if isinstance(a, _IonNature): if isinstance(b, _IonNature): # Both operands have _IonNature. Their IonTypes and annotations must be equivalent. eq = a.ion_type is b.ion_type and _annotations_eq(a, b) else: # Only one operand has _IonNature. It cannot be equivalent to the other operand if it has annotations. eq = not a.ion_annotations if eq: if isinstance(a, IonPyList): return _sequences_eq(a, b, recursive_comparison_func) elif isinstance(a, IonPyDict): return _structs_eq(a, b, recursive_comparison_func) elif isinstance(a, IonPyTimestamp): return timestamp_comparison_func(a, b) elif isinstance(a, IonPyNull): return isinstance(b, IonPyNull) or (b is None and a.ion_type is IonType.NULL) elif isinstance(a, IonPySymbol) or (isinstance(a, IonPyText) and a.ion_type is IonType.SYMBOL): return _symbols_eq(a, b) elif isinstance(a, IonPyDecimal): return _decimals_eq(a, b) elif isinstance(a, IonPyFloat): return _floats_eq(a, b) else: return a == b return False # Reaching this point means that neither operand has _IonNature. for a, b in ((a, b), (b, a)): # Ensures that operand order does not matter. if isinstance(a, list): return _sequences_eq(a, b, recursive_comparison_func) elif isinstance(a, dict): return _structs_eq(a, b, recursive_comparison_func) elif isinstance(a, datetime): return timestamp_comparison_func(a, b) elif isinstance(a, SymbolToken): return _symbols_eq(a, b) elif isinstance(a, Decimal): return _decimals_eq(a, b) elif isinstance(a, float): return _floats_eq(a, b) return a == b
[ "def", "_ion_equals", "(", "a", ",", "b", ",", "timestamp_comparison_func", ",", "recursive_comparison_func", ")", ":", "for", "a", ",", "b", "in", "(", "(", "a", ",", "b", ")", ",", "(", "b", ",", "a", ")", ")", ":", "# Ensures that operand order does not matter.", "if", "isinstance", "(", "a", ",", "_IonNature", ")", ":", "if", "isinstance", "(", "b", ",", "_IonNature", ")", ":", "# Both operands have _IonNature. Their IonTypes and annotations must be equivalent.", "eq", "=", "a", ".", "ion_type", "is", "b", ".", "ion_type", "and", "_annotations_eq", "(", "a", ",", "b", ")", "else", ":", "# Only one operand has _IonNature. It cannot be equivalent to the other operand if it has annotations.", "eq", "=", "not", "a", ".", "ion_annotations", "if", "eq", ":", "if", "isinstance", "(", "a", ",", "IonPyList", ")", ":", "return", "_sequences_eq", "(", "a", ",", "b", ",", "recursive_comparison_func", ")", "elif", "isinstance", "(", "a", ",", "IonPyDict", ")", ":", "return", "_structs_eq", "(", "a", ",", "b", ",", "recursive_comparison_func", ")", "elif", "isinstance", "(", "a", ",", "IonPyTimestamp", ")", ":", "return", "timestamp_comparison_func", "(", "a", ",", "b", ")", "elif", "isinstance", "(", "a", ",", "IonPyNull", ")", ":", "return", "isinstance", "(", "b", ",", "IonPyNull", ")", "or", "(", "b", "is", "None", "and", "a", ".", "ion_type", "is", "IonType", ".", "NULL", ")", "elif", "isinstance", "(", "a", ",", "IonPySymbol", ")", "or", "(", "isinstance", "(", "a", ",", "IonPyText", ")", "and", "a", ".", "ion_type", "is", "IonType", ".", "SYMBOL", ")", ":", "return", "_symbols_eq", "(", "a", ",", "b", ")", "elif", "isinstance", "(", "a", ",", "IonPyDecimal", ")", ":", "return", "_decimals_eq", "(", "a", ",", "b", ")", "elif", "isinstance", "(", "a", ",", "IonPyFloat", ")", ":", "return", "_floats_eq", "(", "a", ",", "b", ")", "else", ":", "return", "a", "==", "b", "return", "False", "# Reaching this point means that neither operand has _IonNature.", "for", "a", ",", "b", "in", "(", "(", "a", ",", "b", ")", ",", "(", "b", ",", "a", ")", ")", ":", "# Ensures that operand order does not matter.", "if", "isinstance", "(", "a", ",", "list", ")", ":", "return", "_sequences_eq", "(", "a", ",", "b", ",", "recursive_comparison_func", ")", "elif", "isinstance", "(", "a", ",", "dict", ")", ":", "return", "_structs_eq", "(", "a", ",", "b", ",", "recursive_comparison_func", ")", "elif", "isinstance", "(", "a", ",", "datetime", ")", ":", "return", "timestamp_comparison_func", "(", "a", ",", "b", ")", "elif", "isinstance", "(", "a", ",", "SymbolToken", ")", ":", "return", "_symbols_eq", "(", "a", ",", "b", ")", "elif", "isinstance", "(", "a", ",", "Decimal", ")", ":", "return", "_decimals_eq", "(", "a", ",", "b", ")", "elif", "isinstance", "(", "a", ",", "float", ")", ":", "return", "_floats_eq", "(", "a", ",", "b", ")", "return", "a", "==", "b" ]
Compares a and b according to the description of the ion_equals method.
[ "Compares", "a", "and", "b", "according", "to", "the", "description", "of", "the", "ion_equals", "method", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/equivalence.py#L68-L110
train
233,771
amzn/ion-python
amazon/ion/equivalence.py
_timestamps_eq
def _timestamps_eq(a, b): """Compares two timestamp operands for equivalence under the Ion data model.""" assert isinstance(a, datetime) if not isinstance(b, datetime): return False # Local offsets must be equivalent. 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 isinstance(b, Timestamp): # Both operands declare their precisions. They are only equivalent if their precisions are the same. if a.precision is b.precision and a.fractional_precision is b.fractional_precision: break return False elif a.precision is not TimestampPrecision.SECOND or a.fractional_precision != MICROSECOND_PRECISION: # Only one of the operands declares its precision. It is only equivalent to the other (a naive datetime) # if it has full microseconds precision. return False return a == b
python
def _timestamps_eq(a, b): """Compares two timestamp operands for equivalence under the Ion data model.""" assert isinstance(a, datetime) if not isinstance(b, datetime): return False # Local offsets must be equivalent. 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 isinstance(b, Timestamp): # Both operands declare their precisions. They are only equivalent if their precisions are the same. if a.precision is b.precision and a.fractional_precision is b.fractional_precision: break return False elif a.precision is not TimestampPrecision.SECOND or a.fractional_precision != MICROSECOND_PRECISION: # Only one of the operands declares its precision. It is only equivalent to the other (a naive datetime) # if it has full microseconds precision. return False return a == b
[ "def", "_timestamps_eq", "(", "a", ",", "b", ")", ":", "assert", "isinstance", "(", "a", ",", "datetime", ")", "if", "not", "isinstance", "(", "b", ",", "datetime", ")", ":", "return", "False", "# Local offsets must be equivalent.", "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", "isinstance", "(", "b", ",", "Timestamp", ")", ":", "# Both operands declare their precisions. They are only equivalent if their precisions are the same.", "if", "a", ".", "precision", "is", "b", ".", "precision", "and", "a", ".", "fractional_precision", "is", "b", ".", "fractional_precision", ":", "break", "return", "False", "elif", "a", ".", "precision", "is", "not", "TimestampPrecision", ".", "SECOND", "or", "a", ".", "fractional_precision", "!=", "MICROSECOND_PRECISION", ":", "# Only one of the operands declares its precision. It is only equivalent to the other (a naive datetime)", "# if it has full microseconds precision.", "return", "False", "return", "a", "==", "b" ]
Compares two timestamp operands for equivalence under the Ion data model.
[ "Compares", "two", "timestamp", "operands", "for", "equivalence", "under", "the", "Ion", "data", "model", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/equivalence.py#L161-L182
train
233,772
amzn/ion-python
amazon/ion/equivalence.py
_timestamp_instants_eq
def _timestamp_instants_eq(a, b): """Compares two timestamp operands for point-in-time equivalence only.""" assert isinstance(a, datetime) if not isinstance(b, datetime): return False # datetime's __eq__ can't compare a None offset and a non-None offset. For these equivalence semantics, a None # offset (unknown local offset) is treated equivalently to a +00:00. if a.tzinfo is None: a = a.replace(tzinfo=OffsetTZInfo()) if b.tzinfo is None: b = b.replace(tzinfo=OffsetTZInfo()) # datetime's __eq__ implementation compares instants; offsets and precision need not be equal. return a == b
python
def _timestamp_instants_eq(a, b): """Compares two timestamp operands for point-in-time equivalence only.""" assert isinstance(a, datetime) if not isinstance(b, datetime): return False # datetime's __eq__ can't compare a None offset and a non-None offset. For these equivalence semantics, a None # offset (unknown local offset) is treated equivalently to a +00:00. if a.tzinfo is None: a = a.replace(tzinfo=OffsetTZInfo()) if b.tzinfo is None: b = b.replace(tzinfo=OffsetTZInfo()) # datetime's __eq__ implementation compares instants; offsets and precision need not be equal. return a == b
[ "def", "_timestamp_instants_eq", "(", "a", ",", "b", ")", ":", "assert", "isinstance", "(", "a", ",", "datetime", ")", "if", "not", "isinstance", "(", "b", ",", "datetime", ")", ":", "return", "False", "# datetime's __eq__ can't compare a None offset and a non-None offset. For these equivalence semantics, a None", "# offset (unknown local offset) is treated equivalently to a +00:00.", "if", "a", ".", "tzinfo", "is", "None", ":", "a", "=", "a", ".", "replace", "(", "tzinfo", "=", "OffsetTZInfo", "(", ")", ")", "if", "b", ".", "tzinfo", "is", "None", ":", "b", "=", "b", ".", "replace", "(", "tzinfo", "=", "OffsetTZInfo", "(", ")", ")", "# datetime's __eq__ implementation compares instants; offsets and precision need not be equal.", "return", "a", "==", "b" ]
Compares two timestamp operands for point-in-time equivalence only.
[ "Compares", "two", "timestamp", "operands", "for", "point", "-", "in", "-", "time", "equivalence", "only", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/equivalence.py#L185-L197
train
233,773
amzn/ion-python
amazon/ion/reader_binary.py
_parse_var_int_components
def _parse_var_int_components(buf, signed): """Parses a ``VarInt`` or ``VarUInt`` field from a file-like object.""" 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_INT_VALUE_BITS value |= octet & _VAR_INT_VALUE_MASK if octet & _VAR_INT_SIGNAL_MASK: break return sign, value
python
def _parse_var_int_components(buf, signed): """Parses a ``VarInt`` or ``VarUInt`` field from a file-like object.""" 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_INT_VALUE_BITS value |= octet & _VAR_INT_VALUE_MASK if octet & _VAR_INT_SIGNAL_MASK: break return sign, value
[ "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_INT_VALUE_BITS", "value", "|=", "octet", "&", "_VAR_INT_VALUE_MASK", "if", "octet", "&", "_VAR_INT_SIGNAL_MASK", ":", "break", "return", "sign", ",", "value" ]
Parses a ``VarInt`` or ``VarUInt`` field from a file-like object.
[ "Parses", "a", "VarInt", "or", "VarUInt", "field", "from", "a", "file", "-", "like", "object", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L132-L152
train
233,774
amzn/ion-python
amazon/ion/reader_binary.py
_parse_signed_int_components
def _parse_signed_int_components(buf): """Parses the remainder of a file-like object as a signed magnitude value. Returns: Returns a pair of the sign bit and the unsigned magnitude. """ 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, value
python
def _parse_signed_int_components(buf): """Parses the remainder of a file-like object as a signed magnitude value. Returns: Returns a pair of the sign bit and the unsigned magnitude. """ 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, value
[ "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", ",", "value" ]
Parses the remainder of a file-like object as a signed magnitude value. Returns: Returns a pair of the sign bit and the unsigned magnitude.
[ "Parses", "the", "remainder", "of", "a", "file", "-", "like", "object", "as", "a", "signed", "magnitude", "value", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L160-L184
train
233,775
amzn/ion-python
amazon/ion/reader_binary.py
_parse_decimal
def _parse_decimal(buf): """Parses the remainder of a file-like object as a decimal.""" exponent = _parse_var_int(buf, signed=True) sign_bit, coefficient = _parse_signed_int_components(buf) if coefficient == 0: # Handle the zero cases--especially negative zero value = Decimal((sign_bit, (0,), exponent)) else: coefficient *= sign_bit and -1 or 1 value = Decimal(coefficient).scaleb(exponent) return value
python
def _parse_decimal(buf): """Parses the remainder of a file-like object as a decimal.""" exponent = _parse_var_int(buf, signed=True) sign_bit, coefficient = _parse_signed_int_components(buf) if coefficient == 0: # Handle the zero cases--especially negative zero value = Decimal((sign_bit, (0,), exponent)) else: coefficient *= sign_bit and -1 or 1 value = Decimal(coefficient).scaleb(exponent) return value
[ "def", "_parse_decimal", "(", "buf", ")", ":", "exponent", "=", "_parse_var_int", "(", "buf", ",", "signed", "=", "True", ")", "sign_bit", ",", "coefficient", "=", "_parse_signed_int_components", "(", "buf", ")", "if", "coefficient", "==", "0", ":", "# Handle the zero cases--especially negative zero", "value", "=", "Decimal", "(", "(", "sign_bit", ",", "(", "0", ",", ")", ",", "exponent", ")", ")", "else", ":", "coefficient", "*=", "sign_bit", "and", "-", "1", "or", "1", "value", "=", "Decimal", "(", "coefficient", ")", ".", "scaleb", "(", "exponent", ")", "return", "value" ]
Parses the remainder of a file-like object as a decimal.
[ "Parses", "the", "remainder", "of", "a", "file", "-", "like", "object", "as", "a", "decimal", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L187-L199
train
233,776
amzn/ion-python
amazon/ion/reader_binary.py
_create_delegate_handler
def _create_delegate_handler(delegate): """Creates a handler function that creates a co-routine that can yield once with the given positional arguments to the delegate as a transition. Args: delegate (Coroutine): The co-routine to delegate to. Returns: A :class:`callable` handler that returns a co-routine that ignores the data it receives and sends with the arguments given to the handler as a :class:`Transition`. """ @coroutine def handler(*args): yield yield delegate.send(Transition(args, delegate)) return handler
python
def _create_delegate_handler(delegate): """Creates a handler function that creates a co-routine that can yield once with the given positional arguments to the delegate as a transition. Args: delegate (Coroutine): The co-routine to delegate to. Returns: A :class:`callable` handler that returns a co-routine that ignores the data it receives and sends with the arguments given to the handler as a :class:`Transition`. """ @coroutine def handler(*args): yield yield delegate.send(Transition(args, delegate)) return handler
[ "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. Args: delegate (Coroutine): The co-routine to delegate to. Returns: A :class:`callable` handler that returns a co-routine that ignores the data it receives and sends with the arguments given to the handler as a :class:`Transition`.
[ "Creates", "a", "handler", "function", "that", "creates", "a", "co", "-", "routine", "that", "can", "yield", "once", "with", "the", "given", "positional", "arguments", "to", "the", "delegate", "as", "a", "transition", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L314-L330
train
233,777
amzn/ion-python
amazon/ion/reader_binary.py
_var_uint_field_handler
def _var_uint_field_handler(handler, ctx): """Handler co-routine for variable unsigned integer fields that. Invokes the given ``handler`` function with the read field and context, then immediately yields to the resulting co-routine. """ _, self = yield queue = ctx.queue value = 0 while True: if len(queue) == 0: # We don't know when the field ends, so read at least one byte. 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 ctx.immediate_transition(handler(value, ctx))
python
def _var_uint_field_handler(handler, ctx): """Handler co-routine for variable unsigned integer fields that. Invokes the given ``handler`` function with the read field and context, then immediately yields to the resulting co-routine. """ _, self = yield queue = ctx.queue value = 0 while True: if len(queue) == 0: # We don't know when the field ends, so read at least one byte. 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 ctx.immediate_transition(handler(value, ctx))
[ "def", "_var_uint_field_handler", "(", "handler", ",", "ctx", ")", ":", "_", ",", "self", "=", "yield", "queue", "=", "ctx", ".", "queue", "value", "=", "0", "while", "True", ":", "if", "len", "(", "queue", ")", "==", "0", ":", "# We don't know when the field ends, so read at least one byte.", "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", "ctx", ".", "immediate_transition", "(", "handler", "(", "value", ",", "ctx", ")", ")" ]
Handler co-routine for variable unsigned integer fields that. Invokes the given ``handler`` function with the read field and context, then immediately yields to the resulting co-routine.
[ "Handler", "co", "-", "routine", "for", "variable", "unsigned", "integer", "fields", "that", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L398-L416
train
233,778
amzn/ion-python
amazon/ion/reader_binary.py
_length_scalar_handler
def _length_scalar_handler(scalar_factory, ion_type, length, ctx): """Handles scalars, ``scalar_factory`` is a function that returns a value or thunk.""" _, 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): # TODO Wrap the exception to get context position. event_cls = IonThunkEvent yield ctx.event_transition(event_cls, IonEventType.SCALAR, ion_type, scalar)
python
def _length_scalar_handler(scalar_factory, ion_type, length, ctx): """Handles scalars, ``scalar_factory`` is a function that returns a value or thunk.""" _, 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): # TODO Wrap the exception to get context position. event_cls = IonThunkEvent yield ctx.event_transition(event_cls, IonEventType.SCALAR, ion_type, scalar)
[ "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", ")", ":", "# TODO Wrap the exception to get context position.", "event_cls", "=", "IonThunkEvent", "yield", "ctx", ".", "event_transition", "(", "event_cls", ",", "IonEventType", ".", "SCALAR", ",", "ion_type", ",", "scalar", ")" ]
Handles scalars, ``scalar_factory`` is a function that returns a value or thunk.
[ "Handles", "scalars", "scalar_factory", "is", "a", "function", "that", "returns", "a", "value", "or", "thunk", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L455-L469
train
233,779
amzn/ion-python
amazon/ion/reader_binary.py
_annotation_handler
def _annotation_handler(ion_type, length, ctx): """Handles annotations. ``ion_type`` is ignored.""" _, self = yield self_handler = _create_delegate_handler(self) if ctx.annotations is not None: raise IonException('Annotation cannot be nested in annotations') # We have to replace our context for annotations specifically to encapsulate the limit ctx = ctx.derive_container_context(length, add_depth=0) # Immediately read the length field and the annotations (ann_length, _), _ = yield ctx.immediate_transition( _var_uint_field_handler(self_handler, ctx) ) if ann_length < 1: raise IonException('Invalid annotation length subfield; annotation wrapper must have at least one annotation.') # Read/parse the annotations. yield ctx.read_data_transition(ann_length, self) ann_data = ctx.queue.read(ann_length) annotations = tuple(_parse_sid_iter(ann_data)) if ctx.limit - ctx.queue.position < 1: # There is no space left for the 'value' subfield, which is required. raise IonException('Incorrect annotation wrapper length.') # Go parse the start of the value but go back to the real parent container. yield ctx.immediate_transition( _start_type_handler(ctx.field_name, ctx.whence, ctx, annotations=annotations) )
python
def _annotation_handler(ion_type, length, ctx): """Handles annotations. ``ion_type`` is ignored.""" _, self = yield self_handler = _create_delegate_handler(self) if ctx.annotations is not None: raise IonException('Annotation cannot be nested in annotations') # We have to replace our context for annotations specifically to encapsulate the limit ctx = ctx.derive_container_context(length, add_depth=0) # Immediately read the length field and the annotations (ann_length, _), _ = yield ctx.immediate_transition( _var_uint_field_handler(self_handler, ctx) ) if ann_length < 1: raise IonException('Invalid annotation length subfield; annotation wrapper must have at least one annotation.') # Read/parse the annotations. yield ctx.read_data_transition(ann_length, self) ann_data = ctx.queue.read(ann_length) annotations = tuple(_parse_sid_iter(ann_data)) if ctx.limit - ctx.queue.position < 1: # There is no space left for the 'value' subfield, which is required. raise IonException('Incorrect annotation wrapper length.') # Go parse the start of the value but go back to the real parent container. yield ctx.immediate_transition( _start_type_handler(ctx.field_name, ctx.whence, ctx, annotations=annotations) )
[ "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'", ")", "# We have to replace our context for annotations specifically to encapsulate the limit", "ctx", "=", "ctx", ".", "derive_container_context", "(", "length", ",", "add_depth", "=", "0", ")", "# Immediately read the length field and the annotations", "(", "ann_length", ",", "_", ")", ",", "_", "=", "yield", "ctx", ".", "immediate_transition", "(", "_var_uint_field_handler", "(", "self_handler", ",", "ctx", ")", ")", "if", "ann_length", "<", "1", ":", "raise", "IonException", "(", "'Invalid annotation length subfield; annotation wrapper must have at least one annotation.'", ")", "# Read/parse the annotations.", "yield", "ctx", ".", "read_data_transition", "(", "ann_length", ",", "self", ")", "ann_data", "=", "ctx", ".", "queue", ".", "read", "(", "ann_length", ")", "annotations", "=", "tuple", "(", "_parse_sid_iter", "(", "ann_data", ")", ")", "if", "ctx", ".", "limit", "-", "ctx", ".", "queue", ".", "position", "<", "1", ":", "# There is no space left for the 'value' subfield, which is required.", "raise", "IonException", "(", "'Incorrect annotation wrapper length.'", ")", "# Go parse the start of the value but go back to the real parent container.", "yield", "ctx", ".", "immediate_transition", "(", "_start_type_handler", "(", "ctx", ".", "field_name", ",", "ctx", ".", "whence", ",", "ctx", ",", "annotations", "=", "annotations", ")", ")" ]
Handles annotations. ``ion_type`` is ignored.
[ "Handles", "annotations", ".", "ion_type", "is", "ignored", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L496-L526
train
233,780
amzn/ion-python
amazon/ion/reader_binary.py
_ordered_struct_start_handler
def _ordered_struct_start_handler(handler, ctx): """Handles the special case of ordered structs, specified by the type ID 0xD1. This coroutine's only purpose is to ensure that the struct in question declares at least one field name/value pair, as required by the spec. """ _, self = yield self_handler = _create_delegate_handler(self) (length, _), _ = yield ctx.immediate_transition( _var_uint_field_handler(self_handler, ctx) ) if length < 2: # A valid field name/value pair is at least two octets: one for the field name SID and one for the value. raise IonException('Ordered structs (type ID 0xD1) must have at least one field name/value pair.') yield ctx.immediate_transition(handler(length, ctx))
python
def _ordered_struct_start_handler(handler, ctx): """Handles the special case of ordered structs, specified by the type ID 0xD1. This coroutine's only purpose is to ensure that the struct in question declares at least one field name/value pair, as required by the spec. """ _, self = yield self_handler = _create_delegate_handler(self) (length, _), _ = yield ctx.immediate_transition( _var_uint_field_handler(self_handler, ctx) ) if length < 2: # A valid field name/value pair is at least two octets: one for the field name SID and one for the value. raise IonException('Ordered structs (type ID 0xD1) must have at least one field name/value pair.') yield ctx.immediate_transition(handler(length, ctx))
[ "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", ":", "# A valid field name/value pair is at least two octets: one for the field name SID and one for the value.", "raise", "IonException", "(", "'Ordered structs (type ID 0xD1) must have at least one field name/value pair.'", ")", "yield", "ctx", ".", "immediate_transition", "(", "handler", "(", "length", ",", "ctx", ")", ")" ]
Handles the special case of ordered structs, specified by the type ID 0xD1. This coroutine's only purpose is to ensure that the struct in question declares at least one field name/value pair, as required by the spec.
[ "Handles", "the", "special", "case", "of", "ordered", "structs", "specified", "by", "the", "type", "ID", "0xD1", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L530-L544
train
233,781
amzn/ion-python
amazon/ion/reader_binary.py
_container_start_handler
def _container_start_handler(ion_type, length, ctx): """Handles container delegation.""" _, self = yield container_ctx = ctx.derive_container_context(length) if ctx.annotations and ctx.limit != container_ctx.limit: # 'ctx' is the annotation wrapper context. `container_ctx` represents the wrapper's 'value' subfield. Their # limits must match. raise IonException('Incorrect annotation wrapper length.') delegate = _container_handler(ion_type, container_ctx) # We start the container, and transition to the new container processor. yield ctx.event_transition( IonEvent, IonEventType.CONTAINER_START, ion_type, value=None, whence=delegate )
python
def _container_start_handler(ion_type, length, ctx): """Handles container delegation.""" _, self = yield container_ctx = ctx.derive_container_context(length) if ctx.annotations and ctx.limit != container_ctx.limit: # 'ctx' is the annotation wrapper context. `container_ctx` represents the wrapper's 'value' subfield. Their # limits must match. raise IonException('Incorrect annotation wrapper length.') delegate = _container_handler(ion_type, container_ctx) # We start the container, and transition to the new container processor. yield ctx.event_transition( IonEvent, IonEventType.CONTAINER_START, ion_type, value=None, whence=delegate )
[ "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", ":", "# 'ctx' is the annotation wrapper context. `container_ctx` represents the wrapper's 'value' subfield. Their", "# limits must match.", "raise", "IonException", "(", "'Incorrect annotation wrapper length.'", ")", "delegate", "=", "_container_handler", "(", "ion_type", ",", "container_ctx", ")", "# We start the container, and transition to the new container processor.", "yield", "ctx", ".", "event_transition", "(", "IonEvent", ",", "IonEventType", ".", "CONTAINER_START", ",", "ion_type", ",", "value", "=", "None", ",", "whence", "=", "delegate", ")" ]
Handles container delegation.
[ "Handles", "container", "delegation", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L548-L562
train
233,782
amzn/ion-python
amazon/ion/reader_binary.py
_bind_length_handlers
def _bind_length_handlers(tids, user_handler, lns): """Binds a set of handlers with the given factory. Args: tids (Sequence[int]): The Type IDs to bind to. user_handler (Callable): A function that takes as its parameters :class:`IonType`, ``length``, and the ``ctx`` context returning a co-routine. lns (Sequence[int]): The low-nibble lengths to bind to. """ 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 < _LENGTH_FIELD_FOLLOWS: # Directly partially bind length. handler = partial(user_handler, ion_type, ln) else: # Delegate to length field parsing first. handler = partial(_var_uint_field_handler, partial(user_handler, ion_type)) _HANDLER_DISPATCH_TABLE[type_octet] = handler
python
def _bind_length_handlers(tids, user_handler, lns): """Binds a set of handlers with the given factory. Args: tids (Sequence[int]): The Type IDs to bind to. user_handler (Callable): A function that takes as its parameters :class:`IonType`, ``length``, and the ``ctx`` context returning a co-routine. lns (Sequence[int]): The low-nibble lengths to bind to. """ 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 < _LENGTH_FIELD_FOLLOWS: # Directly partially bind length. handler = partial(user_handler, ion_type, ln) else: # Delegate to length field parsing first. handler = partial(_var_uint_field_handler, partial(user_handler, ion_type)) _HANDLER_DISPATCH_TABLE[type_octet] = handler
[ "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", "<", "_LENGTH_FIELD_FOLLOWS", ":", "# Directly partially bind length.", "handler", "=", "partial", "(", "user_handler", ",", "ion_type", ",", "ln", ")", "else", ":", "# Delegate to length field parsing first.", "handler", "=", "partial", "(", "_var_uint_field_handler", ",", "partial", "(", "user_handler", ",", "ion_type", ")", ")", "_HANDLER_DISPATCH_TABLE", "[", "type_octet", "]", "=", "handler" ]
Binds a set of handlers with the given factory. Args: tids (Sequence[int]): The Type IDs to bind to. user_handler (Callable): A function that takes as its parameters :class:`IonType`, ``length``, and the ``ctx`` context returning a co-routine. lns (Sequence[int]): The low-nibble lengths to bind to.
[ "Binds", "a", "set", "of", "handlers", "with", "the", "given", "factory", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L777-L799
train
233,783
amzn/ion-python
amazon/ion/reader_binary.py
_bind_length_scalar_handlers
def _bind_length_scalar_handlers(tids, scalar_factory, lns=_NON_ZERO_LENGTH_LNS): """Binds a set of scalar handlers for an inclusive range of low-nibble values. Args: tids (Sequence[int]): The Type IDs to bind to. scalar_factory (Callable): The factory for the scalar parsing function. This function can itself return a function representing a thunk to defer the scalar parsing or a direct value. lns (Sequence[int]): The low-nibble lengths to bind to. """ handler = partial(_length_scalar_handler, scalar_factory) return _bind_length_handlers(tids, handler, lns)
python
def _bind_length_scalar_handlers(tids, scalar_factory, lns=_NON_ZERO_LENGTH_LNS): """Binds a set of scalar handlers for an inclusive range of low-nibble values. Args: tids (Sequence[int]): The Type IDs to bind to. scalar_factory (Callable): The factory for the scalar parsing function. This function can itself return a function representing a thunk to defer the scalar parsing or a direct value. lns (Sequence[int]): The low-nibble lengths to bind to. """ handler = partial(_length_scalar_handler, scalar_factory) return _bind_length_handlers(tids, handler, lns)
[ "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. Args: tids (Sequence[int]): The Type IDs to bind to. scalar_factory (Callable): The factory for the scalar parsing function. This function can itself return a function representing a thunk to defer the scalar parsing or a direct value. lns (Sequence[int]): The low-nibble lengths to bind to.
[ "Binds", "a", "set", "of", "scalar", "handlers", "for", "an", "inclusive", "range", "of", "low", "-", "nibble", "values", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L802-L813
train
233,784
amzn/ion-python
amazon/ion/reader_binary.py
_HandlerContext.remaining
def remaining(self): """Determines how many bytes are remaining in the current context.""" if self.depth == 0: return _STREAM_REMAINING return self.limit - self.queue.position
python
def remaining(self): """Determines how many bytes are remaining in the current context.""" if self.depth == 0: return _STREAM_REMAINING return self.limit - self.queue.position
[ "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.
[ "Determines", "how", "many", "bytes", "are", "remaining", "in", "the", "current", "context", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L229-L233
train
233,785
amzn/ion-python
amazon/ion/reader_binary.py
_HandlerContext.read_data_transition
def read_data_transition(self, length, whence=None, skip=False, stream_event=ION_STREAM_INCOMPLETE_EVENT): """Returns an immediate event_transition to read a specified number of bytes.""" if whence is None: whence = self.whence return Transition( None, _read_data_handler(length, whence, self, skip, stream_event) )
python
def read_data_transition(self, length, whence=None, skip=False, stream_event=ION_STREAM_INCOMPLETE_EVENT): """Returns an immediate event_transition to read a specified number of bytes.""" if whence is None: whence = self.whence return Transition( None, _read_data_handler(length, whence, self, skip, stream_event) )
[ "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.
[ "Returns", "an", "immediate", "event_transition", "to", "read", "a", "specified", "number", "of", "bytes", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L235-L243
train
233,786
amzn/ion-python
amazon/ion/reader.py
_narrow_unichr
def _narrow_unichr(code_point): """Retrieves the unicode character representing any given code point, in a way that won't break on narrow builds. This is necessary because the built-in unichr function will fail for ordinals above 0xFFFF on narrow builds (UCS2); ordinals above 0xFFFF would require recalculating and combining surrogate pairs. This avoids that by retrieving the unicode character that was initially read. Args: code_point (int|CodePoint): An int or a subclass of int that contains the unicode character representing its code point in an attribute named 'char'. """ try: if len(code_point.char) > 1: return code_point.char except AttributeError: pass return six.unichr(code_point)
python
def _narrow_unichr(code_point): """Retrieves the unicode character representing any given code point, in a way that won't break on narrow builds. This is necessary because the built-in unichr function will fail for ordinals above 0xFFFF on narrow builds (UCS2); ordinals above 0xFFFF would require recalculating and combining surrogate pairs. This avoids that by retrieving the unicode character that was initially read. Args: code_point (int|CodePoint): An int or a subclass of int that contains the unicode character representing its code point in an attribute named 'char'. """ try: if len(code_point.char) > 1: return code_point.char except AttributeError: pass return six.unichr(code_point)
[ "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. This is necessary because the built-in unichr function will fail for ordinals above 0xFFFF on narrow builds (UCS2); ordinals above 0xFFFF would require recalculating and combining surrogate pairs. This avoids that by retrieving the unicode character that was initially read. Args: code_point (int|CodePoint): An int or a subclass of int that contains the unicode character representing its code point in an attribute named 'char'.
[ "Retrieves", "the", "unicode", "character", "representing", "any", "given", "code", "point", "in", "a", "way", "that", "won", "t", "break", "on", "narrow", "builds", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader.py#L43-L59
train
233,787
amzn/ion-python
amazon/ion/reader.py
reader_trampoline
def reader_trampoline(start, allow_flush=False): """Provides the co-routine trampoline for a reader state machine. The given co-routine is a state machine that yields :class:`Transition` and takes a Transition of :class:`amazon.ion.core.DataEvent` and the co-routine itself. A reader must start with a ``ReadEventType.NEXT`` event to prime the parser. In many cases this will lead to an ``IonEventType.INCOMPLETE`` being yielded, but not always (consider a reader over an in-memory data structure). Notes: A reader delimits its incomplete parse points with ``IonEventType.INCOMPLETE``. Readers also delimit complete parse points with ``IonEventType.STREAM_END``; this is similar to the ``INCOMPLETE`` case except that it denotes that a logical termination of data is *allowed*. When these event are received, the only valid input event type is a ``ReadEventType.DATA``. Generally, ``ReadEventType.NEXT`` is used to get the next parse event, but ``ReadEventType.SKIP`` can be used to skip over the current container. An internal state machine co-routine can delimit a state change without yielding to the caller by yielding ``None`` event, this will cause the trampoline to invoke the transition delegate, immediately. Args: start: The reader co-routine to initially delegate to. allow_flush(Optional[bool]): True if this reader supports receiving ``NEXT`` after yielding ``INCOMPLETE`` to trigger an attempt to flush pending parse events, otherwise False. Yields: amazon.ion.core.IonEvent: the result of parsing. Receives :class:`DataEvent` to parse into :class:`amazon.ion.core.IonEvent`. """ 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.delegate)) data_event = None if trans.event is not None: # Only yield if there is an event. data_event = (yield trans.event) if trans.event.event_type.is_stream_signal: if data_event.type is not ReadEventType.DATA: if not allow_flush or not (trans.event.event_type is IonEventType.INCOMPLETE and data_event.type is ReadEventType.NEXT): raise TypeError('Reader expected data: %r' % (data_event,)) else: if data_event.type is ReadEventType.DATA: raise TypeError('Reader did not expect data') if data_event.type is ReadEventType.DATA and len(data_event.data) == 0: raise ValueError('Empty data not allowed') if trans.event.depth == 0 \ and trans.event.event_type is not IonEventType.CONTAINER_START \ and data_event.type is ReadEventType.SKIP: raise TypeError('Cannot skip at the top-level')
python
def reader_trampoline(start, allow_flush=False): """Provides the co-routine trampoline for a reader state machine. The given co-routine is a state machine that yields :class:`Transition` and takes a Transition of :class:`amazon.ion.core.DataEvent` and the co-routine itself. A reader must start with a ``ReadEventType.NEXT`` event to prime the parser. In many cases this will lead to an ``IonEventType.INCOMPLETE`` being yielded, but not always (consider a reader over an in-memory data structure). Notes: A reader delimits its incomplete parse points with ``IonEventType.INCOMPLETE``. Readers also delimit complete parse points with ``IonEventType.STREAM_END``; this is similar to the ``INCOMPLETE`` case except that it denotes that a logical termination of data is *allowed*. When these event are received, the only valid input event type is a ``ReadEventType.DATA``. Generally, ``ReadEventType.NEXT`` is used to get the next parse event, but ``ReadEventType.SKIP`` can be used to skip over the current container. An internal state machine co-routine can delimit a state change without yielding to the caller by yielding ``None`` event, this will cause the trampoline to invoke the transition delegate, immediately. Args: start: The reader co-routine to initially delegate to. allow_flush(Optional[bool]): True if this reader supports receiving ``NEXT`` after yielding ``INCOMPLETE`` to trigger an attempt to flush pending parse events, otherwise False. Yields: amazon.ion.core.IonEvent: the result of parsing. Receives :class:`DataEvent` to parse into :class:`amazon.ion.core.IonEvent`. """ 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.delegate)) data_event = None if trans.event is not None: # Only yield if there is an event. data_event = (yield trans.event) if trans.event.event_type.is_stream_signal: if data_event.type is not ReadEventType.DATA: if not allow_flush or not (trans.event.event_type is IonEventType.INCOMPLETE and data_event.type is ReadEventType.NEXT): raise TypeError('Reader expected data: %r' % (data_event,)) else: if data_event.type is ReadEventType.DATA: raise TypeError('Reader did not expect data') if data_event.type is ReadEventType.DATA and len(data_event.data) == 0: raise ValueError('Empty data not allowed') if trans.event.depth == 0 \ and trans.event.event_type is not IonEventType.CONTAINER_START \ and data_event.type is ReadEventType.SKIP: raise TypeError('Cannot skip at the top-level')
[ "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", ".", "delegate", ")", ")", "data_event", "=", "None", "if", "trans", ".", "event", "is", "not", "None", ":", "# Only yield if there is an event.", "data_event", "=", "(", "yield", "trans", ".", "event", ")", "if", "trans", ".", "event", ".", "event_type", ".", "is_stream_signal", ":", "if", "data_event", ".", "type", "is", "not", "ReadEventType", ".", "DATA", ":", "if", "not", "allow_flush", "or", "not", "(", "trans", ".", "event", ".", "event_type", "is", "IonEventType", ".", "INCOMPLETE", "and", "data_event", ".", "type", "is", "ReadEventType", ".", "NEXT", ")", ":", "raise", "TypeError", "(", "'Reader expected data: %r'", "%", "(", "data_event", ",", ")", ")", "else", ":", "if", "data_event", ".", "type", "is", "ReadEventType", ".", "DATA", ":", "raise", "TypeError", "(", "'Reader did not expect data'", ")", "if", "data_event", ".", "type", "is", "ReadEventType", ".", "DATA", "and", "len", "(", "data_event", ".", "data", ")", "==", "0", ":", "raise", "ValueError", "(", "'Empty data not allowed'", ")", "if", "trans", ".", "event", ".", "depth", "==", "0", "and", "trans", ".", "event", ".", "event_type", "is", "not", "IonEventType", ".", "CONTAINER_START", "and", "data_event", ".", "type", "is", "ReadEventType", ".", "SKIP", ":", "raise", "TypeError", "(", "'Cannot skip at the top-level'", ")" ]
Provides the co-routine trampoline for a reader state machine. The given co-routine is a state machine that yields :class:`Transition` and takes a Transition of :class:`amazon.ion.core.DataEvent` and the co-routine itself. A reader must start with a ``ReadEventType.NEXT`` event to prime the parser. In many cases this will lead to an ``IonEventType.INCOMPLETE`` being yielded, but not always (consider a reader over an in-memory data structure). Notes: A reader delimits its incomplete parse points with ``IonEventType.INCOMPLETE``. Readers also delimit complete parse points with ``IonEventType.STREAM_END``; this is similar to the ``INCOMPLETE`` case except that it denotes that a logical termination of data is *allowed*. When these event are received, the only valid input event type is a ``ReadEventType.DATA``. Generally, ``ReadEventType.NEXT`` is used to get the next parse event, but ``ReadEventType.SKIP`` can be used to skip over the current container. An internal state machine co-routine can delimit a state change without yielding to the caller by yielding ``None`` event, this will cause the trampoline to invoke the transition delegate, immediately. Args: start: The reader co-routine to initially delegate to. allow_flush(Optional[bool]): True if this reader supports receiving ``NEXT`` after yielding ``INCOMPLETE`` to trigger an attempt to flush pending parse events, otherwise False. Yields: amazon.ion.core.IonEvent: the result of parsing. Receives :class:`DataEvent` to parse into :class:`amazon.ion.core.IonEvent`.
[ "Provides", "the", "co", "-", "routine", "trampoline", "for", "a", "reader", "state", "machine", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader.py#L312-L369
train
233,788
amzn/ion-python
amazon/ion/reader.py
blocking_reader
def blocking_reader(reader, input, buffer_size=_DEFAULT_BUFFER_SIZE): """Provides an implementation of using the reader co-routine with a file-like object. Args: reader(Coroutine): A reader co-routine. input(BaseIO): The file-like object to read from. buffer_size(Optional[int]): The optional buffer size to use. """ 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: # End of file. if ion_event.event_type is IonEventType.INCOMPLETE: ion_event = reader.send(NEXT_EVENT) continue else: yield ION_STREAM_END_EVENT return ion_event = reader.send(read_data_event(data))
python
def blocking_reader(reader, input, buffer_size=_DEFAULT_BUFFER_SIZE): """Provides an implementation of using the reader co-routine with a file-like object. Args: reader(Coroutine): A reader co-routine. input(BaseIO): The file-like object to read from. buffer_size(Optional[int]): The optional buffer size to use. """ 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: # End of file. if ion_event.event_type is IonEventType.INCOMPLETE: ion_event = reader.send(NEXT_EVENT) continue else: yield ION_STREAM_END_EVENT return ion_event = reader.send(read_data_event(data))
[ "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", ":", "# End of file.", "if", "ion_event", ".", "event_type", "is", "IonEventType", ".", "INCOMPLETE", ":", "ion_event", "=", "reader", ".", "send", "(", "NEXT_EVENT", ")", "continue", "else", ":", "yield", "ION_STREAM_END_EVENT", "return", "ion_event", "=", "reader", ".", "send", "(", "read_data_event", "(", "data", ")", ")" ]
Provides an implementation of using the reader co-routine with a file-like object. Args: reader(Coroutine): A reader co-routine. input(BaseIO): The file-like object to read from. buffer_size(Optional[int]): The optional buffer size to use.
[ "Provides", "an", "implementation", "of", "using", "the", "reader", "co", "-", "routine", "with", "a", "file", "-", "like", "object", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader.py#L376-L398
train
233,789
amzn/ion-python
amazon/ion/reader.py
BufferQueue.read
def read(self, length, skip=False): """Consumes the first ``length`` bytes from the accumulator.""" 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: segment = segments[0] segment_off = offset segment_len = len(segment) segment_rem = segment_len - segment_off segment_read_len = min(segment_rem, length) if segment_off == 0 and segment_read_len == segment_rem: # consume an entire segment if skip: segment_slice = self.__element_type() else: segment_slice = segment else: # Consume a part of the segment. if skip: segment_slice = self.__element_type() else: segment_slice = segment[segment_off:segment_off + segment_read_len] offset = 0 segment_off += segment_read_len if segment_off == segment_len: segments.popleft() self.__offset = 0 else: self.__offset = segment_off if length <= segment_rem and len(data) == 0: return segment_slice data.extend(segment_slice) length -= segment_read_len if self.is_unicode: return data.as_text() else: return data
python
def read(self, length, skip=False): """Consumes the first ``length`` bytes from the accumulator.""" 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: segment = segments[0] segment_off = offset segment_len = len(segment) segment_rem = segment_len - segment_off segment_read_len = min(segment_rem, length) if segment_off == 0 and segment_read_len == segment_rem: # consume an entire segment if skip: segment_slice = self.__element_type() else: segment_slice = segment else: # Consume a part of the segment. if skip: segment_slice = self.__element_type() else: segment_slice = segment[segment_off:segment_off + segment_read_len] offset = 0 segment_off += segment_read_len if segment_off == segment_len: segments.popleft() self.__offset = 0 else: self.__offset = segment_off if length <= segment_rem and len(data) == 0: return segment_slice data.extend(segment_slice) length -= segment_read_len if self.is_unicode: return data.as_text() else: return data
[ "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", ":", "segment", "=", "segments", "[", "0", "]", "segment_off", "=", "offset", "segment_len", "=", "len", "(", "segment", ")", "segment_rem", "=", "segment_len", "-", "segment_off", "segment_read_len", "=", "min", "(", "segment_rem", ",", "length", ")", "if", "segment_off", "==", "0", "and", "segment_read_len", "==", "segment_rem", ":", "# consume an entire segment", "if", "skip", ":", "segment_slice", "=", "self", ".", "__element_type", "(", ")", "else", ":", "segment_slice", "=", "segment", "else", ":", "# Consume a part of the segment.", "if", "skip", ":", "segment_slice", "=", "self", ".", "__element_type", "(", ")", "else", ":", "segment_slice", "=", "segment", "[", "segment_off", ":", "segment_off", "+", "segment_read_len", "]", "offset", "=", "0", "segment_off", "+=", "segment_read_len", "if", "segment_off", "==", "segment_len", ":", "segments", ".", "popleft", "(", ")", "self", ".", "__offset", "=", "0", "else", ":", "self", ".", "__offset", "=", "segment_off", "if", "length", "<=", "segment_rem", "and", "len", "(", "data", ")", "==", "0", ":", "return", "segment_slice", "data", ".", "extend", "(", "segment_slice", ")", "length", "-=", "segment_read_len", "if", "self", ".", "is_unicode", ":", "return", "data", ".", "as_text", "(", ")", "else", ":", "return", "data" ]
Consumes the first ``length`` bytes from the accumulator.
[ "Consumes", "the", "first", "length", "bytes", "from", "the", "accumulator", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader.py#L154-L199
train
233,790
amzn/ion-python
amazon/ion/reader.py
BufferQueue.unread
def unread(self, c): """Unread the given character, byte, or code point. If this is a unicode buffer and the input is an int or byte, it will be interpreted as an ordinal representing a unicode code point. If this is a binary buffer, the input must be a byte or int; a unicode character will raise an error. """ 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 1 if self.__offset == 0: if num_code_units == 1 and six.PY3: if self.is_unicode: segment = c else: segment = six.int2byte(c) else: segment = c self.__segments.appendleft(segment) else: self.__offset -= num_code_units def verify(ch, idx): existing = self.__segments[0][self.__offset + idx] if existing != ch: raise ValueError('Attempted to unread %s when %s was expected.' % (ch, existing)) if num_code_units == 1: verify(c, 0) else: for i in range(num_code_units): verify(c[i], i) self.__size += num_code_units self.position -= num_code_units
python
def unread(self, c): """Unread the given character, byte, or code point. If this is a unicode buffer and the input is an int or byte, it will be interpreted as an ordinal representing a unicode code point. If this is a binary buffer, the input must be a byte or int; a unicode character will raise an error. """ 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 1 if self.__offset == 0: if num_code_units == 1 and six.PY3: if self.is_unicode: segment = c else: segment = six.int2byte(c) else: segment = c self.__segments.appendleft(segment) else: self.__offset -= num_code_units def verify(ch, idx): existing = self.__segments[0][self.__offset + idx] if existing != ch: raise ValueError('Attempted to unread %s when %s was expected.' % (ch, existing)) if num_code_units == 1: verify(c, 0) else: for i in range(num_code_units): verify(c[i], i) self.__size += num_code_units self.position -= num_code_units
[ "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", "1", "if", "self", ".", "__offset", "==", "0", ":", "if", "num_code_units", "==", "1", "and", "six", ".", "PY3", ":", "if", "self", ".", "is_unicode", ":", "segment", "=", "c", "else", ":", "segment", "=", "six", ".", "int2byte", "(", "c", ")", "else", ":", "segment", "=", "c", "self", ".", "__segments", ".", "appendleft", "(", "segment", ")", "else", ":", "self", ".", "__offset", "-=", "num_code_units", "def", "verify", "(", "ch", ",", "idx", ")", ":", "existing", "=", "self", ".", "__segments", "[", "0", "]", "[", "self", ".", "__offset", "+", "idx", "]", "if", "existing", "!=", "ch", ":", "raise", "ValueError", "(", "'Attempted to unread %s when %s was expected.'", "%", "(", "ch", ",", "existing", ")", ")", "if", "num_code_units", "==", "1", ":", "verify", "(", "c", ",", "0", ")", "else", ":", "for", "i", "in", "range", "(", "num_code_units", ")", ":", "verify", "(", "c", "[", "i", "]", ",", "i", ")", "self", ".", "__size", "+=", "num_code_units", "self", ".", "position", "-=", "num_code_units" ]
Unread the given character, byte, or code point. If this is a unicode buffer and the input is an int or byte, it will be interpreted as an ordinal representing a unicode code point. If this is a binary buffer, the input must be a byte or int; a unicode character will raise an error.
[ "Unread", "the", "given", "character", "byte", "or", "code", "point", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader.py#L221-L259
train
233,791
amzn/ion-python
amazon/ion/reader.py
BufferQueue.skip
def skip(self, length): """Removes ``length`` bytes and returns the number length still required to skip""" 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
python
def skip(self, length): """Removes ``length`` bytes and returns the number length still required to skip""" 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
[ "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
[ "Removes", "length", "bytes", "and", "returns", "the", "number", "length", "still", "required", "to", "skip" ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader.py#L261-L273
train
233,792
amzn/ion-python
amazon/ion/reader_managed.py
managed_reader
def managed_reader(reader, catalog=None): """Managed reader wrapping another reader. Args: reader (Coroutine): The underlying non-blocking reader co-routine. catalog (Optional[SymbolTableCatalog]): The catalog to use for resolving imports. Yields: Events from the underlying reader delegating to symbol table processing as needed. The user will never see things like version markers or local symbol tables. """ 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_signal: # We have a symbol processor active, do not yield to user. delegate = symbol_trans.delegate symbol_trans = delegate.send(Transition(ion_event, delegate)) if symbol_trans.delegate is None: # When the symbol processor terminates, the event is the context # and there is no delegate. ctx = symbol_trans.event data_event = NEXT_EVENT else: data_event = symbol_trans.event else: data_event = None if ion_event is not None: event_type = ion_event.event_type ion_type = ion_event.ion_type depth = ion_event.depth # System values only happen at the top-level if depth == 0: if event_type is IonEventType.VERSION_MARKER: if ion_event != ION_VERSION_MARKER_EVENT: raise IonException('Invalid IVM: %s' % (ion_event,)) # Reset and swallow IVM ctx = _ManagedContext(ctx.catalog) data_event = NEXT_EVENT elif ion_type is IonType.SYMBOL \ and len(ion_event.annotations) == 0 \ and ion_event.value is not None \ and ctx.resolve(ion_event.value).text == TEXT_ION_1_0: assert symbol_trans.delegate is None # A faux IVM is a NOP data_event = NEXT_EVENT elif event_type is IonEventType.CONTAINER_START \ and ion_type is IonType.STRUCT \ and ctx.has_symbol_table_annotation(ion_event.annotations): assert symbol_trans.delegate is None # Activate a new symbol processor. delegate = _local_symbol_table_handler(ctx) symbol_trans = Transition(None, delegate) data_event = NEXT_EVENT if data_event is None: # No system processing or we have to get data, yield control. if ion_event is not None: ion_event = _managed_thunk_event(ctx, ion_event) data_event = yield ion_event ion_event = reader.send(data_event)
python
def managed_reader(reader, catalog=None): """Managed reader wrapping another reader. Args: reader (Coroutine): The underlying non-blocking reader co-routine. catalog (Optional[SymbolTableCatalog]): The catalog to use for resolving imports. Yields: Events from the underlying reader delegating to symbol table processing as needed. The user will never see things like version markers or local symbol tables. """ 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_signal: # We have a symbol processor active, do not yield to user. delegate = symbol_trans.delegate symbol_trans = delegate.send(Transition(ion_event, delegate)) if symbol_trans.delegate is None: # When the symbol processor terminates, the event is the context # and there is no delegate. ctx = symbol_trans.event data_event = NEXT_EVENT else: data_event = symbol_trans.event else: data_event = None if ion_event is not None: event_type = ion_event.event_type ion_type = ion_event.ion_type depth = ion_event.depth # System values only happen at the top-level if depth == 0: if event_type is IonEventType.VERSION_MARKER: if ion_event != ION_VERSION_MARKER_EVENT: raise IonException('Invalid IVM: %s' % (ion_event,)) # Reset and swallow IVM ctx = _ManagedContext(ctx.catalog) data_event = NEXT_EVENT elif ion_type is IonType.SYMBOL \ and len(ion_event.annotations) == 0 \ and ion_event.value is not None \ and ctx.resolve(ion_event.value).text == TEXT_ION_1_0: assert symbol_trans.delegate is None # A faux IVM is a NOP data_event = NEXT_EVENT elif event_type is IonEventType.CONTAINER_START \ and ion_type is IonType.STRUCT \ and ctx.has_symbol_table_annotation(ion_event.annotations): assert symbol_trans.delegate is None # Activate a new symbol processor. delegate = _local_symbol_table_handler(ctx) symbol_trans = Transition(None, delegate) data_event = NEXT_EVENT if data_event is None: # No system processing or we have to get data, yield control. if ion_event is not None: ion_event = _managed_thunk_event(ctx, ion_event) data_event = yield ion_event ion_event = reader.send(data_event)
[ "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_signal", ":", "# We have a symbol processor active, do not yield to user.", "delegate", "=", "symbol_trans", ".", "delegate", "symbol_trans", "=", "delegate", ".", "send", "(", "Transition", "(", "ion_event", ",", "delegate", ")", ")", "if", "symbol_trans", ".", "delegate", "is", "None", ":", "# When the symbol processor terminates, the event is the context", "# and there is no delegate.", "ctx", "=", "symbol_trans", ".", "event", "data_event", "=", "NEXT_EVENT", "else", ":", "data_event", "=", "symbol_trans", ".", "event", "else", ":", "data_event", "=", "None", "if", "ion_event", "is", "not", "None", ":", "event_type", "=", "ion_event", ".", "event_type", "ion_type", "=", "ion_event", ".", "ion_type", "depth", "=", "ion_event", ".", "depth", "# System values only happen at the top-level", "if", "depth", "==", "0", ":", "if", "event_type", "is", "IonEventType", ".", "VERSION_MARKER", ":", "if", "ion_event", "!=", "ION_VERSION_MARKER_EVENT", ":", "raise", "IonException", "(", "'Invalid IVM: %s'", "%", "(", "ion_event", ",", ")", ")", "# Reset and swallow IVM", "ctx", "=", "_ManagedContext", "(", "ctx", ".", "catalog", ")", "data_event", "=", "NEXT_EVENT", "elif", "ion_type", "is", "IonType", ".", "SYMBOL", "and", "len", "(", "ion_event", ".", "annotations", ")", "==", "0", "and", "ion_event", ".", "value", "is", "not", "None", "and", "ctx", ".", "resolve", "(", "ion_event", ".", "value", ")", ".", "text", "==", "TEXT_ION_1_0", ":", "assert", "symbol_trans", ".", "delegate", "is", "None", "# A faux IVM is a NOP", "data_event", "=", "NEXT_EVENT", "elif", "event_type", "is", "IonEventType", ".", "CONTAINER_START", "and", "ion_type", "is", "IonType", ".", "STRUCT", "and", "ctx", ".", "has_symbol_table_annotation", "(", "ion_event", ".", "annotations", ")", ":", "assert", "symbol_trans", ".", "delegate", "is", "None", "# Activate a new symbol processor.", "delegate", "=", "_local_symbol_table_handler", "(", "ctx", ")", "symbol_trans", "=", "Transition", "(", "None", ",", "delegate", ")", "data_event", "=", "NEXT_EVENT", "if", "data_event", "is", "None", ":", "# No system processing or we have to get data, yield control.", "if", "ion_event", "is", "not", "None", ":", "ion_event", "=", "_managed_thunk_event", "(", "ctx", ",", "ion_event", ")", "data_event", "=", "yield", "ion_event", "ion_event", "=", "reader", ".", "send", "(", "data_event", ")" ]
Managed reader wrapping another reader. Args: reader (Coroutine): The underlying non-blocking reader co-routine. catalog (Optional[SymbolTableCatalog]): The catalog to use for resolving imports. Yields: Events from the underlying reader delegating to symbol table processing as needed. The user will never see things like version markers or local symbol tables.
[ "Managed", "reader", "wrapping", "another", "reader", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_managed.py#L261-L335
train
233,793
amzn/ion-python
amazon/ion/reader_text.py
_illegal_character
def _illegal_character(c, ctx, message=''): """Raises an IonException upon encountering the given illegal character in the given context. Args: c (int|None): Ordinal of the illegal character. ctx (_HandlerContext): Context in which the illegal character was encountered. message (Optional[str]): Additional information, as necessary. """ 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) else _chr(c) header = 'Illegal character %s' % (c,) raise IonException('%s at position %d in %s value contained in %s. %s Pending value: %s' % (header, ctx.queue.position, value_type, container_type, message, ctx.value))
python
def _illegal_character(c, ctx, message=''): """Raises an IonException upon encountering the given illegal character in the given context. Args: c (int|None): Ordinal of the illegal character. ctx (_HandlerContext): Context in which the illegal character was encountered. message (Optional[str]): Additional information, as necessary. """ 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) else _chr(c) header = 'Illegal character %s' % (c,) raise IonException('%s at position %d in %s value contained in %s. %s Pending value: %s' % (header, ctx.queue.position, value_type, container_type, message, ctx.value))
[ "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", ")", "else", "_chr", "(", "c", ")", "header", "=", "'Illegal character %s'", "%", "(", "c", ",", ")", "raise", "IonException", "(", "'%s at position %d in %s value contained in %s. %s Pending value: %s'", "%", "(", "header", ",", "ctx", ".", "queue", ".", "position", ",", "value_type", ",", "container_type", ",", "message", ",", "ctx", ".", "value", ")", ")" ]
Raises an IonException upon encountering the given illegal character in the given context. Args: c (int|None): Ordinal of the illegal character. ctx (_HandlerContext): Context in which the illegal character was encountered. message (Optional[str]): Additional information, as necessary.
[ "Raises", "an", "IonException", "upon", "encountering", "the", "given", "illegal", "character", "in", "the", "given", "context", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L40-L57
train
233,794
amzn/ion-python
amazon/ion/reader_text.py
_defaultdict
def _defaultdict(dct, fallback=_illegal_character): """Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is accessed. """ out = defaultdict(lambda: fallback) for k, v in six.iteritems(dct): out[k] = v return out
python
def _defaultdict(dct, fallback=_illegal_character): """Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is accessed. """ out = defaultdict(lambda: fallback) for k, v in six.iteritems(dct): out[k] = v return out
[ "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.
[ "Wraps", "the", "given", "dictionary", "such", "that", "the", "given", "fallback", "function", "will", "be", "called", "when", "a", "nonexistent", "key", "is", "accessed", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L60-L67
train
233,795
amzn/ion-python
amazon/ion/reader_text.py
_number_negative_start_handler
def _number_negative_start_handler(c, ctx): """Handles numeric values that start with a negative sign. Branches to delegate co-routines according to _NEGATIVE_TABLE. """ 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))
python
def _number_negative_start_handler(c, ctx): """Handles numeric values that start with a negative sign. Branches to delegate co-routines according to _NEGATIVE_TABLE. """ 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))
[ "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.
[ "Handles", "numeric", "values", "that", "start", "with", "a", "negative", "sign", ".", "Branches", "to", "delegate", "co", "-", "routines", "according", "to", "_NEGATIVE_TABLE", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L585-L594
train
233,796
amzn/ion-python
amazon/ion/reader_text.py
_number_zero_start_handler
def _number_zero_start_handler(c, ctx): """Handles numeric values that start with zero or negative zero. Branches to delegate co-routines according to _ZERO_START_TABLE. """ 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, IonEventType.SCALAR, ctx.ion_type, _parse_decimal_int(ctx.value)) if c == _SLASH: trans = ctx.immediate_transition(_number_slash_end_handler(c, ctx, trans)) yield trans yield ctx.immediate_transition(_ZERO_START_TABLE[c](c, ctx))
python
def _number_zero_start_handler(c, ctx): """Handles numeric values that start with zero or negative zero. Branches to delegate co-routines according to _ZERO_START_TABLE. """ 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, IonEventType.SCALAR, ctx.ion_type, _parse_decimal_int(ctx.value)) if c == _SLASH: trans = ctx.immediate_transition(_number_slash_end_handler(c, ctx, trans)) yield trans yield ctx.immediate_transition(_ZERO_START_TABLE[c](c, ctx))
[ "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", ",", "IonEventType", ".", "SCALAR", ",", "ctx", ".", "ion_type", ",", "_parse_decimal_int", "(", "ctx", ".", "value", ")", ")", "if", "c", "==", "_SLASH", ":", "trans", "=", "ctx", ".", "immediate_transition", "(", "_number_slash_end_handler", "(", "c", ",", "ctx", ",", "trans", ")", ")", "yield", "trans", "yield", "ctx", ".", "immediate_transition", "(", "_ZERO_START_TABLE", "[", "c", "]", "(", "c", ",", "ctx", ")", ")" ]
Handles numeric values that start with zero or negative zero. Branches to delegate co-routines according to _ZERO_START_TABLE.
[ "Handles", "numeric", "values", "that", "start", "with", "zero", "or", "negative", "zero", ".", "Branches", "to", "delegate", "co", "-", "routines", "according", "to", "_ZERO_START_TABLE", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L598-L612
train
233,797
amzn/ion-python
amazon/ion/reader_text.py
_number_or_timestamp_handler
def _number_or_timestamp_handler(c, ctx): """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. """ assert c in _DIGITS ctx.set_ion_type(IonType.INT) # If this is the last digit read, this value is an 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_type, _parse_decimal_int(ctx.value)) if c == _SLASH: trans = ctx.immediate_transition(_number_slash_end_handler(c, ctx, trans)) else: if c not in _DIGITS: trans = ctx.immediate_transition(_NUMBER_OR_TIMESTAMP_TABLE[c](c, ctx)) else: val.append(c) c, _ = yield trans
python
def _number_or_timestamp_handler(c, ctx): """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. """ assert c in _DIGITS ctx.set_ion_type(IonType.INT) # If this is the last digit read, this value is an 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_type, _parse_decimal_int(ctx.value)) if c == _SLASH: trans = ctx.immediate_transition(_number_slash_end_handler(c, ctx, trans)) else: if c not in _DIGITS: trans = ctx.immediate_transition(_NUMBER_OR_TIMESTAMP_TABLE[c](c, ctx)) else: val.append(c) c, _ = yield trans
[ "def", "_number_or_timestamp_handler", "(", "c", ",", "ctx", ")", ":", "assert", "c", "in", "_DIGITS", "ctx", ".", "set_ion_type", "(", "IonType", ".", "INT", ")", "# If this is the last digit read, this value is an 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_type", ",", "_parse_decimal_int", "(", "ctx", ".", "value", ")", ")", "if", "c", "==", "_SLASH", ":", "trans", "=", "ctx", ".", "immediate_transition", "(", "_number_slash_end_handler", "(", "c", ",", "ctx", ",", "trans", ")", ")", "else", ":", "if", "c", "not", "in", "_DIGITS", ":", "trans", "=", "ctx", ".", "immediate_transition", "(", "_NUMBER_OR_TIMESTAMP_TABLE", "[", "c", "]", "(", "c", ",", "ctx", ")", ")", "else", ":", "val", ".", "append", "(", "c", ")", "c", ",", "_", "=", "yield", "trans" ]
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.
[ "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", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L616-L637
train
233,798
amzn/ion-python
amazon/ion/reader_text.py
_number_slash_end_handler
def _number_slash_end_handler(c, ctx, event): """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. """ 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)) # If the previous line returns without error, it's a valid comment and the number may be emitted. yield _CompositeTransition(event, ctx, comment, next_ctx, initialize_handler=False)
python
def _number_slash_end_handler(c, ctx, event): """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. """ 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)) # If the previous line returns without error, it's a valid comment and the number may be emitted. yield _CompositeTransition(event, ctx, comment, next_ctx, initialize_handler=False)
[ "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", ")", ")", "# If the previous line returns without error, it's a valid comment and the number may be emitted.", "yield", "_CompositeTransition", "(", "event", ",", "ctx", ",", "comment", ",", "next_ctx", ",", "initialize_handler", "=", "False", ")" ]
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.
[ "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", "." ]
0b21fa3ba7755f55f745e4aa970d86343b82449d
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L641-L651
train
233,799