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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Crunch-io/crunch-cube | src/cr/cube/measures/index.py | Index.data | def data(cls, cube, weighted, prune):
"""Return ndarray representing table index by margin."""
return cls()._data(cube, weighted, prune) | python | def data(cls, cube, weighted, prune):
"""Return ndarray representing table index by margin."""
return cls()._data(cube, weighted, prune) | [
"def",
"data",
"(",
"cls",
",",
"cube",
",",
"weighted",
",",
"prune",
")",
":",
"return",
"cls",
"(",
")",
".",
"_data",
"(",
"cube",
",",
"weighted",
",",
"prune",
")"
] | Return ndarray representing table index by margin. | [
"Return",
"ndarray",
"representing",
"table",
"index",
"by",
"margin",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/measures/index.py#L18-L20 | train | 37,100 |
Crunch-io/crunch-cube | src/cr/cube/measures/index.py | Index._data | def _data(self, cube, weighted, prune):
"""ndarray representing table index by margin."""
result = []
for slice_ in cube.slices:
if cube.has_mr:
return self._mr_index(cube, weighted, prune)
num = slice_.margin(axis=0, weighted=weighted, prune=prune)
den = slice_.margin(weighted=weighted, prune=prune)
margin = num / den
proportions = slice_.proportions(axis=1, weighted=weighted, prune=prune)
result.append(proportions / margin)
if len(result) == 1 and cube.ndim < 3:
result = result[0]
else:
if prune:
mask = np.array([slice_.mask for slice_ in result])
result = np.ma.masked_array(result, mask)
else:
result = np.array(result)
return result | python | def _data(self, cube, weighted, prune):
"""ndarray representing table index by margin."""
result = []
for slice_ in cube.slices:
if cube.has_mr:
return self._mr_index(cube, weighted, prune)
num = slice_.margin(axis=0, weighted=weighted, prune=prune)
den = slice_.margin(weighted=weighted, prune=prune)
margin = num / den
proportions = slice_.proportions(axis=1, weighted=weighted, prune=prune)
result.append(proportions / margin)
if len(result) == 1 and cube.ndim < 3:
result = result[0]
else:
if prune:
mask = np.array([slice_.mask for slice_ in result])
result = np.ma.masked_array(result, mask)
else:
result = np.array(result)
return result | [
"def",
"_data",
"(",
"self",
",",
"cube",
",",
"weighted",
",",
"prune",
")",
":",
"result",
"=",
"[",
"]",
"for",
"slice_",
"in",
"cube",
".",
"slices",
":",
"if",
"cube",
".",
"has_mr",
":",
"return",
"self",
".",
"_mr_index",
"(",
"cube",
",",
... | ndarray representing table index by margin. | [
"ndarray",
"representing",
"table",
"index",
"by",
"margin",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/measures/index.py#L22-L43 | train | 37,101 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/statshelpers.py | kakwani | def kakwani(values, ineq_axis, weights = None):
"""
Computes the Kakwani index
"""
from scipy.integrate import simps
if weights is None:
weights = ones(len(values))
# sign = -1
# if tax == True:
# sign = -1
# else:
# sign = 1
PLCx, PLCy = pseudo_lorenz(values, ineq_axis, weights)
LCx, LCy = lorenz(ineq_axis, weights)
del PLCx
return simps((LCy - PLCy), LCx) | python | def kakwani(values, ineq_axis, weights = None):
"""
Computes the Kakwani index
"""
from scipy.integrate import simps
if weights is None:
weights = ones(len(values))
# sign = -1
# if tax == True:
# sign = -1
# else:
# sign = 1
PLCx, PLCy = pseudo_lorenz(values, ineq_axis, weights)
LCx, LCy = lorenz(ineq_axis, weights)
del PLCx
return simps((LCy - PLCy), LCx) | [
"def",
"kakwani",
"(",
"values",
",",
"ineq_axis",
",",
"weights",
"=",
"None",
")",
":",
"from",
"scipy",
".",
"integrate",
"import",
"simps",
"if",
"weights",
"is",
"None",
":",
"weights",
"=",
"ones",
"(",
"len",
"(",
"values",
")",
")",
"# sign ... | Computes the Kakwani index | [
"Computes",
"the",
"Kakwani",
"index"
] | bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358 | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/statshelpers.py#L48-L68 | train | 37,102 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/statshelpers.py | lorenz | def lorenz(values, weights = None):
"""
Computes Lorenz Curve coordinates
"""
if weights is None:
weights = ones(len(values))
df = pd.DataFrame({'v': values, 'w': weights})
df = df.sort_values(by = 'v')
x = cumsum(df['w'])
x = x / float(x[-1:])
y = cumsum(df['v'] * df['w'])
y = y / float(y[-1:])
return x, y | python | def lorenz(values, weights = None):
"""
Computes Lorenz Curve coordinates
"""
if weights is None:
weights = ones(len(values))
df = pd.DataFrame({'v': values, 'w': weights})
df = df.sort_values(by = 'v')
x = cumsum(df['w'])
x = x / float(x[-1:])
y = cumsum(df['v'] * df['w'])
y = y / float(y[-1:])
return x, y | [
"def",
"lorenz",
"(",
"values",
",",
"weights",
"=",
"None",
")",
":",
"if",
"weights",
"is",
"None",
":",
"weights",
"=",
"ones",
"(",
"len",
"(",
"values",
")",
")",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"{",
"'v'",
":",
"values",
",",
"'w'",... | Computes Lorenz Curve coordinates | [
"Computes",
"Lorenz",
"Curve",
"coordinates"
] | bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358 | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/statshelpers.py#L71-L85 | train | 37,103 |
Crunch-io/crunch-cube | src/cr/cube/measures/wishart_pairwise_significance.py | WishartPairwiseSignificance.pvals | def pvals(cls, slice_, axis=0, weighted=True):
"""Wishart CDF values for slice columns as square ndarray.
Wishart CDF (Cumulative Distribution Function) is calculated to determine
statistical significance of slice columns, in relation to all other columns.
These values represent the answer to the question "How much is a particular
column different from each other column in the slice".
"""
return cls._factory(slice_, axis, weighted).pvals | python | def pvals(cls, slice_, axis=0, weighted=True):
"""Wishart CDF values for slice columns as square ndarray.
Wishart CDF (Cumulative Distribution Function) is calculated to determine
statistical significance of slice columns, in relation to all other columns.
These values represent the answer to the question "How much is a particular
column different from each other column in the slice".
"""
return cls._factory(slice_, axis, weighted).pvals | [
"def",
"pvals",
"(",
"cls",
",",
"slice_",
",",
"axis",
"=",
"0",
",",
"weighted",
"=",
"True",
")",
":",
"return",
"cls",
".",
"_factory",
"(",
"slice_",
",",
"axis",
",",
"weighted",
")",
".",
"pvals"
] | Wishart CDF values for slice columns as square ndarray.
Wishart CDF (Cumulative Distribution Function) is calculated to determine
statistical significance of slice columns, in relation to all other columns.
These values represent the answer to the question "How much is a particular
column different from each other column in the slice". | [
"Wishart",
"CDF",
"values",
"for",
"slice",
"columns",
"as",
"square",
"ndarray",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/measures/wishart_pairwise_significance.py#L31-L39 | train | 37,104 |
Crunch-io/crunch-cube | src/cr/cube/measures/wishart_pairwise_significance.py | WishartPairwiseSignificance._chi_squared | def _chi_squared(self, proportions, margin, observed):
"""return ndarray of chi-squared measures for proportions' columns.
*proportions* (ndarray): The basis of chi-squared calcualations
*margin* (ndarray): Column margin for proportions (See `def _margin`)
*observed* (ndarray): Row margin proportions (See `def _observed`)
"""
n = self._element_count
chi_squared = np.zeros([n, n])
for i in xrange(1, n):
for j in xrange(0, n - 1):
denominator = 1 / margin[i] + 1 / margin[j]
chi_squared[i, j] = chi_squared[j, i] = (
np.sum(np.square(proportions[:, i] - proportions[:, j]) / observed)
/ denominator
)
return chi_squared | python | def _chi_squared(self, proportions, margin, observed):
"""return ndarray of chi-squared measures for proportions' columns.
*proportions* (ndarray): The basis of chi-squared calcualations
*margin* (ndarray): Column margin for proportions (See `def _margin`)
*observed* (ndarray): Row margin proportions (See `def _observed`)
"""
n = self._element_count
chi_squared = np.zeros([n, n])
for i in xrange(1, n):
for j in xrange(0, n - 1):
denominator = 1 / margin[i] + 1 / margin[j]
chi_squared[i, j] = chi_squared[j, i] = (
np.sum(np.square(proportions[:, i] - proportions[:, j]) / observed)
/ denominator
)
return chi_squared | [
"def",
"_chi_squared",
"(",
"self",
",",
"proportions",
",",
"margin",
",",
"observed",
")",
":",
"n",
"=",
"self",
".",
"_element_count",
"chi_squared",
"=",
"np",
".",
"zeros",
"(",
"[",
"n",
",",
"n",
"]",
")",
"for",
"i",
"in",
"xrange",
"(",
"... | return ndarray of chi-squared measures for proportions' columns.
*proportions* (ndarray): The basis of chi-squared calcualations
*margin* (ndarray): Column margin for proportions (See `def _margin`)
*observed* (ndarray): Row margin proportions (See `def _observed`) | [
"return",
"ndarray",
"of",
"chi",
"-",
"squared",
"measures",
"for",
"proportions",
"columns",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/measures/wishart_pairwise_significance.py#L45-L61 | train | 37,105 |
Crunch-io/crunch-cube | src/cr/cube/measures/wishart_pairwise_significance.py | WishartPairwiseSignificance._pvals_from_chi_squared | def _pvals_from_chi_squared(self, pairwise_chisq):
"""return statistical significance for props' columns.
*pairwise_chisq* (ndarray) Matrix of chi-squared values (bases for Wishart CDF)
"""
return self._intersperse_insertion_rows_and_columns(
1.0 - WishartCDF(pairwise_chisq, self._n_min, self._n_max).values
) | python | def _pvals_from_chi_squared(self, pairwise_chisq):
"""return statistical significance for props' columns.
*pairwise_chisq* (ndarray) Matrix of chi-squared values (bases for Wishart CDF)
"""
return self._intersperse_insertion_rows_and_columns(
1.0 - WishartCDF(pairwise_chisq, self._n_min, self._n_max).values
) | [
"def",
"_pvals_from_chi_squared",
"(",
"self",
",",
"pairwise_chisq",
")",
":",
"return",
"self",
".",
"_intersperse_insertion_rows_and_columns",
"(",
"1.0",
"-",
"WishartCDF",
"(",
"pairwise_chisq",
",",
"self",
".",
"_n_min",
",",
"self",
".",
"_n_max",
")",
"... | return statistical significance for props' columns.
*pairwise_chisq* (ndarray) Matrix of chi-squared values (bases for Wishart CDF) | [
"return",
"statistical",
"significance",
"for",
"props",
"columns",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/measures/wishart_pairwise_significance.py#L76-L83 | train | 37,106 |
Crunch-io/crunch-cube | src/cr/cube/measures/wishart_pairwise_significance.py | WishartPairwiseSignificance._factory | def _factory(slice_, axis, weighted):
"""return subclass for PairwiseSignificance, based on slice dimension types."""
if slice_.dim_types[0] == DT.MR_SUBVAR:
return _MrXCatPairwiseSignificance(slice_, axis, weighted)
return _CatXCatPairwiseSignificance(slice_, axis, weighted) | python | def _factory(slice_, axis, weighted):
"""return subclass for PairwiseSignificance, based on slice dimension types."""
if slice_.dim_types[0] == DT.MR_SUBVAR:
return _MrXCatPairwiseSignificance(slice_, axis, weighted)
return _CatXCatPairwiseSignificance(slice_, axis, weighted) | [
"def",
"_factory",
"(",
"slice_",
",",
"axis",
",",
"weighted",
")",
":",
"if",
"slice_",
".",
"dim_types",
"[",
"0",
"]",
"==",
"DT",
".",
"MR_SUBVAR",
":",
"return",
"_MrXCatPairwiseSignificance",
"(",
"slice_",
",",
"axis",
",",
"weighted",
")",
"retu... | return subclass for PairwiseSignificance, based on slice dimension types. | [
"return",
"subclass",
"for",
"PairwiseSignificance",
"based",
"on",
"slice",
"dimension",
"types",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/measures/wishart_pairwise_significance.py#L86-L90 | train | 37,107 |
Crunch-io/crunch-cube | src/cr/cube/measures/wishart_pairwise_significance.py | WishartPairwiseSignificance._intersperse_insertion_rows_and_columns | def _intersperse_insertion_rows_and_columns(self, pairwise_pvals):
"""Return pvals matrix with inserted NaN rows and columns, as numpy.ndarray.
Each insertion (a header or a subtotal) creates an offset in the calculated
pvals. These need to be taken into account when converting each pval to a
corresponding column letter. For this reason, we need to insert an all-NaN
row and a column at the right indices. These are the inserted indices of each
insertion, along respective dimensions.
"""
for i in self._insertion_indices:
pairwise_pvals = np.insert(pairwise_pvals, i, np.nan, axis=0)
pairwise_pvals = np.insert(pairwise_pvals, i, np.nan, axis=1)
return pairwise_pvals | python | def _intersperse_insertion_rows_and_columns(self, pairwise_pvals):
"""Return pvals matrix with inserted NaN rows and columns, as numpy.ndarray.
Each insertion (a header or a subtotal) creates an offset in the calculated
pvals. These need to be taken into account when converting each pval to a
corresponding column letter. For this reason, we need to insert an all-NaN
row and a column at the right indices. These are the inserted indices of each
insertion, along respective dimensions.
"""
for i in self._insertion_indices:
pairwise_pvals = np.insert(pairwise_pvals, i, np.nan, axis=0)
pairwise_pvals = np.insert(pairwise_pvals, i, np.nan, axis=1)
return pairwise_pvals | [
"def",
"_intersperse_insertion_rows_and_columns",
"(",
"self",
",",
"pairwise_pvals",
")",
":",
"for",
"i",
"in",
"self",
".",
"_insertion_indices",
":",
"pairwise_pvals",
"=",
"np",
".",
"insert",
"(",
"pairwise_pvals",
",",
"i",
",",
"np",
".",
"nan",
",",
... | Return pvals matrix with inserted NaN rows and columns, as numpy.ndarray.
Each insertion (a header or a subtotal) creates an offset in the calculated
pvals. These need to be taken into account when converting each pval to a
corresponding column letter. For this reason, we need to insert an all-NaN
row and a column at the right indices. These are the inserted indices of each
insertion, along respective dimensions. | [
"Return",
"pvals",
"matrix",
"with",
"inserted",
"NaN",
"rows",
"and",
"columns",
"as",
"numpy",
".",
"ndarray",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/measures/wishart_pairwise_significance.py#L97-L109 | train | 37,108 |
Crunch-io/crunch-cube | src/cr/cube/measures/wishart_pairwise_significance.py | WishartPairwiseSignificance._opposite_axis_margin | def _opposite_axis_margin(self):
"""ndarray representing margin along the axis opposite of self._axis
In the process of calculating p-values for the column significance testing we
need both the margin along the primary axis and the percentage margin along
the opposite axis.
"""
off_axis = 1 - self._axis
return self._slice.margin(axis=off_axis, include_mr_cat=self._include_mr_cat) | python | def _opposite_axis_margin(self):
"""ndarray representing margin along the axis opposite of self._axis
In the process of calculating p-values for the column significance testing we
need both the margin along the primary axis and the percentage margin along
the opposite axis.
"""
off_axis = 1 - self._axis
return self._slice.margin(axis=off_axis, include_mr_cat=self._include_mr_cat) | [
"def",
"_opposite_axis_margin",
"(",
"self",
")",
":",
"off_axis",
"=",
"1",
"-",
"self",
".",
"_axis",
"return",
"self",
".",
"_slice",
".",
"margin",
"(",
"axis",
"=",
"off_axis",
",",
"include_mr_cat",
"=",
"self",
".",
"_include_mr_cat",
")"
] | ndarray representing margin along the axis opposite of self._axis
In the process of calculating p-values for the column significance testing we
need both the margin along the primary axis and the percentage margin along
the opposite axis. | [
"ndarray",
"representing",
"margin",
"along",
"the",
"axis",
"opposite",
"of",
"self",
".",
"_axis"
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/measures/wishart_pairwise_significance.py#L132-L140 | train | 37,109 |
Crunch-io/crunch-cube | src/cr/cube/measures/wishart_pairwise_significance.py | WishartPairwiseSignificance._proportions | def _proportions(self):
"""ndarray representing slice proportions along correct axis."""
return self._slice.proportions(
axis=self._axis, include_mr_cat=self._include_mr_cat
) | python | def _proportions(self):
"""ndarray representing slice proportions along correct axis."""
return self._slice.proportions(
axis=self._axis, include_mr_cat=self._include_mr_cat
) | [
"def",
"_proportions",
"(",
"self",
")",
":",
"return",
"self",
".",
"_slice",
".",
"proportions",
"(",
"axis",
"=",
"self",
".",
"_axis",
",",
"include_mr_cat",
"=",
"self",
".",
"_include_mr_cat",
")"
] | ndarray representing slice proportions along correct axis. | [
"ndarray",
"representing",
"slice",
"proportions",
"along",
"correct",
"axis",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/measures/wishart_pairwise_significance.py#L143-L147 | train | 37,110 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/calmar.py | build_dummies_dict | def build_dummies_dict(data):
"""
Return a dict with unique values as keys and vectors as values
"""
unique_val_list = unique(data)
output = {}
for val in unique_val_list:
output[val] = (data == val)
return output | python | def build_dummies_dict(data):
"""
Return a dict with unique values as keys and vectors as values
"""
unique_val_list = unique(data)
output = {}
for val in unique_val_list:
output[val] = (data == val)
return output | [
"def",
"build_dummies_dict",
"(",
"data",
")",
":",
"unique_val_list",
"=",
"unique",
"(",
"data",
")",
"output",
"=",
"{",
"}",
"for",
"val",
"in",
"unique_val_list",
":",
"output",
"[",
"val",
"]",
"=",
"(",
"data",
"==",
"val",
")",
"return",
"outpu... | Return a dict with unique values as keys and vectors as values | [
"Return",
"a",
"dict",
"with",
"unique",
"values",
"as",
"keys",
"and",
"vectors",
"as",
"values"
] | bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358 | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/calmar.py#L44-L52 | train | 37,111 |
Crunch-io/crunch-cube | src/cr/cube/cube_slice.py | CubeSlice.ca_main_axis | def ca_main_axis(self):
"""For univariate CA, the main axis is the categorical axis"""
try:
ca_ind = self.dim_types.index(DT.CA_SUBVAR)
return 1 - ca_ind
except ValueError:
return None | python | def ca_main_axis(self):
"""For univariate CA, the main axis is the categorical axis"""
try:
ca_ind = self.dim_types.index(DT.CA_SUBVAR)
return 1 - ca_ind
except ValueError:
return None | [
"def",
"ca_main_axis",
"(",
"self",
")",
":",
"try",
":",
"ca_ind",
"=",
"self",
".",
"dim_types",
".",
"index",
"(",
"DT",
".",
"CA_SUBVAR",
")",
"return",
"1",
"-",
"ca_ind",
"except",
"ValueError",
":",
"return",
"None"
] | For univariate CA, the main axis is the categorical axis | [
"For",
"univariate",
"CA",
"the",
"main",
"axis",
"is",
"the",
"categorical",
"axis"
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/cube_slice.py#L166-L172 | train | 37,112 |
Crunch-io/crunch-cube | src/cr/cube/cube_slice.py | CubeSlice.can_compare_pairwise | def can_compare_pairwise(self):
"""Return bool indicating if slice can compute pairwise comparisons.
Currently, only the CAT x CAT slice can compute pairwise comparisons. This also
includes the categorical array categories dimnension (CA_CAT).
"""
if self.ndim != 2:
return False
return all(dt in DT.ALLOWED_PAIRWISE_TYPES for dt in self.dim_types) | python | def can_compare_pairwise(self):
"""Return bool indicating if slice can compute pairwise comparisons.
Currently, only the CAT x CAT slice can compute pairwise comparisons. This also
includes the categorical array categories dimnension (CA_CAT).
"""
if self.ndim != 2:
return False
return all(dt in DT.ALLOWED_PAIRWISE_TYPES for dt in self.dim_types) | [
"def",
"can_compare_pairwise",
"(",
"self",
")",
":",
"if",
"self",
".",
"ndim",
"!=",
"2",
":",
"return",
"False",
"return",
"all",
"(",
"dt",
"in",
"DT",
".",
"ALLOWED_PAIRWISE_TYPES",
"for",
"dt",
"in",
"self",
".",
"dim_types",
")"
] | Return bool indicating if slice can compute pairwise comparisons.
Currently, only the CAT x CAT slice can compute pairwise comparisons. This also
includes the categorical array categories dimnension (CA_CAT). | [
"Return",
"bool",
"indicating",
"if",
"slice",
"can",
"compute",
"pairwise",
"comparisons",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/cube_slice.py#L180-L189 | train | 37,113 |
Crunch-io/crunch-cube | src/cr/cube/cube_slice.py | CubeSlice.get_shape | def get_shape(self, prune=False, hs_dims=None):
"""Tuple of array dimensions' lengths.
It returns a tuple of ints, each representing the length of a cube
dimension, in the order those dimensions appear in the cube.
Pruning is supported. Dimensions that get reduced to a single element
(e.g. due to pruning) are removed from the returning shape, thus
allowing for the differentiation between true 2D cubes (over which
statistical testing can be performed) and essentially
1D cubes (over which it can't).
Usage:
>>> shape = get_shape()
>>> pruned_shape = get_shape(prune=True)
"""
if not prune:
return self.as_array(include_transforms_for_dims=hs_dims).shape
shape = compress_pruned(
self.as_array(prune=True, include_transforms_for_dims=hs_dims)
).shape
# Eliminate dimensions that get reduced to 1
# (e.g. single element categoricals)
return tuple(n for n in shape if n > 1) | python | def get_shape(self, prune=False, hs_dims=None):
"""Tuple of array dimensions' lengths.
It returns a tuple of ints, each representing the length of a cube
dimension, in the order those dimensions appear in the cube.
Pruning is supported. Dimensions that get reduced to a single element
(e.g. due to pruning) are removed from the returning shape, thus
allowing for the differentiation between true 2D cubes (over which
statistical testing can be performed) and essentially
1D cubes (over which it can't).
Usage:
>>> shape = get_shape()
>>> pruned_shape = get_shape(prune=True)
"""
if not prune:
return self.as_array(include_transforms_for_dims=hs_dims).shape
shape = compress_pruned(
self.as_array(prune=True, include_transforms_for_dims=hs_dims)
).shape
# Eliminate dimensions that get reduced to 1
# (e.g. single element categoricals)
return tuple(n for n in shape if n > 1) | [
"def",
"get_shape",
"(",
"self",
",",
"prune",
"=",
"False",
",",
"hs_dims",
"=",
"None",
")",
":",
"if",
"not",
"prune",
":",
"return",
"self",
".",
"as_array",
"(",
"include_transforms_for_dims",
"=",
"hs_dims",
")",
".",
"shape",
"shape",
"=",
"compre... | Tuple of array dimensions' lengths.
It returns a tuple of ints, each representing the length of a cube
dimension, in the order those dimensions appear in the cube.
Pruning is supported. Dimensions that get reduced to a single element
(e.g. due to pruning) are removed from the returning shape, thus
allowing for the differentiation between true 2D cubes (over which
statistical testing can be performed) and essentially
1D cubes (over which it can't).
Usage:
>>> shape = get_shape()
>>> pruned_shape = get_shape(prune=True) | [
"Tuple",
"of",
"array",
"dimensions",
"lengths",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/cube_slice.py#L197-L221 | train | 37,114 |
Crunch-io/crunch-cube | src/cr/cube/cube_slice.py | CubeSlice.index_table | def index_table(self, axis=None, baseline=None, prune=False):
"""Return index percentages for a given axis and baseline.
The index values represent the difference of the percentages to the
corresponding baseline values. The baseline values are the univariate
percentages of the corresponding variable.
"""
proportions = self.proportions(axis=axis)
baseline = (
baseline if baseline is not None else self._prepare_index_baseline(axis)
)
# Fix the shape to enable correct broadcasting
if (
axis == 0
and len(baseline.shape) <= 1
and self.ndim == len(self.get_shape())
):
baseline = baseline[:, None]
indexes = proportions / baseline * 100
return self._apply_pruning_mask(indexes) if prune else indexes | python | def index_table(self, axis=None, baseline=None, prune=False):
"""Return index percentages for a given axis and baseline.
The index values represent the difference of the percentages to the
corresponding baseline values. The baseline values are the univariate
percentages of the corresponding variable.
"""
proportions = self.proportions(axis=axis)
baseline = (
baseline if baseline is not None else self._prepare_index_baseline(axis)
)
# Fix the shape to enable correct broadcasting
if (
axis == 0
and len(baseline.shape) <= 1
and self.ndim == len(self.get_shape())
):
baseline = baseline[:, None]
indexes = proportions / baseline * 100
return self._apply_pruning_mask(indexes) if prune else indexes | [
"def",
"index_table",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"baseline",
"=",
"None",
",",
"prune",
"=",
"False",
")",
":",
"proportions",
"=",
"self",
".",
"proportions",
"(",
"axis",
"=",
"axis",
")",
"baseline",
"=",
"(",
"baseline",
"if",
"b... | Return index percentages for a given axis and baseline.
The index values represent the difference of the percentages to the
corresponding baseline values. The baseline values are the univariate
percentages of the corresponding variable. | [
"Return",
"index",
"percentages",
"for",
"a",
"given",
"axis",
"and",
"baseline",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/cube_slice.py#L243-L265 | train | 37,115 |
Crunch-io/crunch-cube | src/cr/cube/cube_slice.py | CubeSlice.labels | def labels(self, hs_dims=None, prune=False):
"""Get labels for the cube slice, and perform pruning by slice."""
if self.ca_as_0th:
labels = self._cube.labels(include_transforms_for_dims=hs_dims)[1:]
else:
labels = self._cube.labels(include_transforms_for_dims=hs_dims)[-2:]
if not prune:
return labels
def prune_dimension_labels(labels, prune_indices):
"""Get pruned labels for single dimension, besed on prune inds."""
labels = [label for label, prune in zip(labels, prune_indices) if not prune]
return labels
labels = [
prune_dimension_labels(dim_labels, dim_prune_inds)
for dim_labels, dim_prune_inds in zip(labels, self._prune_indices(hs_dims))
]
return labels | python | def labels(self, hs_dims=None, prune=False):
"""Get labels for the cube slice, and perform pruning by slice."""
if self.ca_as_0th:
labels = self._cube.labels(include_transforms_for_dims=hs_dims)[1:]
else:
labels = self._cube.labels(include_transforms_for_dims=hs_dims)[-2:]
if not prune:
return labels
def prune_dimension_labels(labels, prune_indices):
"""Get pruned labels for single dimension, besed on prune inds."""
labels = [label for label, prune in zip(labels, prune_indices) if not prune]
return labels
labels = [
prune_dimension_labels(dim_labels, dim_prune_inds)
for dim_labels, dim_prune_inds in zip(labels, self._prune_indices(hs_dims))
]
return labels | [
"def",
"labels",
"(",
"self",
",",
"hs_dims",
"=",
"None",
",",
"prune",
"=",
"False",
")",
":",
"if",
"self",
".",
"ca_as_0th",
":",
"labels",
"=",
"self",
".",
"_cube",
".",
"labels",
"(",
"include_transforms_for_dims",
"=",
"hs_dims",
")",
"[",
"1",... | Get labels for the cube slice, and perform pruning by slice. | [
"Get",
"labels",
"for",
"the",
"cube",
"slice",
"and",
"perform",
"pruning",
"by",
"slice",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/cube_slice.py#L277-L296 | train | 37,116 |
Crunch-io/crunch-cube | src/cr/cube/cube_slice.py | CubeSlice.margin | def margin(
self,
axis=None,
weighted=True,
include_missing=False,
include_transforms_for_dims=None,
prune=False,
include_mr_cat=False,
):
"""Return ndarray representing slice margin across selected axis.
A margin (or basis) can be calculated for a contingency table, provided
that the dimensions of the desired directions are marginable. The
dimensions are marginable if they represent mutualy exclusive data,
such as true categorical data. For array types the items dimensions are
not marginable. Requesting a margin across these dimensions
(e.g. slice.margin(axis=0) for a categorical array cube slice) will
produce an error. For multiple response slices, the implicit convention
is that the provided direction scales to the selections dimension of the
slice. These cases produce meaningful data, but of a slightly different
shape (e.g. slice.margin(0) for a MR x CAT slice will produce 2D ndarray
(variable dimensions are never collapsed!)).
:param axis: Axis across which to sum. Can be 0 (columns margin),
1 (rows margin) and None (table margin). If requested across
variables dimension (e.g. requesting 0 margin for CA array) it will
produce an error.
:param weighted: Weighted or unweighted counts.
:param include_missing: Include missing categories or not.
:param include_transforms_for_dims: Indices of dimensions for which to
include transformations
:param prune: Perform pruning based on unweighted counts.
:returns: (weighed or unweighted counts) summed across provided axis.
For multiple response types, items dimensions are not collapsed.
"""
axis = self._calculate_correct_axis_for_cube(axis)
hs_dims = self._hs_dims_for_cube(include_transforms_for_dims)
margin = self._cube.margin(
axis=axis,
weighted=weighted,
include_missing=include_missing,
include_transforms_for_dims=hs_dims,
prune=prune,
include_mr_cat=include_mr_cat,
)
return self._extract_slice_result_from_cube(margin) | python | def margin(
self,
axis=None,
weighted=True,
include_missing=False,
include_transforms_for_dims=None,
prune=False,
include_mr_cat=False,
):
"""Return ndarray representing slice margin across selected axis.
A margin (or basis) can be calculated for a contingency table, provided
that the dimensions of the desired directions are marginable. The
dimensions are marginable if they represent mutualy exclusive data,
such as true categorical data. For array types the items dimensions are
not marginable. Requesting a margin across these dimensions
(e.g. slice.margin(axis=0) for a categorical array cube slice) will
produce an error. For multiple response slices, the implicit convention
is that the provided direction scales to the selections dimension of the
slice. These cases produce meaningful data, but of a slightly different
shape (e.g. slice.margin(0) for a MR x CAT slice will produce 2D ndarray
(variable dimensions are never collapsed!)).
:param axis: Axis across which to sum. Can be 0 (columns margin),
1 (rows margin) and None (table margin). If requested across
variables dimension (e.g. requesting 0 margin for CA array) it will
produce an error.
:param weighted: Weighted or unweighted counts.
:param include_missing: Include missing categories or not.
:param include_transforms_for_dims: Indices of dimensions for which to
include transformations
:param prune: Perform pruning based on unweighted counts.
:returns: (weighed or unweighted counts) summed across provided axis.
For multiple response types, items dimensions are not collapsed.
"""
axis = self._calculate_correct_axis_for_cube(axis)
hs_dims = self._hs_dims_for_cube(include_transforms_for_dims)
margin = self._cube.margin(
axis=axis,
weighted=weighted,
include_missing=include_missing,
include_transforms_for_dims=hs_dims,
prune=prune,
include_mr_cat=include_mr_cat,
)
return self._extract_slice_result_from_cube(margin) | [
"def",
"margin",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"weighted",
"=",
"True",
",",
"include_missing",
"=",
"False",
",",
"include_transforms_for_dims",
"=",
"None",
",",
"prune",
"=",
"False",
",",
"include_mr_cat",
"=",
"False",
",",
")",
":",
"... | Return ndarray representing slice margin across selected axis.
A margin (or basis) can be calculated for a contingency table, provided
that the dimensions of the desired directions are marginable. The
dimensions are marginable if they represent mutualy exclusive data,
such as true categorical data. For array types the items dimensions are
not marginable. Requesting a margin across these dimensions
(e.g. slice.margin(axis=0) for a categorical array cube slice) will
produce an error. For multiple response slices, the implicit convention
is that the provided direction scales to the selections dimension of the
slice. These cases produce meaningful data, but of a slightly different
shape (e.g. slice.margin(0) for a MR x CAT slice will produce 2D ndarray
(variable dimensions are never collapsed!)).
:param axis: Axis across which to sum. Can be 0 (columns margin),
1 (rows margin) and None (table margin). If requested across
variables dimension (e.g. requesting 0 margin for CA array) it will
produce an error.
:param weighted: Weighted or unweighted counts.
:param include_missing: Include missing categories or not.
:param include_transforms_for_dims: Indices of dimensions for which to
include transformations
:param prune: Perform pruning based on unweighted counts.
:returns: (weighed or unweighted counts) summed across provided axis.
For multiple response types, items dimensions are not collapsed. | [
"Return",
"ndarray",
"representing",
"slice",
"margin",
"across",
"selected",
"axis",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/cube_slice.py#L298-L346 | train | 37,117 |
Crunch-io/crunch-cube | src/cr/cube/cube_slice.py | CubeSlice.min_base_size_mask | def min_base_size_mask(self, size, hs_dims=None, prune=False):
"""Returns MinBaseSizeMask object with correct row, col and table masks.
The returned object stores the necessary information about the base size, as
well as about the base values. It can create corresponding masks in teh row,
column, and table directions, based on the corresponding base values
(the values of the unweighted margins).
Usage:
>>> cube_slice = CrunchCube(response).slices[0] # obtain a valid cube slice
>>> cube_slice.min_base_size_mask(30).row_mask
>>> cube_slice.min_base_size_mask(50).column_mask
>>> cube_slice.min_base_size_mask(22).table_mask
"""
return MinBaseSizeMask(self, size, hs_dims=hs_dims, prune=prune) | python | def min_base_size_mask(self, size, hs_dims=None, prune=False):
"""Returns MinBaseSizeMask object with correct row, col and table masks.
The returned object stores the necessary information about the base size, as
well as about the base values. It can create corresponding masks in teh row,
column, and table directions, based on the corresponding base values
(the values of the unweighted margins).
Usage:
>>> cube_slice = CrunchCube(response).slices[0] # obtain a valid cube slice
>>> cube_slice.min_base_size_mask(30).row_mask
>>> cube_slice.min_base_size_mask(50).column_mask
>>> cube_slice.min_base_size_mask(22).table_mask
"""
return MinBaseSizeMask(self, size, hs_dims=hs_dims, prune=prune) | [
"def",
"min_base_size_mask",
"(",
"self",
",",
"size",
",",
"hs_dims",
"=",
"None",
",",
"prune",
"=",
"False",
")",
":",
"return",
"MinBaseSizeMask",
"(",
"self",
",",
"size",
",",
"hs_dims",
"=",
"hs_dims",
",",
"prune",
"=",
"prune",
")"
] | Returns MinBaseSizeMask object with correct row, col and table masks.
The returned object stores the necessary information about the base size, as
well as about the base values. It can create corresponding masks in teh row,
column, and table directions, based on the corresponding base values
(the values of the unweighted margins).
Usage:
>>> cube_slice = CrunchCube(response).slices[0] # obtain a valid cube slice
>>> cube_slice.min_base_size_mask(30).row_mask
>>> cube_slice.min_base_size_mask(50).column_mask
>>> cube_slice.min_base_size_mask(22).table_mask | [
"Returns",
"MinBaseSizeMask",
"object",
"with",
"correct",
"row",
"col",
"and",
"table",
"masks",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/cube_slice.py#L348-L362 | train | 37,118 |
Crunch-io/crunch-cube | src/cr/cube/cube_slice.py | CubeSlice.mr_dim_ind | def mr_dim_ind(self):
"""Get the correct index of the MR dimension in the cube slice."""
mr_dim_ind = self._cube.mr_dim_ind
if self._cube.ndim == 3:
if isinstance(mr_dim_ind, int):
if mr_dim_ind == 0:
# If only the 0th dimension of a 3D is an MR, the sliced
# don't actuall have the MR... Thus return None.
return None
return mr_dim_ind - 1
elif isinstance(mr_dim_ind, tuple):
# If MR dimension index is a tuple, that means that the cube
# (only a 3D one if it reached this path) has 2 MR dimensions.
# If any of those is 0 ind dimension we don't need to include
# in the slice dimension (because the slice doesn't see the tab
# that it's on). If it's 1st and 2nd dimension, then subtract 1
# from those, and present them as 0th and 1st dimension of the
# slice. This can happend e.g. in a CAT x MR x MR cube (which
# renders MR x MR slices).
mr_dim_ind = tuple(i - 1 for i in mr_dim_ind if i)
return mr_dim_ind if len(mr_dim_ind) > 1 else mr_dim_ind[0]
return mr_dim_ind | python | def mr_dim_ind(self):
"""Get the correct index of the MR dimension in the cube slice."""
mr_dim_ind = self._cube.mr_dim_ind
if self._cube.ndim == 3:
if isinstance(mr_dim_ind, int):
if mr_dim_ind == 0:
# If only the 0th dimension of a 3D is an MR, the sliced
# don't actuall have the MR... Thus return None.
return None
return mr_dim_ind - 1
elif isinstance(mr_dim_ind, tuple):
# If MR dimension index is a tuple, that means that the cube
# (only a 3D one if it reached this path) has 2 MR dimensions.
# If any of those is 0 ind dimension we don't need to include
# in the slice dimension (because the slice doesn't see the tab
# that it's on). If it's 1st and 2nd dimension, then subtract 1
# from those, and present them as 0th and 1st dimension of the
# slice. This can happend e.g. in a CAT x MR x MR cube (which
# renders MR x MR slices).
mr_dim_ind = tuple(i - 1 for i in mr_dim_ind if i)
return mr_dim_ind if len(mr_dim_ind) > 1 else mr_dim_ind[0]
return mr_dim_ind | [
"def",
"mr_dim_ind",
"(",
"self",
")",
":",
"mr_dim_ind",
"=",
"self",
".",
"_cube",
".",
"mr_dim_ind",
"if",
"self",
".",
"_cube",
".",
"ndim",
"==",
"3",
":",
"if",
"isinstance",
"(",
"mr_dim_ind",
",",
"int",
")",
":",
"if",
"mr_dim_ind",
"==",
"0... | Get the correct index of the MR dimension in the cube slice. | [
"Get",
"the",
"correct",
"index",
"of",
"the",
"MR",
"dimension",
"in",
"the",
"cube",
"slice",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/cube_slice.py#L365-L387 | train | 37,119 |
Crunch-io/crunch-cube | src/cr/cube/cube_slice.py | CubeSlice.scale_means | def scale_means(self, hs_dims=None, prune=False):
"""Return list of column and row scaled means for this slice.
If a row/col doesn't have numerical values, return None for the
corresponding dimension. If a slice only has 1D, return only the column
scaled mean (as numpy array). If both row and col scaled means are
present, return them as two numpy arrays inside of a list.
"""
scale_means = self._cube.scale_means(hs_dims, prune)
if self.ca_as_0th:
# If slice is used as 0th CA, then we need to observe the 1st dimension,
# because the 0th dimension is CA items, which is only used for slicing
# (and thus doesn't have numerical values, and also doesn't constitute any
# dimension of the actual crosstabs that will be created in this case).
scale_means = scale_means[0][-1]
if scale_means is None:
return [None]
return [scale_means[self._index]]
return scale_means[self._index] | python | def scale_means(self, hs_dims=None, prune=False):
"""Return list of column and row scaled means for this slice.
If a row/col doesn't have numerical values, return None for the
corresponding dimension. If a slice only has 1D, return only the column
scaled mean (as numpy array). If both row and col scaled means are
present, return them as two numpy arrays inside of a list.
"""
scale_means = self._cube.scale_means(hs_dims, prune)
if self.ca_as_0th:
# If slice is used as 0th CA, then we need to observe the 1st dimension,
# because the 0th dimension is CA items, which is only used for slicing
# (and thus doesn't have numerical values, and also doesn't constitute any
# dimension of the actual crosstabs that will be created in this case).
scale_means = scale_means[0][-1]
if scale_means is None:
return [None]
return [scale_means[self._index]]
return scale_means[self._index] | [
"def",
"scale_means",
"(",
"self",
",",
"hs_dims",
"=",
"None",
",",
"prune",
"=",
"False",
")",
":",
"scale_means",
"=",
"self",
".",
"_cube",
".",
"scale_means",
"(",
"hs_dims",
",",
"prune",
")",
"if",
"self",
".",
"ca_as_0th",
":",
"# If slice is use... | Return list of column and row scaled means for this slice.
If a row/col doesn't have numerical values, return None for the
corresponding dimension. If a slice only has 1D, return only the column
scaled mean (as numpy array). If both row and col scaled means are
present, return them as two numpy arrays inside of a list. | [
"Return",
"list",
"of",
"column",
"and",
"row",
"scaled",
"means",
"for",
"this",
"slice",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/cube_slice.py#L399-L419 | train | 37,120 |
Crunch-io/crunch-cube | src/cr/cube/cube_slice.py | CubeSlice.table_name | def table_name(self):
"""Get slice name.
In case of 2D return cube name. In case of 3D, return the combination
of the cube name with the label of the corresponding slice
(nth label of the 0th dimension).
"""
if self._cube.ndim < 3 and not self.ca_as_0th:
return None
title = self._cube.name
table_name = self._cube.labels()[0][self._index]
return "%s: %s" % (title, table_name) | python | def table_name(self):
"""Get slice name.
In case of 2D return cube name. In case of 3D, return the combination
of the cube name with the label of the corresponding slice
(nth label of the 0th dimension).
"""
if self._cube.ndim < 3 and not self.ca_as_0th:
return None
title = self._cube.name
table_name = self._cube.labels()[0][self._index]
return "%s: %s" % (title, table_name) | [
"def",
"table_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cube",
".",
"ndim",
"<",
"3",
"and",
"not",
"self",
".",
"ca_as_0th",
":",
"return",
"None",
"title",
"=",
"self",
".",
"_cube",
".",
"name",
"table_name",
"=",
"self",
".",
"_cube",
... | Get slice name.
In case of 2D return cube name. In case of 3D, return the combination
of the cube name with the label of the corresponding slice
(nth label of the 0th dimension). | [
"Get",
"slice",
"name",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/cube_slice.py#L448-L460 | train | 37,121 |
Crunch-io/crunch-cube | src/cr/cube/cube_slice.py | CubeSlice.wishart_pairwise_pvals | def wishart_pairwise_pvals(self, axis=0):
"""Return square symmetric matrix of pairwise column-comparison p-values.
Square, symmetric matrix along *axis* of pairwise p-values for the
null hypothesis that col[i] = col[j] for each pair of columns.
*axis* (int): axis along which to perform comparison. Only columns (0)
are implemented currently.
"""
if axis != 0:
raise NotImplementedError("Pairwise comparison only implemented for colums")
return WishartPairwiseSignificance.pvals(self, axis=axis) | python | def wishart_pairwise_pvals(self, axis=0):
"""Return square symmetric matrix of pairwise column-comparison p-values.
Square, symmetric matrix along *axis* of pairwise p-values for the
null hypothesis that col[i] = col[j] for each pair of columns.
*axis* (int): axis along which to perform comparison. Only columns (0)
are implemented currently.
"""
if axis != 0:
raise NotImplementedError("Pairwise comparison only implemented for colums")
return WishartPairwiseSignificance.pvals(self, axis=axis) | [
"def",
"wishart_pairwise_pvals",
"(",
"self",
",",
"axis",
"=",
"0",
")",
":",
"if",
"axis",
"!=",
"0",
":",
"raise",
"NotImplementedError",
"(",
"\"Pairwise comparison only implemented for colums\"",
")",
"return",
"WishartPairwiseSignificance",
".",
"pvals",
"(",
... | Return square symmetric matrix of pairwise column-comparison p-values.
Square, symmetric matrix along *axis* of pairwise p-values for the
null hypothesis that col[i] = col[j] for each pair of columns.
*axis* (int): axis along which to perform comparison. Only columns (0)
are implemented currently. | [
"Return",
"square",
"symmetric",
"matrix",
"of",
"pairwise",
"column",
"-",
"comparison",
"p",
"-",
"values",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/cube_slice.py#L462-L473 | train | 37,122 |
Crunch-io/crunch-cube | src/cr/cube/cube_slice.py | CubeSlice.pvals | def pvals(self, weighted=True, prune=False, hs_dims=None):
"""Return 2D ndarray with calculated P values
This function calculates statistically significant cells for
categorical contingency tables under the null hypothesis that the
row and column variables are independent (uncorrelated).
The values are calculated for 2D tables only.
:param weighted: Use weighted counts for zscores
:param prune: Prune based on unweighted counts
:param hs_dims: Include headers and subtotals (as NaN values)
:returns: 2 or 3 Dimensional ndarray, representing the p-values for each
cell of the table-like representation of the crunch cube.
"""
stats = self.zscore(weighted=weighted, prune=prune, hs_dims=hs_dims)
pvals = 2 * (1 - norm.cdf(np.abs(stats)))
return self._apply_pruning_mask(pvals, hs_dims) if prune else pvals | python | def pvals(self, weighted=True, prune=False, hs_dims=None):
"""Return 2D ndarray with calculated P values
This function calculates statistically significant cells for
categorical contingency tables under the null hypothesis that the
row and column variables are independent (uncorrelated).
The values are calculated for 2D tables only.
:param weighted: Use weighted counts for zscores
:param prune: Prune based on unweighted counts
:param hs_dims: Include headers and subtotals (as NaN values)
:returns: 2 or 3 Dimensional ndarray, representing the p-values for each
cell of the table-like representation of the crunch cube.
"""
stats = self.zscore(weighted=weighted, prune=prune, hs_dims=hs_dims)
pvals = 2 * (1 - norm.cdf(np.abs(stats)))
return self._apply_pruning_mask(pvals, hs_dims) if prune else pvals | [
"def",
"pvals",
"(",
"self",
",",
"weighted",
"=",
"True",
",",
"prune",
"=",
"False",
",",
"hs_dims",
"=",
"None",
")",
":",
"stats",
"=",
"self",
".",
"zscore",
"(",
"weighted",
"=",
"weighted",
",",
"prune",
"=",
"prune",
",",
"hs_dims",
"=",
"h... | Return 2D ndarray with calculated P values
This function calculates statistically significant cells for
categorical contingency tables under the null hypothesis that the
row and column variables are independent (uncorrelated).
The values are calculated for 2D tables only.
:param weighted: Use weighted counts for zscores
:param prune: Prune based on unweighted counts
:param hs_dims: Include headers and subtotals (as NaN values)
:returns: 2 or 3 Dimensional ndarray, representing the p-values for each
cell of the table-like representation of the crunch cube. | [
"Return",
"2D",
"ndarray",
"with",
"calculated",
"P",
"values"
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/cube_slice.py#L501-L518 | train | 37,123 |
Crunch-io/crunch-cube | src/cr/cube/cube_slice.py | CubeSlice.pairwise_indices | def pairwise_indices(self, alpha=0.05, only_larger=True, hs_dims=None):
"""Indices of columns where p < alpha for column-comparison t-tests
Returns an array of tuples of columns that are significant at p<alpha,
from a series of pairwise t-tests.
Argument both_pairs returns indices striclty on the test statistic. If
False, however, only the index of values *significantly smaller* than
each cell are indicated.
"""
return PairwiseSignificance(
self, alpha=alpha, only_larger=only_larger, hs_dims=hs_dims
).pairwise_indices | python | def pairwise_indices(self, alpha=0.05, only_larger=True, hs_dims=None):
"""Indices of columns where p < alpha for column-comparison t-tests
Returns an array of tuples of columns that are significant at p<alpha,
from a series of pairwise t-tests.
Argument both_pairs returns indices striclty on the test statistic. If
False, however, only the index of values *significantly smaller* than
each cell are indicated.
"""
return PairwiseSignificance(
self, alpha=alpha, only_larger=only_larger, hs_dims=hs_dims
).pairwise_indices | [
"def",
"pairwise_indices",
"(",
"self",
",",
"alpha",
"=",
"0.05",
",",
"only_larger",
"=",
"True",
",",
"hs_dims",
"=",
"None",
")",
":",
"return",
"PairwiseSignificance",
"(",
"self",
",",
"alpha",
"=",
"alpha",
",",
"only_larger",
"=",
"only_larger",
",... | Indices of columns where p < alpha for column-comparison t-tests
Returns an array of tuples of columns that are significant at p<alpha,
from a series of pairwise t-tests.
Argument both_pairs returns indices striclty on the test statistic. If
False, however, only the index of values *significantly smaller* than
each cell are indicated. | [
"Indices",
"of",
"columns",
"where",
"p",
"<",
"alpha",
"for",
"column",
"-",
"comparison",
"t",
"-",
"tests"
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/cube_slice.py#L552-L564 | train | 37,124 |
Crunch-io/crunch-cube | src/cr/cube/cube_slice.py | CubeSlice._array_type_std_res | def _array_type_std_res(self, counts, total, colsum, rowsum):
"""Return ndarray containing standard residuals for array values.
The shape of the return value is the same as that of *counts*.
Array variables require special processing because of the
underlying math. Essentially, it boils down to the fact that the
variable dimensions are mutually independent, and standard residuals
are calculated for each of them separately, and then stacked together
in the resulting array.
"""
if self.mr_dim_ind == 0:
# --This is a special case where broadcasting cannot be
# --automatically done. We need to "inflate" the single dimensional
# --ndarrays, to be able to treat them as "columns" (essentially a
# --Nx1 ndarray). This is needed for subsequent multiplication
# --that needs to happen column wise (rowsum * colsum) / total.
total = total[:, np.newaxis]
rowsum = rowsum[:, np.newaxis]
expected_counts = rowsum * colsum / total
variance = rowsum * colsum * (total - rowsum) * (total - colsum) / total ** 3
return (counts - expected_counts) / np.sqrt(variance) | python | def _array_type_std_res(self, counts, total, colsum, rowsum):
"""Return ndarray containing standard residuals for array values.
The shape of the return value is the same as that of *counts*.
Array variables require special processing because of the
underlying math. Essentially, it boils down to the fact that the
variable dimensions are mutually independent, and standard residuals
are calculated for each of them separately, and then stacked together
in the resulting array.
"""
if self.mr_dim_ind == 0:
# --This is a special case where broadcasting cannot be
# --automatically done. We need to "inflate" the single dimensional
# --ndarrays, to be able to treat them as "columns" (essentially a
# --Nx1 ndarray). This is needed for subsequent multiplication
# --that needs to happen column wise (rowsum * colsum) / total.
total = total[:, np.newaxis]
rowsum = rowsum[:, np.newaxis]
expected_counts = rowsum * colsum / total
variance = rowsum * colsum * (total - rowsum) * (total - colsum) / total ** 3
return (counts - expected_counts) / np.sqrt(variance) | [
"def",
"_array_type_std_res",
"(",
"self",
",",
"counts",
",",
"total",
",",
"colsum",
",",
"rowsum",
")",
":",
"if",
"self",
".",
"mr_dim_ind",
"==",
"0",
":",
"# --This is a special case where broadcasting cannot be",
"# --automatically done. We need to \"inflate\" the ... | Return ndarray containing standard residuals for array values.
The shape of the return value is the same as that of *counts*.
Array variables require special processing because of the
underlying math. Essentially, it boils down to the fact that the
variable dimensions are mutually independent, and standard residuals
are calculated for each of them separately, and then stacked together
in the resulting array. | [
"Return",
"ndarray",
"containing",
"standard",
"residuals",
"for",
"array",
"values",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/cube_slice.py#L588-L609 | train | 37,125 |
Crunch-io/crunch-cube | src/cr/cube/cube_slice.py | CubeSlice._calculate_std_res | def _calculate_std_res(self, counts, total, colsum, rowsum):
"""Return ndarray containing standard residuals.
The shape of the return value is the same as that of *counts*.
"""
if set(self.dim_types) & DT.ARRAY_TYPES: # ---has-mr-or-ca---
return self._array_type_std_res(counts, total, colsum, rowsum)
return self._scalar_type_std_res(counts, total, colsum, rowsum) | python | def _calculate_std_res(self, counts, total, colsum, rowsum):
"""Return ndarray containing standard residuals.
The shape of the return value is the same as that of *counts*.
"""
if set(self.dim_types) & DT.ARRAY_TYPES: # ---has-mr-or-ca---
return self._array_type_std_res(counts, total, colsum, rowsum)
return self._scalar_type_std_res(counts, total, colsum, rowsum) | [
"def",
"_calculate_std_res",
"(",
"self",
",",
"counts",
",",
"total",
",",
"colsum",
",",
"rowsum",
")",
":",
"if",
"set",
"(",
"self",
".",
"dim_types",
")",
"&",
"DT",
".",
"ARRAY_TYPES",
":",
"# ---has-mr-or-ca---",
"return",
"self",
".",
"_array_type_... | Return ndarray containing standard residuals.
The shape of the return value is the same as that of *counts*. | [
"Return",
"ndarray",
"containing",
"standard",
"residuals",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/cube_slice.py#L611-L618 | train | 37,126 |
Crunch-io/crunch-cube | src/cr/cube/cube_slice.py | CubeSlice._calculate_correct_axis_for_cube | def _calculate_correct_axis_for_cube(self, axis):
"""Return correct axis for cube, based on ndim.
If cube has 3 dimensions, increase axis by 1. This will translate the
default 0 (cols direction) and 1 (rows direction) to actual 1
(cols direction) and 2 (rows direction). This is needed because the
0th dimension of the 3D cube is only used to slice across. The actual
margins need to be calculated for each slice separately, and since
they're implemented as an ndarray, the direction needs to be increased
by one. For the value of `None`, don't modify the axis parameter.
:param axis: 0, 1, or None. Axis that will be passed to self._cube
methods. If the cube is 3D, the axis is typically
increased by 1, to represent correct measure direction.
:returns: int or None, representing the updated axis to pass to cube
"""
if self._cube.ndim < 3:
if self.ca_as_0th and axis is None:
# Special case for CA slices (in multitables). In this case,
# we need to calculate a measurement across CA categories
# dimension (and not across items, because it's not
# allowed). The value for the axis parameter of None, would
# imply both cat and items dimensions, and we don't want that.
return 1
return axis
# Expected usage of the 'axis' parameter from CubeSlice is 0, 1, or
# None. CrunchCube handles all other logic. The only 'smart' thing
# about the handling here, is that the axes are increased for 3D cubes.
# This way the 3Dness is hidden from the user and he still sees 2D
# crosstabs, with col and row axes (0 and 1), which are transformed to
# corresponding numbers in case of 3D cubes (namely 1 and 2). In the
# case of None, we need to analyze across all valid dimensions, and the
# CrunchCube takes care of that (no need to update axis if it's None).
# If the user provides a tuple, it's considered that he "knows" what
# he's doing, and the axis argument is not updated in this case.
if isinstance(axis, int):
axis += 1
return axis | python | def _calculate_correct_axis_for_cube(self, axis):
"""Return correct axis for cube, based on ndim.
If cube has 3 dimensions, increase axis by 1. This will translate the
default 0 (cols direction) and 1 (rows direction) to actual 1
(cols direction) and 2 (rows direction). This is needed because the
0th dimension of the 3D cube is only used to slice across. The actual
margins need to be calculated for each slice separately, and since
they're implemented as an ndarray, the direction needs to be increased
by one. For the value of `None`, don't modify the axis parameter.
:param axis: 0, 1, or None. Axis that will be passed to self._cube
methods. If the cube is 3D, the axis is typically
increased by 1, to represent correct measure direction.
:returns: int or None, representing the updated axis to pass to cube
"""
if self._cube.ndim < 3:
if self.ca_as_0th and axis is None:
# Special case for CA slices (in multitables). In this case,
# we need to calculate a measurement across CA categories
# dimension (and not across items, because it's not
# allowed). The value for the axis parameter of None, would
# imply both cat and items dimensions, and we don't want that.
return 1
return axis
# Expected usage of the 'axis' parameter from CubeSlice is 0, 1, or
# None. CrunchCube handles all other logic. The only 'smart' thing
# about the handling here, is that the axes are increased for 3D cubes.
# This way the 3Dness is hidden from the user and he still sees 2D
# crosstabs, with col and row axes (0 and 1), which are transformed to
# corresponding numbers in case of 3D cubes (namely 1 and 2). In the
# case of None, we need to analyze across all valid dimensions, and the
# CrunchCube takes care of that (no need to update axis if it's None).
# If the user provides a tuple, it's considered that he "knows" what
# he's doing, and the axis argument is not updated in this case.
if isinstance(axis, int):
axis += 1
return axis | [
"def",
"_calculate_correct_axis_for_cube",
"(",
"self",
",",
"axis",
")",
":",
"if",
"self",
".",
"_cube",
".",
"ndim",
"<",
"3",
":",
"if",
"self",
".",
"ca_as_0th",
"and",
"axis",
"is",
"None",
":",
"# Special case for CA slices (in multitables). In this case,",... | Return correct axis for cube, based on ndim.
If cube has 3 dimensions, increase axis by 1. This will translate the
default 0 (cols direction) and 1 (rows direction) to actual 1
(cols direction) and 2 (rows direction). This is needed because the
0th dimension of the 3D cube is only used to slice across. The actual
margins need to be calculated for each slice separately, and since
they're implemented as an ndarray, the direction needs to be increased
by one. For the value of `None`, don't modify the axis parameter.
:param axis: 0, 1, or None. Axis that will be passed to self._cube
methods. If the cube is 3D, the axis is typically
increased by 1, to represent correct measure direction.
:returns: int or None, representing the updated axis to pass to cube | [
"Return",
"correct",
"axis",
"for",
"cube",
"based",
"on",
"ndim",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/cube_slice.py#L620-L659 | train | 37,127 |
Crunch-io/crunch-cube | src/cr/cube/cube_slice.py | CubeSlice._scalar_type_std_res | def _scalar_type_std_res(self, counts, total, colsum, rowsum):
"""Return ndarray containing standard residuals for category values.
The shape of the return value is the same as that of *counts*.
"""
expected_counts = expected_freq(counts)
residuals = counts - expected_counts
variance = (
np.outer(rowsum, colsum)
* np.outer(total - rowsum, total - colsum)
/ total ** 3
)
return residuals / np.sqrt(variance) | python | def _scalar_type_std_res(self, counts, total, colsum, rowsum):
"""Return ndarray containing standard residuals for category values.
The shape of the return value is the same as that of *counts*.
"""
expected_counts = expected_freq(counts)
residuals = counts - expected_counts
variance = (
np.outer(rowsum, colsum)
* np.outer(total - rowsum, total - colsum)
/ total ** 3
)
return residuals / np.sqrt(variance) | [
"def",
"_scalar_type_std_res",
"(",
"self",
",",
"counts",
",",
"total",
",",
"colsum",
",",
"rowsum",
")",
":",
"expected_counts",
"=",
"expected_freq",
"(",
"counts",
")",
"residuals",
"=",
"counts",
"-",
"expected_counts",
"variance",
"=",
"(",
"np",
".",... | Return ndarray containing standard residuals for category values.
The shape of the return value is the same as that of *counts*. | [
"Return",
"ndarray",
"containing",
"standard",
"residuals",
"for",
"category",
"values",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/cube_slice.py#L709-L721 | train | 37,128 |
Crunch-io/crunch-cube | src/cr/cube/measures/scale_means.py | ScaleMeans.data | def data(self):
"""list of mean numeric values of categorical responses."""
means = []
table = self._slice.as_array()
products = self._inner_prods(table, self.values)
for axis, product in enumerate(products):
if product is None:
means.append(product)
continue
# Calculate means
valid_indices = self._valid_indices(axis)
num = np.sum(product[valid_indices], axis)
den = np.sum(table[valid_indices], axis)
mean = num / den
if not isinstance(mean, np.ndarray):
mean = np.array([mean])
means.append(mean)
return means | python | def data(self):
"""list of mean numeric values of categorical responses."""
means = []
table = self._slice.as_array()
products = self._inner_prods(table, self.values)
for axis, product in enumerate(products):
if product is None:
means.append(product)
continue
# Calculate means
valid_indices = self._valid_indices(axis)
num = np.sum(product[valid_indices], axis)
den = np.sum(table[valid_indices], axis)
mean = num / den
if not isinstance(mean, np.ndarray):
mean = np.array([mean])
means.append(mean)
return means | [
"def",
"data",
"(",
"self",
")",
":",
"means",
"=",
"[",
"]",
"table",
"=",
"self",
".",
"_slice",
".",
"as_array",
"(",
")",
"products",
"=",
"self",
".",
"_inner_prods",
"(",
"table",
",",
"self",
".",
"values",
")",
"for",
"axis",
",",
"product"... | list of mean numeric values of categorical responses. | [
"list",
"of",
"mean",
"numeric",
"values",
"of",
"categorical",
"responses",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/measures/scale_means.py#L33-L52 | train | 37,129 |
Crunch-io/crunch-cube | src/cr/cube/measures/scale_means.py | ScaleMeans.margin | def margin(self, axis):
"""Return marginal value of the current slice scaled means.
This value is the the same what you would get from a single variable
(constituting a 2D cube/slice), when the "non-missing" filter of the
opposite variable would be applied. This behavior is consistent with
what is visible in the front-end client.
"""
if self._slice.ndim < 2:
msg = (
"Scale Means marginal cannot be calculated on 1D cubes, as"
"the scale means already get reduced to a scalar value."
)
raise ValueError(msg)
dimension_index = 1 - axis
margin = self._slice.margin(axis=axis)
if len(margin.shape) > 1:
index = [
0 if d.dimension_type == DT.MR else slice(None)
for d in self._slice.dimensions
]
margin = margin[index]
total = np.sum(margin)
values = self.values[dimension_index]
if values is None:
return None
return np.sum(values * margin) / total | python | def margin(self, axis):
"""Return marginal value of the current slice scaled means.
This value is the the same what you would get from a single variable
(constituting a 2D cube/slice), when the "non-missing" filter of the
opposite variable would be applied. This behavior is consistent with
what is visible in the front-end client.
"""
if self._slice.ndim < 2:
msg = (
"Scale Means marginal cannot be calculated on 1D cubes, as"
"the scale means already get reduced to a scalar value."
)
raise ValueError(msg)
dimension_index = 1 - axis
margin = self._slice.margin(axis=axis)
if len(margin.shape) > 1:
index = [
0 if d.dimension_type == DT.MR else slice(None)
for d in self._slice.dimensions
]
margin = margin[index]
total = np.sum(margin)
values = self.values[dimension_index]
if values is None:
return None
return np.sum(values * margin) / total | [
"def",
"margin",
"(",
"self",
",",
"axis",
")",
":",
"if",
"self",
".",
"_slice",
".",
"ndim",
"<",
"2",
":",
"msg",
"=",
"(",
"\"Scale Means marginal cannot be calculated on 1D cubes, as\"",
"\"the scale means already get reduced to a scalar value.\"",
")",
"raise",
... | Return marginal value of the current slice scaled means.
This value is the the same what you would get from a single variable
(constituting a 2D cube/slice), when the "non-missing" filter of the
opposite variable would be applied. This behavior is consistent with
what is visible in the front-end client. | [
"Return",
"marginal",
"value",
"of",
"the",
"current",
"slice",
"scaled",
"means",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/measures/scale_means.py#L54-L83 | train | 37,130 |
Crunch-io/crunch-cube | src/cr/cube/measures/scale_means.py | ScaleMeans.values | def values(self):
"""list of ndarray value-ids for each dimension in slice.
The values for each dimension appear as an ndarray. None appears
instead of the array for each dimension having only NaN values.
"""
return [
(
np.array(dim.numeric_values)
if (dim.numeric_values and any(~np.isnan(dim.numeric_values)))
else None
)
for dim in self._slice.dimensions
] | python | def values(self):
"""list of ndarray value-ids for each dimension in slice.
The values for each dimension appear as an ndarray. None appears
instead of the array for each dimension having only NaN values.
"""
return [
(
np.array(dim.numeric_values)
if (dim.numeric_values and any(~np.isnan(dim.numeric_values)))
else None
)
for dim in self._slice.dimensions
] | [
"def",
"values",
"(",
"self",
")",
":",
"return",
"[",
"(",
"np",
".",
"array",
"(",
"dim",
".",
"numeric_values",
")",
"if",
"(",
"dim",
".",
"numeric_values",
"and",
"any",
"(",
"~",
"np",
".",
"isnan",
"(",
"dim",
".",
"numeric_values",
")",
")"... | list of ndarray value-ids for each dimension in slice.
The values for each dimension appear as an ndarray. None appears
instead of the array for each dimension having only NaN values. | [
"list",
"of",
"ndarray",
"value",
"-",
"ids",
"for",
"each",
"dimension",
"in",
"slice",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/measures/scale_means.py#L112-L125 | train | 37,131 |
Crunch-io/crunch-cube | src/cr/cube/util.py | compress_pruned | def compress_pruned(table):
"""Compress table based on pruning mask.
Only the rows/cols in which all of the elements are masked need to be
pruned.
"""
if not isinstance(table, np.ma.core.MaskedArray):
return table
if table.ndim == 0:
return table.data
if table.ndim == 1:
return np.ma.compressed(table)
row_inds = ~table.mask.all(axis=1)
col_inds = ~table.mask.all(axis=0)
table = table[row_inds, :][:, col_inds]
if table.dtype == float and table.mask.any():
table[table.mask] = np.nan
return table | python | def compress_pruned(table):
"""Compress table based on pruning mask.
Only the rows/cols in which all of the elements are masked need to be
pruned.
"""
if not isinstance(table, np.ma.core.MaskedArray):
return table
if table.ndim == 0:
return table.data
if table.ndim == 1:
return np.ma.compressed(table)
row_inds = ~table.mask.all(axis=1)
col_inds = ~table.mask.all(axis=0)
table = table[row_inds, :][:, col_inds]
if table.dtype == float and table.mask.any():
table[table.mask] = np.nan
return table | [
"def",
"compress_pruned",
"(",
"table",
")",
":",
"if",
"not",
"isinstance",
"(",
"table",
",",
"np",
".",
"ma",
".",
"core",
".",
"MaskedArray",
")",
":",
"return",
"table",
"if",
"table",
".",
"ndim",
"==",
"0",
":",
"return",
"table",
".",
"data",... | Compress table based on pruning mask.
Only the rows/cols in which all of the elements are masked need to be
pruned. | [
"Compress",
"table",
"based",
"on",
"pruning",
"mask",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/util.py#L16-L36 | train | 37,132 |
Crunch-io/crunch-cube | src/cr/cube/util.py | intersperse_hs_in_std_res | def intersperse_hs_in_std_res(slice_, hs_dims, res):
"""Perform the insertions of place-holding rows and cols for insertions."""
for dim, inds in enumerate(slice_.inserted_hs_indices()):
if dim not in hs_dims:
continue
for i in inds:
res = np.insert(res, i, np.nan, axis=(dim - slice_.ndim))
return res | python | def intersperse_hs_in_std_res(slice_, hs_dims, res):
"""Perform the insertions of place-holding rows and cols for insertions."""
for dim, inds in enumerate(slice_.inserted_hs_indices()):
if dim not in hs_dims:
continue
for i in inds:
res = np.insert(res, i, np.nan, axis=(dim - slice_.ndim))
return res | [
"def",
"intersperse_hs_in_std_res",
"(",
"slice_",
",",
"hs_dims",
",",
"res",
")",
":",
"for",
"dim",
",",
"inds",
"in",
"enumerate",
"(",
"slice_",
".",
"inserted_hs_indices",
"(",
")",
")",
":",
"if",
"dim",
"not",
"in",
"hs_dims",
":",
"continue",
"f... | Perform the insertions of place-holding rows and cols for insertions. | [
"Perform",
"the",
"insertions",
"of",
"place",
"-",
"holding",
"rows",
"and",
"cols",
"for",
"insertions",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/util.py#L39-L46 | train | 37,133 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/utils.py | inflate_parameter_leaf | def inflate_parameter_leaf(sub_parameter, base_year, inflator, unit_type = 'unit'):
"""
Inflate a Parameter leaf according to unit type
Basic unit type are supposed by default
Other admissible unit types are threshold_unit and rate_unit
"""
if isinstance(sub_parameter, Scale):
if unit_type == 'threshold_unit':
for bracket in sub_parameter.brackets:
threshold = bracket.children['threshold']
inflate_parameter_leaf(threshold, base_year, inflator)
return
else:
# Remove new values for year > base_year
kept_instants_str = [
parameter_at_instant.instant_str
for parameter_at_instant in sub_parameter.values_list
if periods.instant(parameter_at_instant.instant_str).year <= base_year
]
if not kept_instants_str:
return
last_admissible_instant_str = max(kept_instants_str)
sub_parameter.update(
start = last_admissible_instant_str,
value = sub_parameter(last_admissible_instant_str)
)
restricted_to_base_year_value_list = [
parameter_at_instant for parameter_at_instant in sub_parameter.values_list
if periods.instant(parameter_at_instant.instant_str).year == base_year
]
# When value is changed in the base year
if restricted_to_base_year_value_list:
for parameter_at_instant in reversed(restricted_to_base_year_value_list):
if parameter_at_instant.instant_str.startswith(str(base_year)):
value = (
parameter_at_instant.value * (1 + inflator)
if parameter_at_instant.value is not None
else None
)
sub_parameter.update(
start = parameter_at_instant.instant_str.replace(
str(base_year), str(base_year + 1)
),
value = value,
)
# Or use the value at that instant even when it is defined earlier tahn the base year
else:
value = (
sub_parameter("{}-12-31".format(base_year)) * (1 + inflator)
if sub_parameter("{}-12-31".format(base_year)) is not None
else None
)
sub_parameter.update(
start = "{}-01-01".format(base_year + 1),
value = value
) | python | def inflate_parameter_leaf(sub_parameter, base_year, inflator, unit_type = 'unit'):
"""
Inflate a Parameter leaf according to unit type
Basic unit type are supposed by default
Other admissible unit types are threshold_unit and rate_unit
"""
if isinstance(sub_parameter, Scale):
if unit_type == 'threshold_unit':
for bracket in sub_parameter.brackets:
threshold = bracket.children['threshold']
inflate_parameter_leaf(threshold, base_year, inflator)
return
else:
# Remove new values for year > base_year
kept_instants_str = [
parameter_at_instant.instant_str
for parameter_at_instant in sub_parameter.values_list
if periods.instant(parameter_at_instant.instant_str).year <= base_year
]
if not kept_instants_str:
return
last_admissible_instant_str = max(kept_instants_str)
sub_parameter.update(
start = last_admissible_instant_str,
value = sub_parameter(last_admissible_instant_str)
)
restricted_to_base_year_value_list = [
parameter_at_instant for parameter_at_instant in sub_parameter.values_list
if periods.instant(parameter_at_instant.instant_str).year == base_year
]
# When value is changed in the base year
if restricted_to_base_year_value_list:
for parameter_at_instant in reversed(restricted_to_base_year_value_list):
if parameter_at_instant.instant_str.startswith(str(base_year)):
value = (
parameter_at_instant.value * (1 + inflator)
if parameter_at_instant.value is not None
else None
)
sub_parameter.update(
start = parameter_at_instant.instant_str.replace(
str(base_year), str(base_year + 1)
),
value = value,
)
# Or use the value at that instant even when it is defined earlier tahn the base year
else:
value = (
sub_parameter("{}-12-31".format(base_year)) * (1 + inflator)
if sub_parameter("{}-12-31".format(base_year)) is not None
else None
)
sub_parameter.update(
start = "{}-01-01".format(base_year + 1),
value = value
) | [
"def",
"inflate_parameter_leaf",
"(",
"sub_parameter",
",",
"base_year",
",",
"inflator",
",",
"unit_type",
"=",
"'unit'",
")",
":",
"if",
"isinstance",
"(",
"sub_parameter",
",",
"Scale",
")",
":",
"if",
"unit_type",
"==",
"'threshold_unit'",
":",
"for",
"bra... | Inflate a Parameter leaf according to unit type
Basic unit type are supposed by default
Other admissible unit types are threshold_unit and rate_unit | [
"Inflate",
"a",
"Parameter",
"leaf",
"according",
"to",
"unit",
"type"
] | bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358 | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/utils.py#L63-L121 | train | 37,134 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/scenarios.py | AbstractSurveyScenario.calculate_variable | def calculate_variable(self, variable = None, period = None, use_baseline = False):
"""
Compute and return the variable values for period and baseline or reform tax_benefit_system
"""
if use_baseline:
assert self.baseline_simulation is not None, "self.baseline_simulation is None"
simulation = self.baseline_simulation
else:
assert self.simulation is not None
simulation = self.simulation
tax_benefit_system = simulation.tax_benefit_system
assert period is not None
if not isinstance(period, periods.Period):
period = periods.period(period)
assert simulation is not None
assert tax_benefit_system is not None
assert variable in tax_benefit_system.variables, "{} is not a valid variable".format(variable)
period_size_independent = tax_benefit_system.get_variable(variable).is_period_size_independent
definition_period = tax_benefit_system.get_variable(variable).definition_period
if period_size_independent is False and definition_period != u'eternity':
values = simulation.calculate_add(variable, period = period)
elif period_size_independent is True and definition_period == u'month' and period.size_in_months > 1:
values = simulation.calculate(variable, period = period.first_month)
elif period_size_independent is True and definition_period == u'month' and period.size_in_months == 1:
values = simulation.calculate(variable, period = period)
elif period_size_independent is True and definition_period == u'year' and period.size_in_months > 12:
values = simulation.calculate(variable, period = period.start.offset('first-of', 'year').period('year'))
elif period_size_independent is True and definition_period == u'year' and period.size_in_months == 12:
values = simulation.calculate(variable, period = period)
elif period_size_independent is True and definition_period == u'year':
values = simulation.calculate(variable, period = period.this_year)
elif definition_period == u'eternity':
values = simulation.calculate(variable, period = period)
else:
values = None
assert values is not None, 'Unspecified calculation period for variable {}'.format(variable)
return values | python | def calculate_variable(self, variable = None, period = None, use_baseline = False):
"""
Compute and return the variable values for period and baseline or reform tax_benefit_system
"""
if use_baseline:
assert self.baseline_simulation is not None, "self.baseline_simulation is None"
simulation = self.baseline_simulation
else:
assert self.simulation is not None
simulation = self.simulation
tax_benefit_system = simulation.tax_benefit_system
assert period is not None
if not isinstance(period, periods.Period):
period = periods.period(period)
assert simulation is not None
assert tax_benefit_system is not None
assert variable in tax_benefit_system.variables, "{} is not a valid variable".format(variable)
period_size_independent = tax_benefit_system.get_variable(variable).is_period_size_independent
definition_period = tax_benefit_system.get_variable(variable).definition_period
if period_size_independent is False and definition_period != u'eternity':
values = simulation.calculate_add(variable, period = period)
elif period_size_independent is True and definition_period == u'month' and period.size_in_months > 1:
values = simulation.calculate(variable, period = period.first_month)
elif period_size_independent is True and definition_period == u'month' and period.size_in_months == 1:
values = simulation.calculate(variable, period = period)
elif period_size_independent is True and definition_period == u'year' and period.size_in_months > 12:
values = simulation.calculate(variable, period = period.start.offset('first-of', 'year').period('year'))
elif period_size_independent is True and definition_period == u'year' and period.size_in_months == 12:
values = simulation.calculate(variable, period = period)
elif period_size_independent is True and definition_period == u'year':
values = simulation.calculate(variable, period = period.this_year)
elif definition_period == u'eternity':
values = simulation.calculate(variable, period = period)
else:
values = None
assert values is not None, 'Unspecified calculation period for variable {}'.format(variable)
return values | [
"def",
"calculate_variable",
"(",
"self",
",",
"variable",
"=",
"None",
",",
"period",
"=",
"None",
",",
"use_baseline",
"=",
"False",
")",
":",
"if",
"use_baseline",
":",
"assert",
"self",
".",
"baseline_simulation",
"is",
"not",
"None",
",",
"\"self.baseli... | Compute and return the variable values for period and baseline or reform tax_benefit_system | [
"Compute",
"and",
"return",
"the",
"variable",
"values",
"for",
"period",
"and",
"baseline",
"or",
"reform",
"tax_benefit_system"
] | bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358 | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/scenarios.py#L298-L339 | train | 37,135 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/scenarios.py | AbstractSurveyScenario.filter_input_variables | def filter_input_variables(self, input_data_frame = None, simulation = None):
"""
Filter the input data frame from variables that won't be used or are set to be computed
"""
assert input_data_frame is not None
assert simulation is not None
id_variable_by_entity_key = self.id_variable_by_entity_key
role_variable_by_entity_key = self.role_variable_by_entity_key
used_as_input_variables = self.used_as_input_variables
tax_benefit_system = simulation.tax_benefit_system
variables = tax_benefit_system.variables
id_variables = [
id_variable_by_entity_key[_entity.key] for _entity in simulation.entities.values()
if not _entity.is_person]
role_variables = [
role_variable_by_entity_key[_entity.key] for _entity in simulation.entities.values()
if not _entity.is_person]
log.debug('Variable used_as_input_variables in filter: \n {}'.format(used_as_input_variables))
unknown_columns = []
for column_name in input_data_frame:
if column_name in id_variables + role_variables:
continue
if column_name not in variables:
unknown_columns.append(column_name)
input_data_frame.drop(column_name, axis = 1, inplace = True)
if unknown_columns:
log.debug('The following unknown columns {}, are dropped from input table'.format(
sorted(unknown_columns)))
used_columns = []
dropped_columns = []
for column_name in input_data_frame:
if column_name in id_variables + role_variables:
continue
variable = variables[column_name]
# Keeping the calculated variables that are initialized by the input data
if variable.formulas:
if column_name in used_as_input_variables:
used_columns.append(column_name)
continue
dropped_columns.append(column_name)
input_data_frame.drop(column_name, axis = 1, inplace = True)
#
#
#
if used_columns:
log.debug(
'These columns are not dropped because present in used_as_input_variables:\n {}'.format(
sorted(used_columns)))
if dropped_columns:
log.debug(
'These columns in survey are set to be calculated, we drop them from the input table:\n {}'.format(
sorted(dropped_columns)))
log.info('Keeping the following variables in the input_data_frame:\n {}'.format(
sorted(list(input_data_frame.columns))))
return input_data_frame | python | def filter_input_variables(self, input_data_frame = None, simulation = None):
"""
Filter the input data frame from variables that won't be used or are set to be computed
"""
assert input_data_frame is not None
assert simulation is not None
id_variable_by_entity_key = self.id_variable_by_entity_key
role_variable_by_entity_key = self.role_variable_by_entity_key
used_as_input_variables = self.used_as_input_variables
tax_benefit_system = simulation.tax_benefit_system
variables = tax_benefit_system.variables
id_variables = [
id_variable_by_entity_key[_entity.key] for _entity in simulation.entities.values()
if not _entity.is_person]
role_variables = [
role_variable_by_entity_key[_entity.key] for _entity in simulation.entities.values()
if not _entity.is_person]
log.debug('Variable used_as_input_variables in filter: \n {}'.format(used_as_input_variables))
unknown_columns = []
for column_name in input_data_frame:
if column_name in id_variables + role_variables:
continue
if column_name not in variables:
unknown_columns.append(column_name)
input_data_frame.drop(column_name, axis = 1, inplace = True)
if unknown_columns:
log.debug('The following unknown columns {}, are dropped from input table'.format(
sorted(unknown_columns)))
used_columns = []
dropped_columns = []
for column_name in input_data_frame:
if column_name in id_variables + role_variables:
continue
variable = variables[column_name]
# Keeping the calculated variables that are initialized by the input data
if variable.formulas:
if column_name in used_as_input_variables:
used_columns.append(column_name)
continue
dropped_columns.append(column_name)
input_data_frame.drop(column_name, axis = 1, inplace = True)
#
#
#
if used_columns:
log.debug(
'These columns are not dropped because present in used_as_input_variables:\n {}'.format(
sorted(used_columns)))
if dropped_columns:
log.debug(
'These columns in survey are set to be calculated, we drop them from the input table:\n {}'.format(
sorted(dropped_columns)))
log.info('Keeping the following variables in the input_data_frame:\n {}'.format(
sorted(list(input_data_frame.columns))))
return input_data_frame | [
"def",
"filter_input_variables",
"(",
"self",
",",
"input_data_frame",
"=",
"None",
",",
"simulation",
"=",
"None",
")",
":",
"assert",
"input_data_frame",
"is",
"not",
"None",
"assert",
"simulation",
"is",
"not",
"None",
"id_variable_by_entity_key",
"=",
"self",
... | Filter the input data frame from variables that won't be used or are set to be computed | [
"Filter",
"the",
"input",
"data",
"frame",
"from",
"variables",
"that",
"won",
"t",
"be",
"used",
"or",
"are",
"set",
"to",
"be",
"computed"
] | bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358 | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/scenarios.py#L523-L585 | train | 37,136 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/scenarios.py | AbstractSurveyScenario.init_from_data | def init_from_data(self, calibration_kwargs = None, inflation_kwargs = None,
rebuild_input_data = False, rebuild_kwargs = None, data = None, memory_config = None):
'''Initialises a survey scenario from data.
:param rebuild_input_data: Whether or not to clean, format and save data.
Take a look at :func:`build_input_data`
:param data: Contains the data, or metadata needed to know where to find it.
'''
# When not ``None``, it'll try to get the data for *year*.
if data is not None:
data_year = data.get("data_year", self.year)
if calibration_kwargs is not None:
assert set(calibration_kwargs.keys()).issubset(set(
['target_margins_by_variable', 'parameters', 'total_population']))
if inflation_kwargs is not None:
assert set(inflation_kwargs.keys()).issubset(set(['inflator_by_variable', 'target_by_variable']))
self._set_id_variable_by_entity_key()
self._set_role_variable_by_entity_key()
self._set_used_as_input_variables_by_entity()
# When ``True`` it'll assume it is raw data and do all that described supra.
# When ``False``, it'll assume data is ready for consumption.
if rebuild_input_data:
if rebuild_kwargs is not None:
self.build_input_data(year = data_year, **rebuild_kwargs)
else:
self.build_input_data(year = data_year)
debug = self.debug
trace = self.trace
# Inverting reform and baseline because we are more likely
# to use baseline input in reform than the other way around
if self.baseline_tax_benefit_system is not None:
self.new_simulation(debug = debug, data = data, trace = trace, memory_config = memory_config,
use_baseline = True)
# Note that I can pass a :class:`pd.DataFrame` directly, if I don't want to rebuild the data.
self.new_simulation(debug = debug, data = data, trace = trace, memory_config = memory_config)
if calibration_kwargs:
self.calibrate(**calibration_kwargs)
if inflation_kwargs:
self.inflate(**inflation_kwargs) | python | def init_from_data(self, calibration_kwargs = None, inflation_kwargs = None,
rebuild_input_data = False, rebuild_kwargs = None, data = None, memory_config = None):
'''Initialises a survey scenario from data.
:param rebuild_input_data: Whether or not to clean, format and save data.
Take a look at :func:`build_input_data`
:param data: Contains the data, or metadata needed to know where to find it.
'''
# When not ``None``, it'll try to get the data for *year*.
if data is not None:
data_year = data.get("data_year", self.year)
if calibration_kwargs is not None:
assert set(calibration_kwargs.keys()).issubset(set(
['target_margins_by_variable', 'parameters', 'total_population']))
if inflation_kwargs is not None:
assert set(inflation_kwargs.keys()).issubset(set(['inflator_by_variable', 'target_by_variable']))
self._set_id_variable_by_entity_key()
self._set_role_variable_by_entity_key()
self._set_used_as_input_variables_by_entity()
# When ``True`` it'll assume it is raw data and do all that described supra.
# When ``False``, it'll assume data is ready for consumption.
if rebuild_input_data:
if rebuild_kwargs is not None:
self.build_input_data(year = data_year, **rebuild_kwargs)
else:
self.build_input_data(year = data_year)
debug = self.debug
trace = self.trace
# Inverting reform and baseline because we are more likely
# to use baseline input in reform than the other way around
if self.baseline_tax_benefit_system is not None:
self.new_simulation(debug = debug, data = data, trace = trace, memory_config = memory_config,
use_baseline = True)
# Note that I can pass a :class:`pd.DataFrame` directly, if I don't want to rebuild the data.
self.new_simulation(debug = debug, data = data, trace = trace, memory_config = memory_config)
if calibration_kwargs:
self.calibrate(**calibration_kwargs)
if inflation_kwargs:
self.inflate(**inflation_kwargs) | [
"def",
"init_from_data",
"(",
"self",
",",
"calibration_kwargs",
"=",
"None",
",",
"inflation_kwargs",
"=",
"None",
",",
"rebuild_input_data",
"=",
"False",
",",
"rebuild_kwargs",
"=",
"None",
",",
"data",
"=",
"None",
",",
"memory_config",
"=",
"None",
")",
... | Initialises a survey scenario from data.
:param rebuild_input_data: Whether or not to clean, format and save data.
Take a look at :func:`build_input_data`
:param data: Contains the data, or metadata needed to know where to find it. | [
"Initialises",
"a",
"survey",
"scenario",
"from",
"data",
"."
] | bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358 | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/scenarios.py#L628-L677 | train | 37,137 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/scenarios.py | AbstractSurveyScenario.neutralize_variables | def neutralize_variables(self, tax_benefit_system):
"""
Neutralizing input variables not in input dataframe and keep some crucial variables
"""
for variable_name, variable in tax_benefit_system.variables.items():
if variable.formulas:
continue
if self.used_as_input_variables and (variable_name in self.used_as_input_variables):
continue
if self.non_neutralizable_variables and (variable_name in self.non_neutralizable_variables):
continue
if self.weight_column_name_by_entity and (variable_name in self.weight_column_name_by_entity.values()):
continue
tax_benefit_system.neutralize_variable(variable_name) | python | def neutralize_variables(self, tax_benefit_system):
"""
Neutralizing input variables not in input dataframe and keep some crucial variables
"""
for variable_name, variable in tax_benefit_system.variables.items():
if variable.formulas:
continue
if self.used_as_input_variables and (variable_name in self.used_as_input_variables):
continue
if self.non_neutralizable_variables and (variable_name in self.non_neutralizable_variables):
continue
if self.weight_column_name_by_entity and (variable_name in self.weight_column_name_by_entity.values()):
continue
tax_benefit_system.neutralize_variable(variable_name) | [
"def",
"neutralize_variables",
"(",
"self",
",",
"tax_benefit_system",
")",
":",
"for",
"variable_name",
",",
"variable",
"in",
"tax_benefit_system",
".",
"variables",
".",
"items",
"(",
")",
":",
"if",
"variable",
".",
"formulas",
":",
"continue",
"if",
"self... | Neutralizing input variables not in input dataframe and keep some crucial variables | [
"Neutralizing",
"input",
"variables",
"not",
"in",
"input",
"dataframe",
"and",
"keep",
"some",
"crucial",
"variables"
] | bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358 | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/scenarios.py#L1020-L1034 | train | 37,138 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/scenarios.py | AbstractSurveyScenario.set_tax_benefit_systems | def set_tax_benefit_systems(self, tax_benefit_system = None, baseline_tax_benefit_system = None):
"""
Set the tax and benefit system and eventually the baseline tax and benefit system
"""
assert tax_benefit_system is not None
self.tax_benefit_system = tax_benefit_system
if self.cache_blacklist is not None:
self.tax_benefit_system.cache_blacklist = self.cache_blacklist
if baseline_tax_benefit_system is not None:
self.baseline_tax_benefit_system = baseline_tax_benefit_system
if self.cache_blacklist is not None:
self.baseline_tax_benefit_system.cache_blacklist = self.cache_blacklist | python | def set_tax_benefit_systems(self, tax_benefit_system = None, baseline_tax_benefit_system = None):
"""
Set the tax and benefit system and eventually the baseline tax and benefit system
"""
assert tax_benefit_system is not None
self.tax_benefit_system = tax_benefit_system
if self.cache_blacklist is not None:
self.tax_benefit_system.cache_blacklist = self.cache_blacklist
if baseline_tax_benefit_system is not None:
self.baseline_tax_benefit_system = baseline_tax_benefit_system
if self.cache_blacklist is not None:
self.baseline_tax_benefit_system.cache_blacklist = self.cache_blacklist | [
"def",
"set_tax_benefit_systems",
"(",
"self",
",",
"tax_benefit_system",
"=",
"None",
",",
"baseline_tax_benefit_system",
"=",
"None",
")",
":",
"assert",
"tax_benefit_system",
"is",
"not",
"None",
"self",
".",
"tax_benefit_system",
"=",
"tax_benefit_system",
"if",
... | Set the tax and benefit system and eventually the baseline tax and benefit system | [
"Set",
"the",
"tax",
"and",
"benefit",
"system",
"and",
"eventually",
"the",
"baseline",
"tax",
"and",
"benefit",
"system"
] | bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358 | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/scenarios.py#L1058-L1069 | train | 37,139 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/scenarios.py | AbstractSurveyScenario._set_id_variable_by_entity_key | def _set_id_variable_by_entity_key(self) -> Dict[str, str]:
'''Identify and set the good ids for the different entities'''
if self.id_variable_by_entity_key is None:
self.id_variable_by_entity_key = dict(
(entity.key, entity.key + '_id') for entity in self.tax_benefit_system.entities)
log.debug("Use default id_variable names:\n {}".format(self.id_variable_by_entity_key))
return self.id_variable_by_entity_key | python | def _set_id_variable_by_entity_key(self) -> Dict[str, str]:
'''Identify and set the good ids for the different entities'''
if self.id_variable_by_entity_key is None:
self.id_variable_by_entity_key = dict(
(entity.key, entity.key + '_id') for entity in self.tax_benefit_system.entities)
log.debug("Use default id_variable names:\n {}".format(self.id_variable_by_entity_key))
return self.id_variable_by_entity_key | [
"def",
"_set_id_variable_by_entity_key",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"if",
"self",
".",
"id_variable_by_entity_key",
"is",
"None",
":",
"self",
".",
"id_variable_by_entity_key",
"=",
"dict",
"(",
"(",
"entity",
".",
"key... | Identify and set the good ids for the different entities | [
"Identify",
"and",
"set",
"the",
"good",
"ids",
"for",
"the",
"different",
"entities"
] | bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358 | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/scenarios.py#L1210-L1217 | train | 37,140 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/scenarios.py | AbstractSurveyScenario._set_role_variable_by_entity_key | def _set_role_variable_by_entity_key(self) -> Dict[str, str]:
'''Identify and set the good roles for the different entities'''
if self.role_variable_by_entity_key is None:
self.role_variable_by_entity_key = dict(
(entity.key, entity.key + '_legacy_role') for entity in self.tax_benefit_system.entities)
return self.role_variable_by_entity_key | python | def _set_role_variable_by_entity_key(self) -> Dict[str, str]:
'''Identify and set the good roles for the different entities'''
if self.role_variable_by_entity_key is None:
self.role_variable_by_entity_key = dict(
(entity.key, entity.key + '_legacy_role') for entity in self.tax_benefit_system.entities)
return self.role_variable_by_entity_key | [
"def",
"_set_role_variable_by_entity_key",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"if",
"self",
".",
"role_variable_by_entity_key",
"is",
"None",
":",
"self",
".",
"role_variable_by_entity_key",
"=",
"dict",
"(",
"(",
"entity",
".",
... | Identify and set the good roles for the different entities | [
"Identify",
"and",
"set",
"the",
"good",
"roles",
"for",
"the",
"different",
"entities"
] | bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358 | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/scenarios.py#L1219-L1225 | train | 37,141 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/scenarios.py | AbstractSurveyScenario._set_used_as_input_variables_by_entity | def _set_used_as_input_variables_by_entity(self) -> Dict[str, List[str]]:
'''Identify and set the good input variables for the different entities'''
if self.used_as_input_variables_by_entity is not None:
return
tax_benefit_system = self.tax_benefit_system
assert set(self.used_as_input_variables) <= set(tax_benefit_system.variables.keys()), \
"Some variables used as input variables are not part of the tax benefit system:\n {}".format(
set(self.used_as_input_variables).difference(set(tax_benefit_system.variables.keys()))
)
self.used_as_input_variables_by_entity = dict()
for entity in tax_benefit_system.entities:
self.used_as_input_variables_by_entity[entity.key] = [
variable
for variable in self.used_as_input_variables
if tax_benefit_system.get_variable(variable).entity == entity
]
return self.used_as_input_variables_by_entity | python | def _set_used_as_input_variables_by_entity(self) -> Dict[str, List[str]]:
'''Identify and set the good input variables for the different entities'''
if self.used_as_input_variables_by_entity is not None:
return
tax_benefit_system = self.tax_benefit_system
assert set(self.used_as_input_variables) <= set(tax_benefit_system.variables.keys()), \
"Some variables used as input variables are not part of the tax benefit system:\n {}".format(
set(self.used_as_input_variables).difference(set(tax_benefit_system.variables.keys()))
)
self.used_as_input_variables_by_entity = dict()
for entity in tax_benefit_system.entities:
self.used_as_input_variables_by_entity[entity.key] = [
variable
for variable in self.used_as_input_variables
if tax_benefit_system.get_variable(variable).entity == entity
]
return self.used_as_input_variables_by_entity | [
"def",
"_set_used_as_input_variables_by_entity",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
":",
"if",
"self",
".",
"used_as_input_variables_by_entity",
"is",
"not",
"None",
":",
"return",
"tax_benefit_system",
"=",
"self",
... | Identify and set the good input variables for the different entities | [
"Identify",
"and",
"set",
"the",
"good",
"input",
"variables",
"for",
"the",
"different",
"entities"
] | bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358 | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/scenarios.py#L1227-L1248 | train | 37,142 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _ApparentDimensions._dimensions | def _dimensions(self):
"""tuple of dimension objects in this collection.
This composed tuple is the source for the dimension objects in this
collection.
"""
return tuple(d for d in self._all_dimensions if d.dimension_type != DT.MR_CAT) | python | def _dimensions(self):
"""tuple of dimension objects in this collection.
This composed tuple is the source for the dimension objects in this
collection.
"""
return tuple(d for d in self._all_dimensions if d.dimension_type != DT.MR_CAT) | [
"def",
"_dimensions",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"d",
"for",
"d",
"in",
"self",
".",
"_all_dimensions",
"if",
"d",
".",
"dimension_type",
"!=",
"DT",
".",
"MR_CAT",
")"
] | tuple of dimension objects in this collection.
This composed tuple is the source for the dimension objects in this
collection. | [
"tuple",
"of",
"dimension",
"objects",
"in",
"this",
"collection",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L80-L86 | train | 37,143 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _DimensionFactory._iter_dimensions | def _iter_dimensions(self):
"""Generate Dimension object for each dimension dict."""
return (
Dimension(raw_dimension.dimension_dict, raw_dimension.dimension_type)
for raw_dimension in self._raw_dimensions
) | python | def _iter_dimensions(self):
"""Generate Dimension object for each dimension dict."""
return (
Dimension(raw_dimension.dimension_dict, raw_dimension.dimension_type)
for raw_dimension in self._raw_dimensions
) | [
"def",
"_iter_dimensions",
"(",
"self",
")",
":",
"return",
"(",
"Dimension",
"(",
"raw_dimension",
".",
"dimension_dict",
",",
"raw_dimension",
".",
"dimension_type",
")",
"for",
"raw_dimension",
"in",
"self",
".",
"_raw_dimensions",
")"
] | Generate Dimension object for each dimension dict. | [
"Generate",
"Dimension",
"object",
"for",
"each",
"dimension",
"dict",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L105-L110 | train | 37,144 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _DimensionFactory._raw_dimensions | def _raw_dimensions(self):
"""Sequence of _RawDimension objects wrapping each dimension dict."""
return tuple(
_RawDimension(dimension_dict, self._dimension_dicts)
for dimension_dict in self._dimension_dicts
) | python | def _raw_dimensions(self):
"""Sequence of _RawDimension objects wrapping each dimension dict."""
return tuple(
_RawDimension(dimension_dict, self._dimension_dicts)
for dimension_dict in self._dimension_dicts
) | [
"def",
"_raw_dimensions",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"_RawDimension",
"(",
"dimension_dict",
",",
"self",
".",
"_dimension_dicts",
")",
"for",
"dimension_dict",
"in",
"self",
".",
"_dimension_dicts",
")"
] | Sequence of _RawDimension objects wrapping each dimension dict. | [
"Sequence",
"of",
"_RawDimension",
"objects",
"wrapping",
"each",
"dimension",
"dict",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L113-L118 | train | 37,145 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _RawDimension.dimension_type | def dimension_type(self):
"""Return member of DIMENSION_TYPE appropriate to dimension_dict."""
base_type = self._base_type
if base_type == "categorical":
return self._resolve_categorical()
if base_type == "enum.variable":
return self._resolve_array_type()
if base_type == "enum.datetime":
return DT.DATETIME
if base_type == "enum.numeric":
return DT.BINNED_NUMERIC
if base_type == "enum.text":
return DT.TEXT
raise NotImplementedError("unrecognized dimension type %s" % base_type) | python | def dimension_type(self):
"""Return member of DIMENSION_TYPE appropriate to dimension_dict."""
base_type = self._base_type
if base_type == "categorical":
return self._resolve_categorical()
if base_type == "enum.variable":
return self._resolve_array_type()
if base_type == "enum.datetime":
return DT.DATETIME
if base_type == "enum.numeric":
return DT.BINNED_NUMERIC
if base_type == "enum.text":
return DT.TEXT
raise NotImplementedError("unrecognized dimension type %s" % base_type) | [
"def",
"dimension_type",
"(",
"self",
")",
":",
"base_type",
"=",
"self",
".",
"_base_type",
"if",
"base_type",
"==",
"\"categorical\"",
":",
"return",
"self",
".",
"_resolve_categorical",
"(",
")",
"if",
"base_type",
"==",
"\"enum.variable\"",
":",
"return",
... | Return member of DIMENSION_TYPE appropriate to dimension_dict. | [
"Return",
"member",
"of",
"DIMENSION_TYPE",
"appropriate",
"to",
"dimension_dict",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L139-L152 | train | 37,146 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _RawDimension._base_type | def _base_type(self):
"""Return str like 'enum.numeric' representing dimension type.
This string is a 'type.subclass' concatenation of the str keys
used to identify the dimension type in the cube response JSON.
The '.subclass' suffix only appears where a subtype is present.
"""
type_class = self._dimension_dict["type"]["class"]
if type_class == "categorical":
return "categorical"
if type_class == "enum":
subclass = self._dimension_dict["type"]["subtype"]["class"]
return "enum.%s" % subclass
raise NotImplementedError("unexpected dimension type class '%s'" % type_class) | python | def _base_type(self):
"""Return str like 'enum.numeric' representing dimension type.
This string is a 'type.subclass' concatenation of the str keys
used to identify the dimension type in the cube response JSON.
The '.subclass' suffix only appears where a subtype is present.
"""
type_class = self._dimension_dict["type"]["class"]
if type_class == "categorical":
return "categorical"
if type_class == "enum":
subclass = self._dimension_dict["type"]["subtype"]["class"]
return "enum.%s" % subclass
raise NotImplementedError("unexpected dimension type class '%s'" % type_class) | [
"def",
"_base_type",
"(",
"self",
")",
":",
"type_class",
"=",
"self",
".",
"_dimension_dict",
"[",
"\"type\"",
"]",
"[",
"\"class\"",
"]",
"if",
"type_class",
"==",
"\"categorical\"",
":",
"return",
"\"categorical\"",
"if",
"type_class",
"==",
"\"enum\"",
":"... | Return str like 'enum.numeric' representing dimension type.
This string is a 'type.subclass' concatenation of the str keys
used to identify the dimension type in the cube response JSON.
The '.subclass' suffix only appears where a subtype is present. | [
"Return",
"str",
"like",
"enum",
".",
"numeric",
"representing",
"dimension",
"type",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L160-L173 | train | 37,147 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _RawDimension._resolve_array_type | def _resolve_array_type(self):
"""Return one of the ARRAY_TYPES members of DIMENSION_TYPE.
This method distinguishes between CA and MR dimensions. The return
value is only meaningful if the dimension is known to be of array
type (i.e. either CA or MR, base-type 'enum.variable').
"""
next_raw_dimension = self._next_raw_dimension
if next_raw_dimension is None:
return DT.CA
is_mr_subvar = (
next_raw_dimension._base_type == "categorical"
and next_raw_dimension._has_selected_category
and next_raw_dimension._alias == self._alias
)
return DT.MR if is_mr_subvar else DT.CA | python | def _resolve_array_type(self):
"""Return one of the ARRAY_TYPES members of DIMENSION_TYPE.
This method distinguishes between CA and MR dimensions. The return
value is only meaningful if the dimension is known to be of array
type (i.e. either CA or MR, base-type 'enum.variable').
"""
next_raw_dimension = self._next_raw_dimension
if next_raw_dimension is None:
return DT.CA
is_mr_subvar = (
next_raw_dimension._base_type == "categorical"
and next_raw_dimension._has_selected_category
and next_raw_dimension._alias == self._alias
)
return DT.MR if is_mr_subvar else DT.CA | [
"def",
"_resolve_array_type",
"(",
"self",
")",
":",
"next_raw_dimension",
"=",
"self",
".",
"_next_raw_dimension",
"if",
"next_raw_dimension",
"is",
"None",
":",
"return",
"DT",
".",
"CA",
"is_mr_subvar",
"=",
"(",
"next_raw_dimension",
".",
"_base_type",
"==",
... | Return one of the ARRAY_TYPES members of DIMENSION_TYPE.
This method distinguishes between CA and MR dimensions. The return
value is only meaningful if the dimension is known to be of array
type (i.e. either CA or MR, base-type 'enum.variable'). | [
"Return",
"one",
"of",
"the",
"ARRAY_TYPES",
"members",
"of",
"DIMENSION_TYPE",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L209-L225 | train | 37,148 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _RawDimension._resolve_categorical | def _resolve_categorical(self):
"""Return one of the categorical members of DIMENSION_TYPE.
This method distinguishes between CAT, CA_CAT, MR_CAT, and LOGICAL
dimension types, all of which have the base type 'categorical'. The
return value is only meaningful if the dimension is known to be one
of the categorical types (has base-type 'categorical').
"""
# ---an array categorical is either CA_CAT or MR_CAT---
if self._is_array_cat:
return DT.MR_CAT if self._has_selected_category else DT.CA_CAT
# ---what's left is logical or plain-old categorical---
return DT.LOGICAL if self._has_selected_category else DT.CAT | python | def _resolve_categorical(self):
"""Return one of the categorical members of DIMENSION_TYPE.
This method distinguishes between CAT, CA_CAT, MR_CAT, and LOGICAL
dimension types, all of which have the base type 'categorical'. The
return value is only meaningful if the dimension is known to be one
of the categorical types (has base-type 'categorical').
"""
# ---an array categorical is either CA_CAT or MR_CAT---
if self._is_array_cat:
return DT.MR_CAT if self._has_selected_category else DT.CA_CAT
# ---what's left is logical or plain-old categorical---
return DT.LOGICAL if self._has_selected_category else DT.CAT | [
"def",
"_resolve_categorical",
"(",
"self",
")",
":",
"# ---an array categorical is either CA_CAT or MR_CAT---",
"if",
"self",
".",
"_is_array_cat",
":",
"return",
"DT",
".",
"MR_CAT",
"if",
"self",
".",
"_has_selected_category",
"else",
"DT",
".",
"CA_CAT",
"# ---wha... | Return one of the categorical members of DIMENSION_TYPE.
This method distinguishes between CAT, CA_CAT, MR_CAT, and LOGICAL
dimension types, all of which have the base type 'categorical'. The
return value is only meaningful if the dimension is known to be one
of the categorical types (has base-type 'categorical'). | [
"Return",
"one",
"of",
"the",
"categorical",
"members",
"of",
"DIMENSION_TYPE",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L227-L240 | train | 37,149 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | Dimension.inserted_hs_indices | def inserted_hs_indices(self):
"""list of int index of each inserted subtotal for the dimension.
Each value represents the position of a subtotal in the interleaved
sequence of elements and subtotals items.
"""
# ---don't do H&S insertions for CA and MR subvar dimensions---
if self.dimension_type in DT.ARRAY_TYPES:
return []
return [
idx
for idx, item in enumerate(
self._iter_interleaved_items(self.valid_elements)
)
if item.is_insertion
] | python | def inserted_hs_indices(self):
"""list of int index of each inserted subtotal for the dimension.
Each value represents the position of a subtotal in the interleaved
sequence of elements and subtotals items.
"""
# ---don't do H&S insertions for CA and MR subvar dimensions---
if self.dimension_type in DT.ARRAY_TYPES:
return []
return [
idx
for idx, item in enumerate(
self._iter_interleaved_items(self.valid_elements)
)
if item.is_insertion
] | [
"def",
"inserted_hs_indices",
"(",
"self",
")",
":",
"# ---don't do H&S insertions for CA and MR subvar dimensions---",
"if",
"self",
".",
"dimension_type",
"in",
"DT",
".",
"ARRAY_TYPES",
":",
"return",
"[",
"]",
"return",
"[",
"idx",
"for",
"idx",
",",
"item",
"... | list of int index of each inserted subtotal for the dimension.
Each value represents the position of a subtotal in the interleaved
sequence of elements and subtotals items. | [
"list",
"of",
"int",
"index",
"of",
"each",
"inserted",
"subtotal",
"for",
"the",
"dimension",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L299-L315 | train | 37,150 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | Dimension.is_marginable | def is_marginable(self):
"""True if adding counts across this dimension axis is meaningful."""
return self.dimension_type not in {DT.CA, DT.MR, DT.MR_CAT, DT.LOGICAL} | python | def is_marginable(self):
"""True if adding counts across this dimension axis is meaningful."""
return self.dimension_type not in {DT.CA, DT.MR, DT.MR_CAT, DT.LOGICAL} | [
"def",
"is_marginable",
"(",
"self",
")",
":",
"return",
"self",
".",
"dimension_type",
"not",
"in",
"{",
"DT",
".",
"CA",
",",
"DT",
".",
"MR",
",",
"DT",
".",
"MR_CAT",
",",
"DT",
".",
"LOGICAL",
"}"
] | True if adding counts across this dimension axis is meaningful. | [
"True",
"if",
"adding",
"counts",
"across",
"this",
"dimension",
"axis",
"is",
"meaningful",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L318-L320 | train | 37,151 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | Dimension.labels | def labels(
self, include_missing=False, include_transforms=False, include_cat_ids=False
):
"""Return list of str labels for the elements of this dimension.
Returns a list of (label, element_id) pairs if *include_cat_ids* is
True. The `element_id` value in the second position of the pair is
None for subtotal items (which don't have an element-id).
"""
# TODO: Having an alternate return type triggered by a flag-parameter
# (`include_cat_ids` in this case) is poor practice. Using flags like
# that effectively squashes what should be two methods into one.
# Either get rid of the need for that alternate return value type or
# create a separate method for it.
elements = self.all_elements if include_missing else self.valid_elements
include_subtotals = include_transforms and self.dimension_type != DT.CA_SUBVAR
# ---items are elements or subtotals, interleaved in display order---
interleaved_items = tuple(self._iter_interleaved_items(elements))
labels = list(
item.label
for item in interleaved_items
if include_subtotals or not item.is_insertion
)
if include_cat_ids:
element_ids = tuple(
None if item.is_insertion else item.element_id
for item in interleaved_items
if include_subtotals or not item.is_insertion
)
return list(zip(labels, element_ids))
return labels | python | def labels(
self, include_missing=False, include_transforms=False, include_cat_ids=False
):
"""Return list of str labels for the elements of this dimension.
Returns a list of (label, element_id) pairs if *include_cat_ids* is
True. The `element_id` value in the second position of the pair is
None for subtotal items (which don't have an element-id).
"""
# TODO: Having an alternate return type triggered by a flag-parameter
# (`include_cat_ids` in this case) is poor practice. Using flags like
# that effectively squashes what should be two methods into one.
# Either get rid of the need for that alternate return value type or
# create a separate method for it.
elements = self.all_elements if include_missing else self.valid_elements
include_subtotals = include_transforms and self.dimension_type != DT.CA_SUBVAR
# ---items are elements or subtotals, interleaved in display order---
interleaved_items = tuple(self._iter_interleaved_items(elements))
labels = list(
item.label
for item in interleaved_items
if include_subtotals or not item.is_insertion
)
if include_cat_ids:
element_ids = tuple(
None if item.is_insertion else item.element_id
for item in interleaved_items
if include_subtotals or not item.is_insertion
)
return list(zip(labels, element_ids))
return labels | [
"def",
"labels",
"(",
"self",
",",
"include_missing",
"=",
"False",
",",
"include_transforms",
"=",
"False",
",",
"include_cat_ids",
"=",
"False",
")",
":",
"# TODO: Having an alternate return type triggered by a flag-parameter",
"# (`include_cat_ids` in this case) is poor prac... | Return list of str labels for the elements of this dimension.
Returns a list of (label, element_id) pairs if *include_cat_ids* is
True. The `element_id` value in the second position of the pair is
None for subtotal items (which don't have an element-id). | [
"Return",
"list",
"of",
"str",
"labels",
"for",
"the",
"elements",
"of",
"this",
"dimension",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L322-L357 | train | 37,152 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | Dimension._iter_interleaved_items | def _iter_interleaved_items(self, elements):
"""Generate element or subtotal items in interleaved order.
This ordering corresponds to how value "rows" (or columns) are to
appear after subtotals have been inserted at their anchor locations.
Where more than one subtotal is anchored to the same location, they
appear in their document order in the cube response.
Only elements in the passed *elements* collection appear, which
allows control over whether missing elements are included by choosing
`.all_elements` or `.valid_elements`.
"""
subtotals = self._subtotals
for subtotal in subtotals.iter_for_anchor("top"):
yield subtotal
for element in elements:
yield element
for subtotal in subtotals.iter_for_anchor(element.element_id):
yield subtotal
for subtotal in subtotals.iter_for_anchor("bottom"):
yield subtotal | python | def _iter_interleaved_items(self, elements):
"""Generate element or subtotal items in interleaved order.
This ordering corresponds to how value "rows" (or columns) are to
appear after subtotals have been inserted at their anchor locations.
Where more than one subtotal is anchored to the same location, they
appear in their document order in the cube response.
Only elements in the passed *elements* collection appear, which
allows control over whether missing elements are included by choosing
`.all_elements` or `.valid_elements`.
"""
subtotals = self._subtotals
for subtotal in subtotals.iter_for_anchor("top"):
yield subtotal
for element in elements:
yield element
for subtotal in subtotals.iter_for_anchor(element.element_id):
yield subtotal
for subtotal in subtotals.iter_for_anchor("bottom"):
yield subtotal | [
"def",
"_iter_interleaved_items",
"(",
"self",
",",
"elements",
")",
":",
"subtotals",
"=",
"self",
".",
"_subtotals",
"for",
"subtotal",
"in",
"subtotals",
".",
"iter_for_anchor",
"(",
"\"top\"",
")",
":",
"yield",
"subtotal",
"for",
"element",
"in",
"element... | Generate element or subtotal items in interleaved order.
This ordering corresponds to how value "rows" (or columns) are to
appear after subtotals have been inserted at their anchor locations.
Where more than one subtotal is anchored to the same location, they
appear in their document order in the cube response.
Only elements in the passed *elements* collection appear, which
allows control over whether missing elements are included by choosing
`.all_elements` or `.valid_elements`. | [
"Generate",
"element",
"or",
"subtotal",
"items",
"in",
"interleaved",
"order",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L391-L414 | train | 37,153 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | Dimension._subtotals | def _subtotals(self):
"""_Subtotals sequence object for this dimension.
The subtotals sequence provides access to any subtotal insertions
defined on this dimension.
"""
view = self._dimension_dict.get("references", {}).get("view", {})
# ---view can be both None and {}, thus the edge case.---
insertion_dicts = (
[] if view is None else view.get("transform", {}).get("insertions", [])
)
return _Subtotals(insertion_dicts, self.valid_elements) | python | def _subtotals(self):
"""_Subtotals sequence object for this dimension.
The subtotals sequence provides access to any subtotal insertions
defined on this dimension.
"""
view = self._dimension_dict.get("references", {}).get("view", {})
# ---view can be both None and {}, thus the edge case.---
insertion_dicts = (
[] if view is None else view.get("transform", {}).get("insertions", [])
)
return _Subtotals(insertion_dicts, self.valid_elements) | [
"def",
"_subtotals",
"(",
"self",
")",
":",
"view",
"=",
"self",
".",
"_dimension_dict",
".",
"get",
"(",
"\"references\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"view\"",
",",
"{",
"}",
")",
"# ---view can be both None and {}, thus the edge case.---",
"inser... | _Subtotals sequence object for this dimension.
The subtotals sequence provides access to any subtotal insertions
defined on this dimension. | [
"_Subtotals",
"sequence",
"object",
"for",
"this",
"dimension",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L417-L428 | train | 37,154 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _AllElements._elements | def _elements(self):
"""Composed tuple storing actual sequence of element objects."""
ElementCls, element_dicts = self._element_makings
return tuple(
ElementCls(element_dict, idx, element_dicts)
for idx, element_dict in enumerate(element_dicts)
) | python | def _elements(self):
"""Composed tuple storing actual sequence of element objects."""
ElementCls, element_dicts = self._element_makings
return tuple(
ElementCls(element_dict, idx, element_dicts)
for idx, element_dict in enumerate(element_dicts)
) | [
"def",
"_elements",
"(",
"self",
")",
":",
"ElementCls",
",",
"element_dicts",
"=",
"self",
".",
"_element_makings",
"return",
"tuple",
"(",
"ElementCls",
"(",
"element_dict",
",",
"idx",
",",
"element_dicts",
")",
"for",
"idx",
",",
"element_dict",
"in",
"e... | Composed tuple storing actual sequence of element objects. | [
"Composed",
"tuple",
"storing",
"actual",
"sequence",
"of",
"element",
"objects",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L524-L530 | train | 37,155 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _BaseElement.numeric_value | def numeric_value(self):
"""Numeric value assigned to element by user, np.nan if absent."""
numeric_value = self._element_dict.get("numeric_value")
return np.nan if numeric_value is None else numeric_value | python | def numeric_value(self):
"""Numeric value assigned to element by user, np.nan if absent."""
numeric_value = self._element_dict.get("numeric_value")
return np.nan if numeric_value is None else numeric_value | [
"def",
"numeric_value",
"(",
"self",
")",
":",
"numeric_value",
"=",
"self",
".",
"_element_dict",
".",
"get",
"(",
"\"numeric_value\"",
")",
"return",
"np",
".",
"nan",
"if",
"numeric_value",
"is",
"None",
"else",
"numeric_value"
] | Numeric value assigned to element by user, np.nan if absent. | [
"Numeric",
"value",
"assigned",
"to",
"element",
"by",
"user",
"np",
".",
"nan",
"if",
"absent",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L596-L599 | train | 37,156 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _Element.label | def label(self):
"""str display-name for this element, '' when absent from cube response.
This property handles numeric, datetime and text variables, but also
subvar dimensions
"""
value = self._element_dict.get("value")
type_name = type(value).__name__
if type_name == "NoneType":
return ""
if type_name == "list":
# ---like '10-15' or 'A-F'---
return "-".join([str(item) for item in value])
if type_name in ("float", "int"):
return str(value)
if type_name in ("str", "unicode"):
return value
# ---For CA and MR subvar dimensions---
name = value.get("references", {}).get("name")
return name if name else "" | python | def label(self):
"""str display-name for this element, '' when absent from cube response.
This property handles numeric, datetime and text variables, but also
subvar dimensions
"""
value = self._element_dict.get("value")
type_name = type(value).__name__
if type_name == "NoneType":
return ""
if type_name == "list":
# ---like '10-15' or 'A-F'---
return "-".join([str(item) for item in value])
if type_name in ("float", "int"):
return str(value)
if type_name in ("str", "unicode"):
return value
# ---For CA and MR subvar dimensions---
name = value.get("references", {}).get("name")
return name if name else "" | [
"def",
"label",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"_element_dict",
".",
"get",
"(",
"\"value\"",
")",
"type_name",
"=",
"type",
"(",
"value",
")",
".",
"__name__",
"if",
"type_name",
"==",
"\"NoneType\"",
":",
"return",
"\"\"",
"if",
"t... | str display-name for this element, '' when absent from cube response.
This property handles numeric, datetime and text variables, but also
subvar dimensions | [
"str",
"display",
"-",
"name",
"for",
"this",
"element",
"when",
"absent",
"from",
"cube",
"response",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L620-L644 | train | 37,157 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _Subtotals._iter_valid_subtotal_dicts | def _iter_valid_subtotal_dicts(self):
"""Generate each insertion dict that represents a valid subtotal."""
for insertion_dict in self._insertion_dicts:
# ---skip any non-dicts---
if not isinstance(insertion_dict, dict):
continue
# ---skip any non-subtotal insertions---
if insertion_dict.get("function") != "subtotal":
continue
# ---skip any malformed subtotal-dicts---
if not {"anchor", "args", "name"}.issubset(insertion_dict.keys()):
continue
# ---skip if doesn't reference at least one non-missing element---
if not self._element_ids.intersection(insertion_dict["args"]):
continue
# ---an insertion-dict that successfully runs this gauntlet
# ---is a valid subtotal dict
yield insertion_dict | python | def _iter_valid_subtotal_dicts(self):
"""Generate each insertion dict that represents a valid subtotal."""
for insertion_dict in self._insertion_dicts:
# ---skip any non-dicts---
if not isinstance(insertion_dict, dict):
continue
# ---skip any non-subtotal insertions---
if insertion_dict.get("function") != "subtotal":
continue
# ---skip any malformed subtotal-dicts---
if not {"anchor", "args", "name"}.issubset(insertion_dict.keys()):
continue
# ---skip if doesn't reference at least one non-missing element---
if not self._element_ids.intersection(insertion_dict["args"]):
continue
# ---an insertion-dict that successfully runs this gauntlet
# ---is a valid subtotal dict
yield insertion_dict | [
"def",
"_iter_valid_subtotal_dicts",
"(",
"self",
")",
":",
"for",
"insertion_dict",
"in",
"self",
".",
"_insertion_dicts",
":",
"# ---skip any non-dicts---",
"if",
"not",
"isinstance",
"(",
"insertion_dict",
",",
"dict",
")",
":",
"continue",
"# ---skip any non-subto... | Generate each insertion dict that represents a valid subtotal. | [
"Generate",
"each",
"insertion",
"dict",
"that",
"represents",
"a",
"valid",
"subtotal",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L681-L702 | train | 37,158 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _Subtotals._subtotals | def _subtotals(self):
"""Composed tuple storing actual sequence of _Subtotal objects."""
return tuple(
_Subtotal(subtotal_dict, self.valid_elements)
for subtotal_dict in self._iter_valid_subtotal_dicts()
) | python | def _subtotals(self):
"""Composed tuple storing actual sequence of _Subtotal objects."""
return tuple(
_Subtotal(subtotal_dict, self.valid_elements)
for subtotal_dict in self._iter_valid_subtotal_dicts()
) | [
"def",
"_subtotals",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"_Subtotal",
"(",
"subtotal_dict",
",",
"self",
".",
"valid_elements",
")",
"for",
"subtotal_dict",
"in",
"self",
".",
"_iter_valid_subtotal_dicts",
"(",
")",
")"
] | Composed tuple storing actual sequence of _Subtotal objects. | [
"Composed",
"tuple",
"storing",
"actual",
"sequence",
"of",
"_Subtotal",
"objects",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L705-L710 | train | 37,159 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _Subtotal.anchor | def anchor(self):
"""int or str indicating element under which to insert this subtotal.
An int anchor is the id of the dimension element (category or
subvariable) under which to place this subtotal. The return value can
also be one of 'top' or 'bottom'.
The return value defaults to 'bottom' for an anchor referring to an
element that is no longer present in the dimension or an element that
represents missing data.
"""
anchor = self._subtotal_dict["anchor"]
try:
anchor = int(anchor)
if anchor not in self.valid_elements.element_ids:
return "bottom"
return anchor
except (TypeError, ValueError):
return anchor.lower() | python | def anchor(self):
"""int or str indicating element under which to insert this subtotal.
An int anchor is the id of the dimension element (category or
subvariable) under which to place this subtotal. The return value can
also be one of 'top' or 'bottom'.
The return value defaults to 'bottom' for an anchor referring to an
element that is no longer present in the dimension or an element that
represents missing data.
"""
anchor = self._subtotal_dict["anchor"]
try:
anchor = int(anchor)
if anchor not in self.valid_elements.element_ids:
return "bottom"
return anchor
except (TypeError, ValueError):
return anchor.lower() | [
"def",
"anchor",
"(",
"self",
")",
":",
"anchor",
"=",
"self",
".",
"_subtotal_dict",
"[",
"\"anchor\"",
"]",
"try",
":",
"anchor",
"=",
"int",
"(",
"anchor",
")",
"if",
"anchor",
"not",
"in",
"self",
".",
"valid_elements",
".",
"element_ids",
":",
"re... | int or str indicating element under which to insert this subtotal.
An int anchor is the id of the dimension element (category or
subvariable) under which to place this subtotal. The return value can
also be one of 'top' or 'bottom'.
The return value defaults to 'bottom' for an anchor referring to an
element that is no longer present in the dimension or an element that
represents missing data. | [
"int",
"or",
"str",
"indicating",
"element",
"under",
"which",
"to",
"insert",
"this",
"subtotal",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L721-L739 | train | 37,160 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _Subtotal.anchor_idx | def anchor_idx(self):
"""int or str representing index of anchor element in dimension.
When the anchor is an operation, like 'top' or 'bottom'
"""
anchor = self.anchor
if anchor in ["top", "bottom"]:
return anchor
return self.valid_elements.get_by_id(anchor).index_in_valids | python | def anchor_idx(self):
"""int or str representing index of anchor element in dimension.
When the anchor is an operation, like 'top' or 'bottom'
"""
anchor = self.anchor
if anchor in ["top", "bottom"]:
return anchor
return self.valid_elements.get_by_id(anchor).index_in_valids | [
"def",
"anchor_idx",
"(",
"self",
")",
":",
"anchor",
"=",
"self",
".",
"anchor",
"if",
"anchor",
"in",
"[",
"\"top\"",
",",
"\"bottom\"",
"]",
":",
"return",
"anchor",
"return",
"self",
".",
"valid_elements",
".",
"get_by_id",
"(",
"anchor",
")",
".",
... | int or str representing index of anchor element in dimension.
When the anchor is an operation, like 'top' or 'bottom' | [
"int",
"or",
"str",
"representing",
"index",
"of",
"anchor",
"element",
"in",
"dimension",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L742-L750 | train | 37,161 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _Subtotal.addend_ids | def addend_ids(self):
"""tuple of int ids of elements contributing to this subtotal.
Any element id not present in the dimension or present but
representing missing data is excluded.
"""
return tuple(
arg
for arg in self._subtotal_dict.get("args", [])
if arg in self.valid_elements.element_ids
) | python | def addend_ids(self):
"""tuple of int ids of elements contributing to this subtotal.
Any element id not present in the dimension or present but
representing missing data is excluded.
"""
return tuple(
arg
for arg in self._subtotal_dict.get("args", [])
if arg in self.valid_elements.element_ids
) | [
"def",
"addend_ids",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"arg",
"for",
"arg",
"in",
"self",
".",
"_subtotal_dict",
".",
"get",
"(",
"\"args\"",
",",
"[",
"]",
")",
"if",
"arg",
"in",
"self",
".",
"valid_elements",
".",
"element_ids",
")"
] | tuple of int ids of elements contributing to this subtotal.
Any element id not present in the dimension or present but
representing missing data is excluded. | [
"tuple",
"of",
"int",
"ids",
"of",
"elements",
"contributing",
"to",
"this",
"subtotal",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L753-L763 | train | 37,162 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _Subtotal.addend_idxs | def addend_idxs(self):
"""tuple of int index of each addend element for this subtotal.
The length of the tuple is the same as that for `.addend_ids`, but
each value repesents the offset of that element within the dimension,
rather than its element id.
"""
return tuple(
self.valid_elements.get_by_id(addend_id).index_in_valids
for addend_id in self.addend_ids
) | python | def addend_idxs(self):
"""tuple of int index of each addend element for this subtotal.
The length of the tuple is the same as that for `.addend_ids`, but
each value repesents the offset of that element within the dimension,
rather than its element id.
"""
return tuple(
self.valid_elements.get_by_id(addend_id).index_in_valids
for addend_id in self.addend_ids
) | [
"def",
"addend_idxs",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"self",
".",
"valid_elements",
".",
"get_by_id",
"(",
"addend_id",
")",
".",
"index_in_valids",
"for",
"addend_id",
"in",
"self",
".",
"addend_ids",
")"
] | tuple of int index of each addend element for this subtotal.
The length of the tuple is the same as that for `.addend_ids`, but
each value repesents the offset of that element within the dimension,
rather than its element id. | [
"tuple",
"of",
"int",
"index",
"of",
"each",
"addend",
"element",
"for",
"this",
"subtotal",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L766-L776 | train | 37,163 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/scripts/build_collection.py | create_data_file_by_format | def create_data_file_by_format(directory_path = None):
"""
Browse subdirectories to extract stata and sas files
"""
stata_files = []
sas_files = []
for root, subdirs, files in os.walk(directory_path):
for file_name in files:
file_path = os.path.join(root, file_name)
if os.path.basename(file_name).endswith(".dta"):
log.info("Found stata file {}".format(file_path))
stata_files.append(file_path)
if os.path.basename(file_name).endswith(".sas7bdat"):
log.info("Found sas file {}".format(file_path))
sas_files.append(file_path)
return {'stata': stata_files, 'sas': sas_files} | python | def create_data_file_by_format(directory_path = None):
"""
Browse subdirectories to extract stata and sas files
"""
stata_files = []
sas_files = []
for root, subdirs, files in os.walk(directory_path):
for file_name in files:
file_path = os.path.join(root, file_name)
if os.path.basename(file_name).endswith(".dta"):
log.info("Found stata file {}".format(file_path))
stata_files.append(file_path)
if os.path.basename(file_name).endswith(".sas7bdat"):
log.info("Found sas file {}".format(file_path))
sas_files.append(file_path)
return {'stata': stata_files, 'sas': sas_files} | [
"def",
"create_data_file_by_format",
"(",
"directory_path",
"=",
"None",
")",
":",
"stata_files",
"=",
"[",
"]",
"sas_files",
"=",
"[",
"]",
"for",
"root",
",",
"subdirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"directory_path",
")",
":",
"for",
"fi... | Browse subdirectories to extract stata and sas files | [
"Browse",
"subdirectories",
"to",
"extract",
"stata",
"and",
"sas",
"files"
] | bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358 | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/scripts/build_collection.py#L55-L71 | train | 37,164 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.as_array | def as_array(
self,
include_missing=False,
weighted=True,
include_transforms_for_dims=None,
prune=False,
):
"""Return `ndarray` representing cube values.
Returns the tabular representation of the crunch cube. The returned
array has the same number of dimensions as the cube. E.g. for
a cross-tab representation of a categorical and numerical variable,
the resulting cube will have two dimensions.
*include_missing* (bool): Include rows/cols for missing values.
Example 1 (Categorical x Categorical)::
>>> cube = CrunchCube(response)
>>> cube.as_array()
np.array([
[5, 2],
[5, 3],
])
Example 2 (Categorical x Categorical, include missing values)::
>>> cube = CrunchCube(response)
>>> cube.as_array(include_missing=True)
np.array([
[5, 3, 2, 0],
[5, 2, 3, 0],
[0, 0, 0, 0],
])
"""
array = self._as_array(
include_missing=include_missing,
weighted=weighted,
include_transforms_for_dims=include_transforms_for_dims,
)
# ---prune array if pruning was requested---
if prune:
array = self._prune_body(array, transforms=include_transforms_for_dims)
return self._drop_mr_cat_dims(array) | python | def as_array(
self,
include_missing=False,
weighted=True,
include_transforms_for_dims=None,
prune=False,
):
"""Return `ndarray` representing cube values.
Returns the tabular representation of the crunch cube. The returned
array has the same number of dimensions as the cube. E.g. for
a cross-tab representation of a categorical and numerical variable,
the resulting cube will have two dimensions.
*include_missing* (bool): Include rows/cols for missing values.
Example 1 (Categorical x Categorical)::
>>> cube = CrunchCube(response)
>>> cube.as_array()
np.array([
[5, 2],
[5, 3],
])
Example 2 (Categorical x Categorical, include missing values)::
>>> cube = CrunchCube(response)
>>> cube.as_array(include_missing=True)
np.array([
[5, 3, 2, 0],
[5, 2, 3, 0],
[0, 0, 0, 0],
])
"""
array = self._as_array(
include_missing=include_missing,
weighted=weighted,
include_transforms_for_dims=include_transforms_for_dims,
)
# ---prune array if pruning was requested---
if prune:
array = self._prune_body(array, transforms=include_transforms_for_dims)
return self._drop_mr_cat_dims(array) | [
"def",
"as_array",
"(",
"self",
",",
"include_missing",
"=",
"False",
",",
"weighted",
"=",
"True",
",",
"include_transforms_for_dims",
"=",
"None",
",",
"prune",
"=",
"False",
",",
")",
":",
"array",
"=",
"self",
".",
"_as_array",
"(",
"include_missing",
... | Return `ndarray` representing cube values.
Returns the tabular representation of the crunch cube. The returned
array has the same number of dimensions as the cube. E.g. for
a cross-tab representation of a categorical and numerical variable,
the resulting cube will have two dimensions.
*include_missing* (bool): Include rows/cols for missing values.
Example 1 (Categorical x Categorical)::
>>> cube = CrunchCube(response)
>>> cube.as_array()
np.array([
[5, 2],
[5, 3],
])
Example 2 (Categorical x Categorical, include missing values)::
>>> cube = CrunchCube(response)
>>> cube.as_array(include_missing=True)
np.array([
[5, 3, 2, 0],
[5, 2, 3, 0],
[0, 0, 0, 0],
]) | [
"Return",
"ndarray",
"representing",
"cube",
"values",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L81-L126 | train | 37,165 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.count | def count(self, weighted=True):
"""Return numberic count of rows considered for cube response."""
return self._measures.weighted_n if weighted else self._measures.unweighted_n | python | def count(self, weighted=True):
"""Return numberic count of rows considered for cube response."""
return self._measures.weighted_n if weighted else self._measures.unweighted_n | [
"def",
"count",
"(",
"self",
",",
"weighted",
"=",
"True",
")",
":",
"return",
"self",
".",
"_measures",
".",
"weighted_n",
"if",
"weighted",
"else",
"self",
".",
"_measures",
".",
"unweighted_n"
] | Return numberic count of rows considered for cube response. | [
"Return",
"numberic",
"count",
"of",
"rows",
"considered",
"for",
"cube",
"response",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L132-L134 | train | 37,166 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.index | def index(self, weighted=True, prune=False):
"""Return cube index measurement.
This function is deprecated. Use index_table from CubeSlice.
"""
warnings.warn(
"CrunchCube.index() is deprecated. Use CubeSlice.index_table().",
DeprecationWarning,
)
return Index.data(self, weighted, prune) | python | def index(self, weighted=True, prune=False):
"""Return cube index measurement.
This function is deprecated. Use index_table from CubeSlice.
"""
warnings.warn(
"CrunchCube.index() is deprecated. Use CubeSlice.index_table().",
DeprecationWarning,
)
return Index.data(self, weighted, prune) | [
"def",
"index",
"(",
"self",
",",
"weighted",
"=",
"True",
",",
"prune",
"=",
"False",
")",
":",
"warnings",
".",
"warn",
"(",
"\"CrunchCube.index() is deprecated. Use CubeSlice.index_table().\"",
",",
"DeprecationWarning",
",",
")",
"return",
"Index",
".",
"data"... | Return cube index measurement.
This function is deprecated. Use index_table from CubeSlice. | [
"Return",
"cube",
"index",
"measurement",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L189-L198 | train | 37,167 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.is_univariate_ca | def is_univariate_ca(self):
"""True if cube only contains a CA dimension-pair, in either order."""
return self.ndim == 2 and set(self.dim_types) == {DT.CA_SUBVAR, DT.CA_CAT} | python | def is_univariate_ca(self):
"""True if cube only contains a CA dimension-pair, in either order."""
return self.ndim == 2 and set(self.dim_types) == {DT.CA_SUBVAR, DT.CA_CAT} | [
"def",
"is_univariate_ca",
"(",
"self",
")",
":",
"return",
"self",
".",
"ndim",
"==",
"2",
"and",
"set",
"(",
"self",
".",
"dim_types",
")",
"==",
"{",
"DT",
".",
"CA_SUBVAR",
",",
"DT",
".",
"CA_CAT",
"}"
] | True if cube only contains a CA dimension-pair, in either order. | [
"True",
"if",
"cube",
"only",
"contains",
"a",
"CA",
"dimension",
"-",
"pair",
"in",
"either",
"order",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L228-L230 | train | 37,168 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.labels | def labels(self, include_missing=False, include_transforms_for_dims=False):
"""Gets labels for each cube's dimension.
Args
include_missing (bool): Include labels for missing values
Returns
labels (list of lists): Labels for each dimension
"""
return [
dim.labels(include_missing, include_transforms_for_dims)
for dim in self.dimensions
] | python | def labels(self, include_missing=False, include_transforms_for_dims=False):
"""Gets labels for each cube's dimension.
Args
include_missing (bool): Include labels for missing values
Returns
labels (list of lists): Labels for each dimension
"""
return [
dim.labels(include_missing, include_transforms_for_dims)
for dim in self.dimensions
] | [
"def",
"labels",
"(",
"self",
",",
"include_missing",
"=",
"False",
",",
"include_transforms_for_dims",
"=",
"False",
")",
":",
"return",
"[",
"dim",
".",
"labels",
"(",
"include_missing",
",",
"include_transforms_for_dims",
")",
"for",
"dim",
"in",
"self",
".... | Gets labels for each cube's dimension.
Args
include_missing (bool): Include labels for missing values
Returns
labels (list of lists): Labels for each dimension | [
"Gets",
"labels",
"for",
"each",
"cube",
"s",
"dimension",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L237-L249 | train | 37,169 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.margin | def margin(
self,
axis=None,
weighted=True,
include_missing=False,
include_transforms_for_dims=None,
prune=False,
include_mr_cat=False,
):
"""Get margin for the selected axis.
the selected axis. For MR variables, this is the sum of the selected
and non-selected slices.
Args
axis (int): Axis across the margin is calculated. If no axis is
provided the margin is calculated across all axis.
For Categoricals, Num, Datetime, and Text, this
translates to sumation of all elements.
Returns
Calculated margin for the selected axis
Example 1:
>>> cube = CrunchCube(fixt_cat_x_cat)
np.array([
[5, 2],
[5, 3],
])
>>> cube.margin(axis=0)
np.array([10, 5])
Example 2:
>>> cube = CrunchCube(fixt_cat_x_num_x_datetime)
np.array([
[[1, 1],
[0, 0],
[0, 0],
[0, 0]],
[[2, 1],
[1, 1],
[0, 0],
[0, 0]],
[[0, 0],
[2, 3],
[0, 0],
[0, 0]],
[[0, 0],
[0, 0],
[3, 2],
[0, 0]],
[[0, 0],
[0, 0],
[1, 1],
[0, 1]]
])
>>> cube.margin(axis=0)
np.array([
[3, 2],
[3, 4],
[4, 3],
[0, 1],
])
"""
table = self._counts(weighted).raw_cube_array
new_axis = self._adjust_axis(axis)
index = tuple(
None if i in new_axis else slice(None) for i, _ in enumerate(table.shape)
)
# Calculate denominator. Only include those H&S dimensions, across
# which we DON'T sum. These H&S are needed because of the shape, when
# dividing. Those across dims which are summed across MUST NOT be
# included, because they would change the result.
hs_dims = self._hs_dims_for_den(include_transforms_for_dims, axis)
den = self._apply_subtotals(
self._apply_missings(table, include_missing=include_missing), hs_dims
)
# Apply correct mask (based on the as_array shape)
arr = self._as_array(
include_transforms_for_dims=hs_dims, include_missing=include_missing
)
# ---prune array if pruning was requested---
if prune:
arr = self._prune_body(arr, transforms=hs_dims)
arr = self._drop_mr_cat_dims(arr, fix_valids=include_missing)
if isinstance(arr, np.ma.core.MaskedArray):
# Inflate the reduced version of the array, to match the
# non-reduced version, for the purposes of creating the correct
# mask. Create additional dimension (with no elements) where MR_CAT
# dimensions should be. Don't inflate 0th dimension if it has only
# a single element, because it's not being reduced
# in self._drop_mr_cat_dims
inflate_ind = tuple(
(
None
if (
d.dimension_type == DT.MR_CAT
or i != 0
and (n <= 1 or len(d.valid_elements) <= 1)
)
else slice(None)
)
for i, (d, n) in enumerate(zip(self._all_dimensions, table.shape))
)
mask = np.logical_or(np.zeros(den.shape, dtype=bool), arr.mask[inflate_ind])
den = np.ma.masked_array(den, mask)
if (
self.ndim != 1
or axis is None
or axis == 0
and len(self._all_dimensions) == 1
):
# Special case for 1D cube wigh MR, for "Table" direction
den = np.sum(den, axis=new_axis)[index]
den = self._drop_mr_cat_dims(
den, fix_valids=(include_missing or include_mr_cat)
)
if den.shape[0] == 1 and len(den.shape) > 1 and self.ndim < 3:
den = den.reshape(den.shape[1:])
return den | python | def margin(
self,
axis=None,
weighted=True,
include_missing=False,
include_transforms_for_dims=None,
prune=False,
include_mr_cat=False,
):
"""Get margin for the selected axis.
the selected axis. For MR variables, this is the sum of the selected
and non-selected slices.
Args
axis (int): Axis across the margin is calculated. If no axis is
provided the margin is calculated across all axis.
For Categoricals, Num, Datetime, and Text, this
translates to sumation of all elements.
Returns
Calculated margin for the selected axis
Example 1:
>>> cube = CrunchCube(fixt_cat_x_cat)
np.array([
[5, 2],
[5, 3],
])
>>> cube.margin(axis=0)
np.array([10, 5])
Example 2:
>>> cube = CrunchCube(fixt_cat_x_num_x_datetime)
np.array([
[[1, 1],
[0, 0],
[0, 0],
[0, 0]],
[[2, 1],
[1, 1],
[0, 0],
[0, 0]],
[[0, 0],
[2, 3],
[0, 0],
[0, 0]],
[[0, 0],
[0, 0],
[3, 2],
[0, 0]],
[[0, 0],
[0, 0],
[1, 1],
[0, 1]]
])
>>> cube.margin(axis=0)
np.array([
[3, 2],
[3, 4],
[4, 3],
[0, 1],
])
"""
table = self._counts(weighted).raw_cube_array
new_axis = self._adjust_axis(axis)
index = tuple(
None if i in new_axis else slice(None) for i, _ in enumerate(table.shape)
)
# Calculate denominator. Only include those H&S dimensions, across
# which we DON'T sum. These H&S are needed because of the shape, when
# dividing. Those across dims which are summed across MUST NOT be
# included, because they would change the result.
hs_dims = self._hs_dims_for_den(include_transforms_for_dims, axis)
den = self._apply_subtotals(
self._apply_missings(table, include_missing=include_missing), hs_dims
)
# Apply correct mask (based on the as_array shape)
arr = self._as_array(
include_transforms_for_dims=hs_dims, include_missing=include_missing
)
# ---prune array if pruning was requested---
if prune:
arr = self._prune_body(arr, transforms=hs_dims)
arr = self._drop_mr_cat_dims(arr, fix_valids=include_missing)
if isinstance(arr, np.ma.core.MaskedArray):
# Inflate the reduced version of the array, to match the
# non-reduced version, for the purposes of creating the correct
# mask. Create additional dimension (with no elements) where MR_CAT
# dimensions should be. Don't inflate 0th dimension if it has only
# a single element, because it's not being reduced
# in self._drop_mr_cat_dims
inflate_ind = tuple(
(
None
if (
d.dimension_type == DT.MR_CAT
or i != 0
and (n <= 1 or len(d.valid_elements) <= 1)
)
else slice(None)
)
for i, (d, n) in enumerate(zip(self._all_dimensions, table.shape))
)
mask = np.logical_or(np.zeros(den.shape, dtype=bool), arr.mask[inflate_ind])
den = np.ma.masked_array(den, mask)
if (
self.ndim != 1
or axis is None
or axis == 0
and len(self._all_dimensions) == 1
):
# Special case for 1D cube wigh MR, for "Table" direction
den = np.sum(den, axis=new_axis)[index]
den = self._drop_mr_cat_dims(
den, fix_valids=(include_missing or include_mr_cat)
)
if den.shape[0] == 1 and len(den.shape) > 1 and self.ndim < 3:
den = den.reshape(den.shape[1:])
return den | [
"def",
"margin",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"weighted",
"=",
"True",
",",
"include_missing",
"=",
"False",
",",
"include_transforms_for_dims",
"=",
"None",
",",
"prune",
"=",
"False",
",",
"include_mr_cat",
"=",
"False",
",",
")",
":",
"... | Get margin for the selected axis.
the selected axis. For MR variables, this is the sum of the selected
and non-selected slices.
Args
axis (int): Axis across the margin is calculated. If no axis is
provided the margin is calculated across all axis.
For Categoricals, Num, Datetime, and Text, this
translates to sumation of all elements.
Returns
Calculated margin for the selected axis
Example 1:
>>> cube = CrunchCube(fixt_cat_x_cat)
np.array([
[5, 2],
[5, 3],
])
>>> cube.margin(axis=0)
np.array([10, 5])
Example 2:
>>> cube = CrunchCube(fixt_cat_x_num_x_datetime)
np.array([
[[1, 1],
[0, 0],
[0, 0],
[0, 0]],
[[2, 1],
[1, 1],
[0, 0],
[0, 0]],
[[0, 0],
[2, 3],
[0, 0],
[0, 0]],
[[0, 0],
[0, 0],
[3, 2],
[0, 0]],
[[0, 0],
[0, 0],
[1, 1],
[0, 1]]
])
>>> cube.margin(axis=0)
np.array([
[3, 2],
[3, 4],
[4, 3],
[0, 1],
]) | [
"Get",
"margin",
"for",
"the",
"selected",
"axis",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L251-L379 | train | 37,170 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.mr_dim_ind | def mr_dim_ind(self):
"""Return int, tuple of int, or None, representing MR indices.
The return value represents the index of each multiple-response (MR)
dimension in this cube. Return value is None if there are no MR
dimensions, and int if there is one MR dimension, and a tuple of int
when there are more than one. The index is the (zero-based) position
of the MR dimensions in the _ApparentDimensions sequence returned by
the :attr"`.dimensions` property.
"""
# TODO: rename to `mr_dim_idxs` or better yet get rid of need for
# this as it's really a cube internal characteristic.
# TODO: Make this return a tuple in all cases, like (), (1,), or (0, 2).
indices = tuple(
idx
for idx, d in enumerate(self.dimensions)
if d.dimension_type == DT.MR_SUBVAR
)
if indices == ():
return None
if len(indices) == 1:
return indices[0]
return indices | python | def mr_dim_ind(self):
"""Return int, tuple of int, or None, representing MR indices.
The return value represents the index of each multiple-response (MR)
dimension in this cube. Return value is None if there are no MR
dimensions, and int if there is one MR dimension, and a tuple of int
when there are more than one. The index is the (zero-based) position
of the MR dimensions in the _ApparentDimensions sequence returned by
the :attr"`.dimensions` property.
"""
# TODO: rename to `mr_dim_idxs` or better yet get rid of need for
# this as it's really a cube internal characteristic.
# TODO: Make this return a tuple in all cases, like (), (1,), or (0, 2).
indices = tuple(
idx
for idx, d in enumerate(self.dimensions)
if d.dimension_type == DT.MR_SUBVAR
)
if indices == ():
return None
if len(indices) == 1:
return indices[0]
return indices | [
"def",
"mr_dim_ind",
"(",
"self",
")",
":",
"# TODO: rename to `mr_dim_idxs` or better yet get rid of need for",
"# this as it's really a cube internal characteristic.",
"# TODO: Make this return a tuple in all cases, like (), (1,), or (0, 2).",
"indices",
"=",
"tuple",
"(",
"idx",
"for"... | Return int, tuple of int, or None, representing MR indices.
The return value represents the index of each multiple-response (MR)
dimension in this cube. Return value is None if there are no MR
dimensions, and int if there is one MR dimension, and a tuple of int
when there are more than one. The index is the (zero-based) position
of the MR dimensions in the _ApparentDimensions sequence returned by
the :attr"`.dimensions` property. | [
"Return",
"int",
"tuple",
"of",
"int",
"or",
"None",
"representing",
"MR",
"indices",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L387-L409 | train | 37,171 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.population_counts | def population_counts(
self,
population_size,
weighted=True,
include_missing=False,
include_transforms_for_dims=None,
prune=False,
):
"""Return counts scaled in proportion to overall population.
The return value is a numpy.ndarray object. Count values are scaled
proportionally to approximate their value if the entire population
had been sampled. This calculation is based on the estimated size of
the population provided as *population size*. The remaining arguments
have the same meaning as they do for the `.proportions()` method.
Example::
>>> cube = CrunchCube(fixt_cat_x_cat)
>>> cube.as_array()
np.array([
[5, 2],
[5, 3],
])
>>> cube.population_counts(9000)
np.array([
[3000, 1200],
[3000, 1800],
])
"""
population_counts = [
slice_.population_counts(
population_size,
weighted=weighted,
include_missing=include_missing,
include_transforms_for_dims=include_transforms_for_dims,
prune=prune,
)
for slice_ in self.slices
]
if len(population_counts) > 1:
return np.array(population_counts)
return population_counts[0] | python | def population_counts(
self,
population_size,
weighted=True,
include_missing=False,
include_transforms_for_dims=None,
prune=False,
):
"""Return counts scaled in proportion to overall population.
The return value is a numpy.ndarray object. Count values are scaled
proportionally to approximate their value if the entire population
had been sampled. This calculation is based on the estimated size of
the population provided as *population size*. The remaining arguments
have the same meaning as they do for the `.proportions()` method.
Example::
>>> cube = CrunchCube(fixt_cat_x_cat)
>>> cube.as_array()
np.array([
[5, 2],
[5, 3],
])
>>> cube.population_counts(9000)
np.array([
[3000, 1200],
[3000, 1800],
])
"""
population_counts = [
slice_.population_counts(
population_size,
weighted=weighted,
include_missing=include_missing,
include_transforms_for_dims=include_transforms_for_dims,
prune=prune,
)
for slice_ in self.slices
]
if len(population_counts) > 1:
return np.array(population_counts)
return population_counts[0] | [
"def",
"population_counts",
"(",
"self",
",",
"population_size",
",",
"weighted",
"=",
"True",
",",
"include_missing",
"=",
"False",
",",
"include_transforms_for_dims",
"=",
"None",
",",
"prune",
"=",
"False",
",",
")",
":",
"population_counts",
"=",
"[",
"sli... | Return counts scaled in proportion to overall population.
The return value is a numpy.ndarray object. Count values are scaled
proportionally to approximate their value if the entire population
had been sampled. This calculation is based on the estimated size of
the population provided as *population size*. The remaining arguments
have the same meaning as they do for the `.proportions()` method.
Example::
>>> cube = CrunchCube(fixt_cat_x_cat)
>>> cube.as_array()
np.array([
[5, 2],
[5, 3],
])
>>> cube.population_counts(9000)
np.array([
[3000, 1200],
[3000, 1800],
]) | [
"Return",
"counts",
"scaled",
"in",
"proportion",
"to",
"overall",
"population",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L469-L512 | train | 37,172 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.proportions | def proportions(
self,
axis=None,
weighted=True,
include_transforms_for_dims=None,
include_mr_cat=False,
prune=False,
):
"""Return percentage values for cube as `numpy.ndarray`.
This function calculates the proportions across the selected axis
of a crunch cube. For most variable types, it means the value divided
by the margin value. For a multiple-response variable, the value is
divided by the sum of selected and non-selected slices.
*axis* (int): base axis of proportions calculation. If no axis is
provided, calculations are done across the entire table.
*weighted* (bool): Specifies weighted or non-weighted proportions.
*include_transforms_for_dims* (list): Also include headings and
subtotals transformations for the provided dimensions. If the
dimensions have the transformations, they'll be included in the
resulting numpy array. If the dimensions don't have the
transformations, nothing will happen (the result will be the same as
if the argument weren't provided).
*include_transforms_for_dims* (list): Include headers and subtotals
(H&S) across various dimensions. The dimensions are provided as list
elements. For example: "include_transforms_for_dims=[0, 1]" instructs
the CrunchCube to return H&S for both rows and columns (if it's a 2D
cube).
*include_mr_cat* (bool): Include MR categories.
*prune* (bool): Instructs the CrunchCube to prune empty rows/cols.
Emptiness is determined by the state of the margin (if it's either
0 or nan at certain index). If it is, the corresponding row/col is
not included in the result.
Example 1::
>>> cube = CrunchCube(fixt_cat_x_cat)
np.array([
[5, 2],
[5, 3],
])
>>> cube.proportions()
np.array([
[0.3333333, 0.1333333],
[0.3333333, 0.2000000],
])
Example 2::
>>> cube = CrunchCube(fixt_cat_x_cat)
np.array([
[5, 2],
[5, 3],
])
>>> cube.proportions(axis=0)
np.array([
[0.5, 0.4],
[0.5, 0.6],
])
"""
# Calculate numerator from table (include all H&S dimensions).
table = self._measure(weighted).raw_cube_array
num = self._apply_subtotals(
self._apply_missings(table), include_transforms_for_dims
)
proportions = num / self._denominator(
weighted, include_transforms_for_dims, axis
)
if not include_mr_cat:
proportions = self._drop_mr_cat_dims(proportions)
# Apply correct mask (based on the as_array shape)
arr = self.as_array(
prune=prune, include_transforms_for_dims=include_transforms_for_dims
)
if isinstance(arr, np.ma.core.MaskedArray):
proportions = np.ma.masked_array(proportions, arr.mask)
return proportions | python | def proportions(
self,
axis=None,
weighted=True,
include_transforms_for_dims=None,
include_mr_cat=False,
prune=False,
):
"""Return percentage values for cube as `numpy.ndarray`.
This function calculates the proportions across the selected axis
of a crunch cube. For most variable types, it means the value divided
by the margin value. For a multiple-response variable, the value is
divided by the sum of selected and non-selected slices.
*axis* (int): base axis of proportions calculation. If no axis is
provided, calculations are done across the entire table.
*weighted* (bool): Specifies weighted or non-weighted proportions.
*include_transforms_for_dims* (list): Also include headings and
subtotals transformations for the provided dimensions. If the
dimensions have the transformations, they'll be included in the
resulting numpy array. If the dimensions don't have the
transformations, nothing will happen (the result will be the same as
if the argument weren't provided).
*include_transforms_for_dims* (list): Include headers and subtotals
(H&S) across various dimensions. The dimensions are provided as list
elements. For example: "include_transforms_for_dims=[0, 1]" instructs
the CrunchCube to return H&S for both rows and columns (if it's a 2D
cube).
*include_mr_cat* (bool): Include MR categories.
*prune* (bool): Instructs the CrunchCube to prune empty rows/cols.
Emptiness is determined by the state of the margin (if it's either
0 or nan at certain index). If it is, the corresponding row/col is
not included in the result.
Example 1::
>>> cube = CrunchCube(fixt_cat_x_cat)
np.array([
[5, 2],
[5, 3],
])
>>> cube.proportions()
np.array([
[0.3333333, 0.1333333],
[0.3333333, 0.2000000],
])
Example 2::
>>> cube = CrunchCube(fixt_cat_x_cat)
np.array([
[5, 2],
[5, 3],
])
>>> cube.proportions(axis=0)
np.array([
[0.5, 0.4],
[0.5, 0.6],
])
"""
# Calculate numerator from table (include all H&S dimensions).
table = self._measure(weighted).raw_cube_array
num = self._apply_subtotals(
self._apply_missings(table), include_transforms_for_dims
)
proportions = num / self._denominator(
weighted, include_transforms_for_dims, axis
)
if not include_mr_cat:
proportions = self._drop_mr_cat_dims(proportions)
# Apply correct mask (based on the as_array shape)
arr = self.as_array(
prune=prune, include_transforms_for_dims=include_transforms_for_dims
)
if isinstance(arr, np.ma.core.MaskedArray):
proportions = np.ma.masked_array(proportions, arr.mask)
return proportions | [
"def",
"proportions",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"weighted",
"=",
"True",
",",
"include_transforms_for_dims",
"=",
"None",
",",
"include_mr_cat",
"=",
"False",
",",
"prune",
"=",
"False",
",",
")",
":",
"# Calculate numerator from table (include... | Return percentage values for cube as `numpy.ndarray`.
This function calculates the proportions across the selected axis
of a crunch cube. For most variable types, it means the value divided
by the margin value. For a multiple-response variable, the value is
divided by the sum of selected and non-selected slices.
*axis* (int): base axis of proportions calculation. If no axis is
provided, calculations are done across the entire table.
*weighted* (bool): Specifies weighted or non-weighted proportions.
*include_transforms_for_dims* (list): Also include headings and
subtotals transformations for the provided dimensions. If the
dimensions have the transformations, they'll be included in the
resulting numpy array. If the dimensions don't have the
transformations, nothing will happen (the result will be the same as
if the argument weren't provided).
*include_transforms_for_dims* (list): Include headers and subtotals
(H&S) across various dimensions. The dimensions are provided as list
elements. For example: "include_transforms_for_dims=[0, 1]" instructs
the CrunchCube to return H&S for both rows and columns (if it's a 2D
cube).
*include_mr_cat* (bool): Include MR categories.
*prune* (bool): Instructs the CrunchCube to prune empty rows/cols.
Emptiness is determined by the state of the margin (if it's either
0 or nan at certain index). If it is, the corresponding row/col is
not included in the result.
Example 1::
>>> cube = CrunchCube(fixt_cat_x_cat)
np.array([
[5, 2],
[5, 3],
])
>>> cube.proportions()
np.array([
[0.3333333, 0.1333333],
[0.3333333, 0.2000000],
])
Example 2::
>>> cube = CrunchCube(fixt_cat_x_cat)
np.array([
[5, 2],
[5, 3],
])
>>> cube.proportions(axis=0)
np.array([
[0.5, 0.4],
[0.5, 0.6],
]) | [
"Return",
"percentage",
"values",
"for",
"cube",
"as",
"numpy",
".",
"ndarray",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L525-L613 | train | 37,173 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._denominator | def _denominator(self, weighted, include_transforms_for_dims, axis):
"""Calculate denominator for percentages.
Only include those H&S dimensions, across which we DON'T sum. These H&S
are needed because of the shape, when dividing. Those across dims
which are summed across MUST NOT be included, because they would
change the result."""
table = self._measure(weighted).raw_cube_array
new_axis = self._adjust_axis(axis)
index = tuple(
None if i in new_axis else slice(None) for i, _ in enumerate(table.shape)
)
hs_dims = self._hs_dims_for_den(include_transforms_for_dims, axis)
den = self._apply_subtotals(self._apply_missings(table), hs_dims)
return np.sum(den, axis=new_axis)[index] | python | def _denominator(self, weighted, include_transforms_for_dims, axis):
"""Calculate denominator for percentages.
Only include those H&S dimensions, across which we DON'T sum. These H&S
are needed because of the shape, when dividing. Those across dims
which are summed across MUST NOT be included, because they would
change the result."""
table = self._measure(weighted).raw_cube_array
new_axis = self._adjust_axis(axis)
index = tuple(
None if i in new_axis else slice(None) for i, _ in enumerate(table.shape)
)
hs_dims = self._hs_dims_for_den(include_transforms_for_dims, axis)
den = self._apply_subtotals(self._apply_missings(table), hs_dims)
return np.sum(den, axis=new_axis)[index] | [
"def",
"_denominator",
"(",
"self",
",",
"weighted",
",",
"include_transforms_for_dims",
",",
"axis",
")",
":",
"table",
"=",
"self",
".",
"_measure",
"(",
"weighted",
")",
".",
"raw_cube_array",
"new_axis",
"=",
"self",
".",
"_adjust_axis",
"(",
"axis",
")"... | Calculate denominator for percentages.
Only include those H&S dimensions, across which we DON'T sum. These H&S
are needed because of the shape, when dividing. Those across dims
which are summed across MUST NOT be included, because they would
change the result. | [
"Calculate",
"denominator",
"for",
"percentages",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L615-L630 | train | 37,174 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.scale_means | def scale_means(self, hs_dims=None, prune=False):
"""Get cube means."""
slices_means = [ScaleMeans(slice_).data for slice_ in self.slices]
if hs_dims and self.ndim > 1:
# Intersperse scale means with nans if H&S specified, and 2D. No
# need to modify 1D, as only one mean will ever be inserted.
inserted_indices = self.inserted_hs_indices()[-2:]
for scale_means in slices_means:
# Scale means 0 corresonds to the column dimension (is
# calculated by using its values). The result of it, however,
# is a row. That's why we need to check the insertions on the
# row dim (inserted columns).
if scale_means[0] is not None and 1 in hs_dims and inserted_indices[1]:
for i in inserted_indices[1]:
scale_means[0] = np.insert(scale_means[0], i, np.nan)
# Scale means 1 is a column, so we need to check
# for row insertions.
if scale_means[1] is not None and 0 in hs_dims and inserted_indices[0]:
for i in inserted_indices[0]:
scale_means[1] = np.insert(scale_means[1], i, np.nan)
if prune:
# Apply pruning
arr = self.as_array(include_transforms_for_dims=hs_dims, prune=True)
if isinstance(arr, np.ma.core.MaskedArray):
mask = arr.mask
for i, scale_means in enumerate(slices_means):
if scale_means[0] is not None:
row_mask = (
mask.all(axis=0) if self.ndim < 3 else mask.all(axis=1)[i]
)
scale_means[0] = scale_means[0][~row_mask]
if self.ndim > 1 and scale_means[1] is not None:
col_mask = (
mask.all(axis=1) if self.ndim < 3 else mask.all(axis=2)[i]
)
scale_means[1] = scale_means[1][~col_mask]
return slices_means | python | def scale_means(self, hs_dims=None, prune=False):
"""Get cube means."""
slices_means = [ScaleMeans(slice_).data for slice_ in self.slices]
if hs_dims and self.ndim > 1:
# Intersperse scale means with nans if H&S specified, and 2D. No
# need to modify 1D, as only one mean will ever be inserted.
inserted_indices = self.inserted_hs_indices()[-2:]
for scale_means in slices_means:
# Scale means 0 corresonds to the column dimension (is
# calculated by using its values). The result of it, however,
# is a row. That's why we need to check the insertions on the
# row dim (inserted columns).
if scale_means[0] is not None and 1 in hs_dims and inserted_indices[1]:
for i in inserted_indices[1]:
scale_means[0] = np.insert(scale_means[0], i, np.nan)
# Scale means 1 is a column, so we need to check
# for row insertions.
if scale_means[1] is not None and 0 in hs_dims and inserted_indices[0]:
for i in inserted_indices[0]:
scale_means[1] = np.insert(scale_means[1], i, np.nan)
if prune:
# Apply pruning
arr = self.as_array(include_transforms_for_dims=hs_dims, prune=True)
if isinstance(arr, np.ma.core.MaskedArray):
mask = arr.mask
for i, scale_means in enumerate(slices_means):
if scale_means[0] is not None:
row_mask = (
mask.all(axis=0) if self.ndim < 3 else mask.all(axis=1)[i]
)
scale_means[0] = scale_means[0][~row_mask]
if self.ndim > 1 and scale_means[1] is not None:
col_mask = (
mask.all(axis=1) if self.ndim < 3 else mask.all(axis=2)[i]
)
scale_means[1] = scale_means[1][~col_mask]
return slices_means | [
"def",
"scale_means",
"(",
"self",
",",
"hs_dims",
"=",
"None",
",",
"prune",
"=",
"False",
")",
":",
"slices_means",
"=",
"[",
"ScaleMeans",
"(",
"slice_",
")",
".",
"data",
"for",
"slice_",
"in",
"self",
".",
"slices",
"]",
"if",
"hs_dims",
"and",
... | Get cube means. | [
"Get",
"cube",
"means",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L658-L696 | train | 37,175 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.zscore | def zscore(self, weighted=True, prune=False, hs_dims=None):
"""Return ndarray with cube's zscore measurements.
Zscore is a measure of statistical significance of observed vs.
expected counts. It's only applicable to a 2D contingency tables.
For 3D cubes, the measures of separate slices are stacked together
and returned as the result.
:param weighted: Use weighted counts for zscores
:param prune: Prune based on unweighted counts
:param hs_dims: Include headers and subtotals (as NaN values)
:returns zscore: ndarray representing zscore measurements
"""
res = [s.zscore(weighted, prune, hs_dims) for s in self.slices]
return np.array(res) if self.ndim == 3 else res[0] | python | def zscore(self, weighted=True, prune=False, hs_dims=None):
"""Return ndarray with cube's zscore measurements.
Zscore is a measure of statistical significance of observed vs.
expected counts. It's only applicable to a 2D contingency tables.
For 3D cubes, the measures of separate slices are stacked together
and returned as the result.
:param weighted: Use weighted counts for zscores
:param prune: Prune based on unweighted counts
:param hs_dims: Include headers and subtotals (as NaN values)
:returns zscore: ndarray representing zscore measurements
"""
res = [s.zscore(weighted, prune, hs_dims) for s in self.slices]
return np.array(res) if self.ndim == 3 else res[0] | [
"def",
"zscore",
"(",
"self",
",",
"weighted",
"=",
"True",
",",
"prune",
"=",
"False",
",",
"hs_dims",
"=",
"None",
")",
":",
"res",
"=",
"[",
"s",
".",
"zscore",
"(",
"weighted",
",",
"prune",
",",
"hs_dims",
")",
"for",
"s",
"in",
"self",
".",... | Return ndarray with cube's zscore measurements.
Zscore is a measure of statistical significance of observed vs.
expected counts. It's only applicable to a 2D contingency tables.
For 3D cubes, the measures of separate slices are stacked together
and returned as the result.
:param weighted: Use weighted counts for zscores
:param prune: Prune based on unweighted counts
:param hs_dims: Include headers and subtotals (as NaN values)
:returns zscore: ndarray representing zscore measurements | [
"Return",
"ndarray",
"with",
"cube",
"s",
"zscore",
"measurements",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L707-L721 | train | 37,176 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.wishart_pairwise_pvals | def wishart_pairwise_pvals(self, axis=0):
"""Return matrices of column-comparison p-values as list of numpy.ndarrays.
Square, symmetric matrix along *axis* of pairwise p-values for the
null hypothesis that col[i] = col[j] for each pair of columns.
*axis* (int): axis along which to perform comparison. Only columns (0)
are implemented currently.
"""
return [slice_.wishart_pairwise_pvals(axis=axis) for slice_ in self.slices] | python | def wishart_pairwise_pvals(self, axis=0):
"""Return matrices of column-comparison p-values as list of numpy.ndarrays.
Square, symmetric matrix along *axis* of pairwise p-values for the
null hypothesis that col[i] = col[j] for each pair of columns.
*axis* (int): axis along which to perform comparison. Only columns (0)
are implemented currently.
"""
return [slice_.wishart_pairwise_pvals(axis=axis) for slice_ in self.slices] | [
"def",
"wishart_pairwise_pvals",
"(",
"self",
",",
"axis",
"=",
"0",
")",
":",
"return",
"[",
"slice_",
".",
"wishart_pairwise_pvals",
"(",
"axis",
"=",
"axis",
")",
"for",
"slice_",
"in",
"self",
".",
"slices",
"]"
] | Return matrices of column-comparison p-values as list of numpy.ndarrays.
Square, symmetric matrix along *axis* of pairwise p-values for the
null hypothesis that col[i] = col[j] for each pair of columns.
*axis* (int): axis along which to perform comparison. Only columns (0)
are implemented currently. | [
"Return",
"matrices",
"of",
"column",
"-",
"comparison",
"p",
"-",
"values",
"as",
"list",
"of",
"numpy",
".",
"ndarrays",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L723-L732 | train | 37,177 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._adjust_inserted_indices | def _adjust_inserted_indices(inserted_indices_list, prune_indices_list):
"""Adjust inserted indices, if there are pruned elements."""
# Created a copy, to preserve cached property
updated_inserted = [[i for i in dim_inds] for dim_inds in inserted_indices_list]
pruned_and_inserted = zip(prune_indices_list, updated_inserted)
for prune_inds, inserted_inds in pruned_and_inserted:
# Only prune indices if they're not H&S (inserted)
prune_inds = prune_inds[~np.in1d(prune_inds, inserted_inds)]
for i, ind in enumerate(inserted_inds):
ind -= np.sum(prune_inds < ind)
inserted_inds[i] = ind
return updated_inserted | python | def _adjust_inserted_indices(inserted_indices_list, prune_indices_list):
"""Adjust inserted indices, if there are pruned elements."""
# Created a copy, to preserve cached property
updated_inserted = [[i for i in dim_inds] for dim_inds in inserted_indices_list]
pruned_and_inserted = zip(prune_indices_list, updated_inserted)
for prune_inds, inserted_inds in pruned_and_inserted:
# Only prune indices if they're not H&S (inserted)
prune_inds = prune_inds[~np.in1d(prune_inds, inserted_inds)]
for i, ind in enumerate(inserted_inds):
ind -= np.sum(prune_inds < ind)
inserted_inds[i] = ind
return updated_inserted | [
"def",
"_adjust_inserted_indices",
"(",
"inserted_indices_list",
",",
"prune_indices_list",
")",
":",
"# Created a copy, to preserve cached property",
"updated_inserted",
"=",
"[",
"[",
"i",
"for",
"i",
"in",
"dim_inds",
"]",
"for",
"dim_inds",
"in",
"inserted_indices_lis... | Adjust inserted indices, if there are pruned elements. | [
"Adjust",
"inserted",
"indices",
"if",
"there",
"are",
"pruned",
"elements",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L800-L811 | train | 37,178 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._apply_missings | def _apply_missings(self, res, include_missing=False):
"""Return ndarray with missing and insertions as specified.
The return value is the result of the following operations on *res*,
which is a raw cube value array (raw meaning it has shape of original
cube response).
* Remove vectors (rows/cols) for missing elements if *include_missin*
is False.
Note that it does *not* include pruning.
"""
# --element idxs that satisfy `include_missing` arg. Note this
# --includes MR_CAT elements so is essentially all-or-valid-elements
element_idxs = tuple(
(
d.all_elements.element_idxs
if include_missing
else d.valid_elements.element_idxs
)
for d in self._all_dimensions
)
return res[np.ix_(*element_idxs)] if element_idxs else res | python | def _apply_missings(self, res, include_missing=False):
"""Return ndarray with missing and insertions as specified.
The return value is the result of the following operations on *res*,
which is a raw cube value array (raw meaning it has shape of original
cube response).
* Remove vectors (rows/cols) for missing elements if *include_missin*
is False.
Note that it does *not* include pruning.
"""
# --element idxs that satisfy `include_missing` arg. Note this
# --includes MR_CAT elements so is essentially all-or-valid-elements
element_idxs = tuple(
(
d.all_elements.element_idxs
if include_missing
else d.valid_elements.element_idxs
)
for d in self._all_dimensions
)
return res[np.ix_(*element_idxs)] if element_idxs else res | [
"def",
"_apply_missings",
"(",
"self",
",",
"res",
",",
"include_missing",
"=",
"False",
")",
":",
"# --element idxs that satisfy `include_missing` arg. Note this",
"# --includes MR_CAT elements so is essentially all-or-valid-elements",
"element_idxs",
"=",
"tuple",
"(",
"(",
"... | Return ndarray with missing and insertions as specified.
The return value is the result of the following operations on *res*,
which is a raw cube value array (raw meaning it has shape of original
cube response).
* Remove vectors (rows/cols) for missing elements if *include_missin*
is False.
Note that it does *not* include pruning. | [
"Return",
"ndarray",
"with",
"missing",
"and",
"insertions",
"as",
"specified",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L826-L849 | train | 37,179 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._as_array | def _as_array(
self,
include_missing=False,
get_non_selected=False,
weighted=True,
include_transforms_for_dims=False,
):
"""Get crunch cube as ndarray.
Args
include_missing (bool): Include rows/cols for missing values.
get_non_selected (bool): Get non-selected slices for MR vars.
weighted (bool): Take weighted or unweighted counts.
include_transforms_for_dims (list): For which dims to
include headings & subtotals (H&S) transformations.
Returns
res (ndarray): Tabular representation of crunch cube
"""
return self._apply_subtotals(
self._apply_missings(
self._measure(weighted).raw_cube_array, include_missing=include_missing
),
include_transforms_for_dims,
) | python | def _as_array(
self,
include_missing=False,
get_non_selected=False,
weighted=True,
include_transforms_for_dims=False,
):
"""Get crunch cube as ndarray.
Args
include_missing (bool): Include rows/cols for missing values.
get_non_selected (bool): Get non-selected slices for MR vars.
weighted (bool): Take weighted or unweighted counts.
include_transforms_for_dims (list): For which dims to
include headings & subtotals (H&S) transformations.
Returns
res (ndarray): Tabular representation of crunch cube
"""
return self._apply_subtotals(
self._apply_missings(
self._measure(weighted).raw_cube_array, include_missing=include_missing
),
include_transforms_for_dims,
) | [
"def",
"_as_array",
"(",
"self",
",",
"include_missing",
"=",
"False",
",",
"get_non_selected",
"=",
"False",
",",
"weighted",
"=",
"True",
",",
"include_transforms_for_dims",
"=",
"False",
",",
")",
":",
"return",
"self",
".",
"_apply_subtotals",
"(",
"self",... | Get crunch cube as ndarray.
Args
include_missing (bool): Include rows/cols for missing values.
get_non_selected (bool): Get non-selected slices for MR vars.
weighted (bool): Take weighted or unweighted counts.
include_transforms_for_dims (list): For which dims to
include headings & subtotals (H&S) transformations.
Returns
res (ndarray): Tabular representation of crunch cube | [
"Get",
"crunch",
"cube",
"as",
"ndarray",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L878-L901 | train | 37,180 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._cube_dict | def _cube_dict(self):
"""dict containing raw cube response, parsed from JSON payload."""
try:
cube_response = self._cube_response_arg
# ---parse JSON to a dict when constructed with JSON---
cube_dict = (
cube_response
if isinstance(cube_response, dict)
else json.loads(cube_response)
)
# ---cube is 'value' item in a shoji response---
return cube_dict.get("value", cube_dict)
except TypeError:
raise TypeError(
"Unsupported type <%s> provided. Cube response must be JSON "
"(str) or dict." % type(self._cube_response_arg).__name__
) | python | def _cube_dict(self):
"""dict containing raw cube response, parsed from JSON payload."""
try:
cube_response = self._cube_response_arg
# ---parse JSON to a dict when constructed with JSON---
cube_dict = (
cube_response
if isinstance(cube_response, dict)
else json.loads(cube_response)
)
# ---cube is 'value' item in a shoji response---
return cube_dict.get("value", cube_dict)
except TypeError:
raise TypeError(
"Unsupported type <%s> provided. Cube response must be JSON "
"(str) or dict." % type(self._cube_response_arg).__name__
) | [
"def",
"_cube_dict",
"(",
"self",
")",
":",
"try",
":",
"cube_response",
"=",
"self",
".",
"_cube_response_arg",
"# ---parse JSON to a dict when constructed with JSON---",
"cube_dict",
"=",
"(",
"cube_response",
"if",
"isinstance",
"(",
"cube_response",
",",
"dict",
"... | dict containing raw cube response, parsed from JSON payload. | [
"dict",
"containing",
"raw",
"cube",
"response",
"parsed",
"from",
"JSON",
"payload",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L953-L969 | train | 37,181 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._fix_valid_indices | def _fix_valid_indices(cls, valid_indices, insertion_index, dim):
"""Add indices for H&S inserted elements."""
# TODO: make this accept an immutable sequence for valid_indices
# (a tuple) and return an immutable sequence rather than mutating an
# argument.
indices = np.array(sorted(valid_indices[dim]))
slice_index = np.sum(indices <= insertion_index)
indices[slice_index:] += 1
indices = np.insert(indices, slice_index, insertion_index + 1)
valid_indices[dim] = indices.tolist()
return valid_indices | python | def _fix_valid_indices(cls, valid_indices, insertion_index, dim):
"""Add indices for H&S inserted elements."""
# TODO: make this accept an immutable sequence for valid_indices
# (a tuple) and return an immutable sequence rather than mutating an
# argument.
indices = np.array(sorted(valid_indices[dim]))
slice_index = np.sum(indices <= insertion_index)
indices[slice_index:] += 1
indices = np.insert(indices, slice_index, insertion_index + 1)
valid_indices[dim] = indices.tolist()
return valid_indices | [
"def",
"_fix_valid_indices",
"(",
"cls",
",",
"valid_indices",
",",
"insertion_index",
",",
"dim",
")",
":",
"# TODO: make this accept an immutable sequence for valid_indices",
"# (a tuple) and return an immutable sequence rather than mutating an",
"# argument.",
"indices",
"=",
"n... | Add indices for H&S inserted elements. | [
"Add",
"indices",
"for",
"H&S",
"inserted",
"elements",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1029-L1039 | train | 37,182 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._is_axis_allowed | def _is_axis_allowed(self, axis):
"""Check if axis are allowed.
In case the calculation is requested over CA items dimension, it is not
valid. It's valid in all other cases.
"""
if axis is None:
# If table direction was requested, we must ensure that each slice
# doesn't have the CA items dimension (thus the [-2:] part). It's
# OK for the 0th dimension to be items, since no calculation is
# performed over it.
if DT.CA_SUBVAR in self.dim_types[-2:]:
return False
return True
if isinstance(axis, int):
if self.ndim == 1 and axis == 1:
# Special allowed case of a 1D cube, where "row"
# directions is requested.
return True
axis = [axis]
# ---axis is a tuple---
for dim_idx in axis:
if self.dim_types[dim_idx] == DT.CA_SUBVAR:
# If any of the directions explicitly asked for directly
# corresponds to the CA items dimension, the requested
# calculation is not valid.
return False
return True | python | def _is_axis_allowed(self, axis):
"""Check if axis are allowed.
In case the calculation is requested over CA items dimension, it is not
valid. It's valid in all other cases.
"""
if axis is None:
# If table direction was requested, we must ensure that each slice
# doesn't have the CA items dimension (thus the [-2:] part). It's
# OK for the 0th dimension to be items, since no calculation is
# performed over it.
if DT.CA_SUBVAR in self.dim_types[-2:]:
return False
return True
if isinstance(axis, int):
if self.ndim == 1 and axis == 1:
# Special allowed case of a 1D cube, where "row"
# directions is requested.
return True
axis = [axis]
# ---axis is a tuple---
for dim_idx in axis:
if self.dim_types[dim_idx] == DT.CA_SUBVAR:
# If any of the directions explicitly asked for directly
# corresponds to the CA items dimension, the requested
# calculation is not valid.
return False
return True | [
"def",
"_is_axis_allowed",
"(",
"self",
",",
"axis",
")",
":",
"if",
"axis",
"is",
"None",
":",
"# If table direction was requested, we must ensure that each slice",
"# doesn't have the CA items dimension (thus the [-2:] part). It's",
"# OK for the 0th dimension to be items, since no c... | Check if axis are allowed.
In case the calculation is requested over CA items dimension, it is not
valid. It's valid in all other cases. | [
"Check",
"if",
"axis",
"are",
"allowed",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1084-L1114 | train | 37,183 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._measure | def _measure(self, weighted):
"""_BaseMeasure subclass representing primary measure for this cube.
If the cube response includes a means measure, the return value is
means. Otherwise it is counts, with the choice between weighted or
unweighted determined by *weighted*.
Note that weighted counts are provided on an "as-available" basis.
When *weighted* is True and the cube response is not weighted,
unweighted counts are returned.
"""
return (
self._measures.means
if self._measures.means is not None
else self._measures.weighted_counts
if weighted
else self._measures.unweighted_counts
) | python | def _measure(self, weighted):
"""_BaseMeasure subclass representing primary measure for this cube.
If the cube response includes a means measure, the return value is
means. Otherwise it is counts, with the choice between weighted or
unweighted determined by *weighted*.
Note that weighted counts are provided on an "as-available" basis.
When *weighted* is True and the cube response is not weighted,
unweighted counts are returned.
"""
return (
self._measures.means
if self._measures.means is not None
else self._measures.weighted_counts
if weighted
else self._measures.unweighted_counts
) | [
"def",
"_measure",
"(",
"self",
",",
"weighted",
")",
":",
"return",
"(",
"self",
".",
"_measures",
".",
"means",
"if",
"self",
".",
"_measures",
".",
"means",
"is",
"not",
"None",
"else",
"self",
".",
"_measures",
".",
"weighted_counts",
"if",
"weighted... | _BaseMeasure subclass representing primary measure for this cube.
If the cube response includes a means measure, the return value is
means. Otherwise it is counts, with the choice between weighted or
unweighted determined by *weighted*.
Note that weighted counts are provided on an "as-available" basis.
When *weighted* is True and the cube response is not weighted,
unweighted counts are returned. | [
"_BaseMeasure",
"subclass",
"representing",
"primary",
"measure",
"for",
"this",
"cube",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1133-L1150 | train | 37,184 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._prune_3d_body | def _prune_3d_body(self, res, transforms):
"""Return masked array where mask indicates pruned vectors.
*res* is an ndarray (result). *transforms* is a list of ...
"""
mask = np.zeros(res.shape)
mr_dim_idxs = self.mr_dim_ind
for i, prune_inds in enumerate(self.prune_indices(transforms)):
rows_pruned = prune_inds[0]
cols_pruned = prune_inds[1]
rows_pruned = np.repeat(rows_pruned[:, None], len(cols_pruned), axis=1)
cols_pruned = np.repeat(cols_pruned[None, :], len(rows_pruned), axis=0)
slice_mask = np.logical_or(rows_pruned, cols_pruned)
# In case of MRs we need to "inflate" mask
if mr_dim_idxs == (1, 2):
slice_mask = slice_mask[:, np.newaxis, :, np.newaxis]
elif mr_dim_idxs == (0, 1):
slice_mask = slice_mask[np.newaxis, :, np.newaxis, :]
elif mr_dim_idxs == (0, 2):
slice_mask = slice_mask[np.newaxis, :, :, np.newaxis]
elif mr_dim_idxs == 1 and self.ndim == 3:
slice_mask = slice_mask[:, np.newaxis, :]
elif mr_dim_idxs == 2 and self.ndim == 3:
slice_mask = slice_mask[:, :, np.newaxis]
mask[i] = slice_mask
res = np.ma.masked_array(res, mask=mask)
return res | python | def _prune_3d_body(self, res, transforms):
"""Return masked array where mask indicates pruned vectors.
*res* is an ndarray (result). *transforms* is a list of ...
"""
mask = np.zeros(res.shape)
mr_dim_idxs = self.mr_dim_ind
for i, prune_inds in enumerate(self.prune_indices(transforms)):
rows_pruned = prune_inds[0]
cols_pruned = prune_inds[1]
rows_pruned = np.repeat(rows_pruned[:, None], len(cols_pruned), axis=1)
cols_pruned = np.repeat(cols_pruned[None, :], len(rows_pruned), axis=0)
slice_mask = np.logical_or(rows_pruned, cols_pruned)
# In case of MRs we need to "inflate" mask
if mr_dim_idxs == (1, 2):
slice_mask = slice_mask[:, np.newaxis, :, np.newaxis]
elif mr_dim_idxs == (0, 1):
slice_mask = slice_mask[np.newaxis, :, np.newaxis, :]
elif mr_dim_idxs == (0, 2):
slice_mask = slice_mask[np.newaxis, :, :, np.newaxis]
elif mr_dim_idxs == 1 and self.ndim == 3:
slice_mask = slice_mask[:, np.newaxis, :]
elif mr_dim_idxs == 2 and self.ndim == 3:
slice_mask = slice_mask[:, :, np.newaxis]
mask[i] = slice_mask
res = np.ma.masked_array(res, mask=mask)
return res | [
"def",
"_prune_3d_body",
"(",
"self",
",",
"res",
",",
"transforms",
")",
":",
"mask",
"=",
"np",
".",
"zeros",
"(",
"res",
".",
"shape",
")",
"mr_dim_idxs",
"=",
"self",
".",
"mr_dim_ind",
"for",
"i",
",",
"prune_inds",
"in",
"enumerate",
"(",
"self",... | Return masked array where mask indicates pruned vectors.
*res* is an ndarray (result). *transforms* is a list of ... | [
"Return",
"masked",
"array",
"where",
"mask",
"indicates",
"pruned",
"vectors",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1161-L1191 | train | 37,185 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.prune_indices | def prune_indices(self, transforms=None):
"""Return indices of pruned rows and columns as list.
The return value has one of three possible forms:
* a 1-element list of row indices (in case of 1D cube)
* 2-element list of row and col indices (in case of 2D cube)
* n-element list of tuples of 2 elements (if it's 3D cube).
For each case, the 2 elements are the ROW and COL indices of the
elements that need to be pruned. If it's a 3D cube, these indices are
calculated "per slice", that is NOT on the 0th dimension (as the 0th
dimension represents the slices).
"""
if self.ndim >= 3:
# In case of a 3D cube, return list of tuples
# (of row and col pruned indices).
return self._prune_3d_indices(transforms)
def prune_non_3d_indices(transforms):
row_margin = self._pruning_base(
hs_dims=transforms, axis=self.row_direction_axis
)
row_indices = self._margin_pruned_indices(
row_margin, self._inserted_dim_inds(transforms, 0), 0
)
if row_indices.ndim > 1:
# In case of MR, we'd have 2D prune indices
row_indices = row_indices.all(axis=1)
if self.ndim == 1:
return [row_indices]
col_margin = self._pruning_base(
hs_dims=transforms, axis=self._col_direction_axis
)
col_indices = self._margin_pruned_indices(
col_margin, self._inserted_dim_inds(transforms, 1), 1
)
if col_indices.ndim > 1:
# In case of MR, we'd have 2D prune indices
col_indices = col_indices.all(axis=0)
return [row_indices, col_indices]
# In case of 1 or 2 D cubes, return a list of
# row indices (or row and col indices)
return prune_non_3d_indices(transforms) | python | def prune_indices(self, transforms=None):
"""Return indices of pruned rows and columns as list.
The return value has one of three possible forms:
* a 1-element list of row indices (in case of 1D cube)
* 2-element list of row and col indices (in case of 2D cube)
* n-element list of tuples of 2 elements (if it's 3D cube).
For each case, the 2 elements are the ROW and COL indices of the
elements that need to be pruned. If it's a 3D cube, these indices are
calculated "per slice", that is NOT on the 0th dimension (as the 0th
dimension represents the slices).
"""
if self.ndim >= 3:
# In case of a 3D cube, return list of tuples
# (of row and col pruned indices).
return self._prune_3d_indices(transforms)
def prune_non_3d_indices(transforms):
row_margin = self._pruning_base(
hs_dims=transforms, axis=self.row_direction_axis
)
row_indices = self._margin_pruned_indices(
row_margin, self._inserted_dim_inds(transforms, 0), 0
)
if row_indices.ndim > 1:
# In case of MR, we'd have 2D prune indices
row_indices = row_indices.all(axis=1)
if self.ndim == 1:
return [row_indices]
col_margin = self._pruning_base(
hs_dims=transforms, axis=self._col_direction_axis
)
col_indices = self._margin_pruned_indices(
col_margin, self._inserted_dim_inds(transforms, 1), 1
)
if col_indices.ndim > 1:
# In case of MR, we'd have 2D prune indices
col_indices = col_indices.all(axis=0)
return [row_indices, col_indices]
# In case of 1 or 2 D cubes, return a list of
# row indices (or row and col indices)
return prune_non_3d_indices(transforms) | [
"def",
"prune_indices",
"(",
"self",
",",
"transforms",
"=",
"None",
")",
":",
"if",
"self",
".",
"ndim",
">=",
"3",
":",
"# In case of a 3D cube, return list of tuples",
"# (of row and col pruned indices).",
"return",
"self",
".",
"_prune_3d_indices",
"(",
"transform... | Return indices of pruned rows and columns as list.
The return value has one of three possible forms:
* a 1-element list of row indices (in case of 1D cube)
* 2-element list of row and col indices (in case of 2D cube)
* n-element list of tuples of 2 elements (if it's 3D cube).
For each case, the 2 elements are the ROW and COL indices of the
elements that need to be pruned. If it's a 3D cube, these indices are
calculated "per slice", that is NOT on the 0th dimension (as the 0th
dimension represents the slices). | [
"Return",
"indices",
"of",
"pruned",
"rows",
"and",
"columns",
"as",
"list",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1256-L1305 | train | 37,186 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._pruning_base | def _pruning_base(self, axis=None, hs_dims=None):
"""Gets margin if across CAT dimension. Gets counts if across items.
Categorical variables are pruned based on their marginal values. If the
marginal is a 0 or a NaN, the corresponding row/column is pruned. In
case of a subvars (items) dimension, we only prune if all the counts
of the corresponding row/column are zero.
"""
if not self._is_axis_allowed(axis):
# In case we encountered axis that would go across items dimension,
# we need to return at least some result, to prevent explicitly
# checking for this condition, wherever self._margin is used
return self.as_array(weighted=False, include_transforms_for_dims=hs_dims)
# In case of allowed axis, just return the normal API margin. This call
# would throw an exception when directly invoked with bad axis. This is
# intended, because we want to be as explicit as possible. Margins
# across items are not allowed.
return self.margin(
axis=axis, weighted=False, include_transforms_for_dims=hs_dims
) | python | def _pruning_base(self, axis=None, hs_dims=None):
"""Gets margin if across CAT dimension. Gets counts if across items.
Categorical variables are pruned based on their marginal values. If the
marginal is a 0 or a NaN, the corresponding row/column is pruned. In
case of a subvars (items) dimension, we only prune if all the counts
of the corresponding row/column are zero.
"""
if not self._is_axis_allowed(axis):
# In case we encountered axis that would go across items dimension,
# we need to return at least some result, to prevent explicitly
# checking for this condition, wherever self._margin is used
return self.as_array(weighted=False, include_transforms_for_dims=hs_dims)
# In case of allowed axis, just return the normal API margin. This call
# would throw an exception when directly invoked with bad axis. This is
# intended, because we want to be as explicit as possible. Margins
# across items are not allowed.
return self.margin(
axis=axis, weighted=False, include_transforms_for_dims=hs_dims
) | [
"def",
"_pruning_base",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"hs_dims",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_is_axis_allowed",
"(",
"axis",
")",
":",
"# In case we encountered axis that would go across items dimension,",
"# we need to return at le... | Gets margin if across CAT dimension. Gets counts if across items.
Categorical variables are pruned based on their marginal values. If the
marginal is a 0 or a NaN, the corresponding row/column is pruned. In
case of a subvars (items) dimension, we only prune if all the counts
of the corresponding row/column are zero. | [
"Gets",
"margin",
"if",
"across",
"CAT",
"dimension",
".",
"Gets",
"counts",
"if",
"across",
"items",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1322-L1342 | train | 37,187 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._update_result | def _update_result(self, result, insertions, dimension_index):
"""Insert subtotals into resulting ndarray."""
for j, (ind_insertion, value) in enumerate(insertions):
result = np.insert(
result, ind_insertion + j + 1, value, axis=dimension_index
)
return result | python | def _update_result(self, result, insertions, dimension_index):
"""Insert subtotals into resulting ndarray."""
for j, (ind_insertion, value) in enumerate(insertions):
result = np.insert(
result, ind_insertion + j + 1, value, axis=dimension_index
)
return result | [
"def",
"_update_result",
"(",
"self",
",",
"result",
",",
"insertions",
",",
"dimension_index",
")",
":",
"for",
"j",
",",
"(",
"ind_insertion",
",",
"value",
")",
"in",
"enumerate",
"(",
"insertions",
")",
":",
"result",
"=",
"np",
".",
"insert",
"(",
... | Insert subtotals into resulting ndarray. | [
"Insert",
"subtotals",
"into",
"resulting",
"ndarray",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1344-L1350 | train | 37,188 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | _Measures.means | def means(self):
"""_MeanMeasure object providing access to means values.
None when the cube response does not contain a mean measure.
"""
mean_measure_dict = (
self._cube_dict.get("result", {}).get("measures", {}).get("mean")
)
if mean_measure_dict is None:
return None
return _MeanMeasure(self._cube_dict, self._all_dimensions) | python | def means(self):
"""_MeanMeasure object providing access to means values.
None when the cube response does not contain a mean measure.
"""
mean_measure_dict = (
self._cube_dict.get("result", {}).get("measures", {}).get("mean")
)
if mean_measure_dict is None:
return None
return _MeanMeasure(self._cube_dict, self._all_dimensions) | [
"def",
"means",
"(",
"self",
")",
":",
"mean_measure_dict",
"=",
"(",
"self",
".",
"_cube_dict",
".",
"get",
"(",
"\"result\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"measures\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"mean\"",
")",
")",
"if",
... | _MeanMeasure object providing access to means values.
None when the cube response does not contain a mean measure. | [
"_MeanMeasure",
"object",
"providing",
"access",
"to",
"means",
"values",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1381-L1391 | train | 37,189 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | _Measures.missing_count | def missing_count(self):
"""numeric representing count of missing rows in cube response."""
if self.means:
return self.means.missing_count
return self._cube_dict["result"].get("missing", 0) | python | def missing_count(self):
"""numeric representing count of missing rows in cube response."""
if self.means:
return self.means.missing_count
return self._cube_dict["result"].get("missing", 0) | [
"def",
"missing_count",
"(",
"self",
")",
":",
"if",
"self",
".",
"means",
":",
"return",
"self",
".",
"means",
".",
"missing_count",
"return",
"self",
".",
"_cube_dict",
"[",
"\"result\"",
"]",
".",
"get",
"(",
"\"missing\"",
",",
"0",
")"
] | numeric representing count of missing rows in cube response. | [
"numeric",
"representing",
"count",
"of",
"missing",
"rows",
"in",
"cube",
"response",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1394-L1398 | train | 37,190 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | _Measures.weighted_counts | def weighted_counts(self):
"""_WeightedCountMeasure object for this cube.
This object provides access to weighted counts for this cube, if
available. If the cube response is not weighted, the
_UnweightedCountMeasure object for this cube is returned.
"""
if not self.is_weighted:
return self.unweighted_counts
return _WeightedCountMeasure(self._cube_dict, self._all_dimensions) | python | def weighted_counts(self):
"""_WeightedCountMeasure object for this cube.
This object provides access to weighted counts for this cube, if
available. If the cube response is not weighted, the
_UnweightedCountMeasure object for this cube is returned.
"""
if not self.is_weighted:
return self.unweighted_counts
return _WeightedCountMeasure(self._cube_dict, self._all_dimensions) | [
"def",
"weighted_counts",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_weighted",
":",
"return",
"self",
".",
"unweighted_counts",
"return",
"_WeightedCountMeasure",
"(",
"self",
".",
"_cube_dict",
",",
"self",
".",
"_all_dimensions",
")"
] | _WeightedCountMeasure object for this cube.
This object provides access to weighted counts for this cube, if
available. If the cube response is not weighted, the
_UnweightedCountMeasure object for this cube is returned. | [
"_WeightedCountMeasure",
"object",
"for",
"this",
"cube",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1433-L1442 | train | 37,191 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | _Measures.weighted_n | def weighted_n(self):
"""float count of returned rows adjusted for weighting."""
if not self.is_weighted:
return float(self.unweighted_n)
return float(sum(self._cube_dict["result"]["measures"]["count"]["data"])) | python | def weighted_n(self):
"""float count of returned rows adjusted for weighting."""
if not self.is_weighted:
return float(self.unweighted_n)
return float(sum(self._cube_dict["result"]["measures"]["count"]["data"])) | [
"def",
"weighted_n",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_weighted",
":",
"return",
"float",
"(",
"self",
".",
"unweighted_n",
")",
"return",
"float",
"(",
"sum",
"(",
"self",
".",
"_cube_dict",
"[",
"\"result\"",
"]",
"[",
"\"measures\""... | float count of returned rows adjusted for weighting. | [
"float",
"count",
"of",
"returned",
"rows",
"adjusted",
"for",
"weighting",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1445-L1449 | train | 37,192 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | _BaseMeasure.raw_cube_array | def raw_cube_array(self):
"""Return read-only ndarray of measure values from cube-response.
The shape of the ndarray mirrors the shape of the (raw) cube
response. Specifically, it includes values for missing elements, any
MR_CAT dimensions, and any prunable rows and columns.
"""
array = np.array(self._flat_values).reshape(self._all_dimensions.shape)
# ---must be read-only to avoid hard-to-find bugs---
array.flags.writeable = False
return array | python | def raw_cube_array(self):
"""Return read-only ndarray of measure values from cube-response.
The shape of the ndarray mirrors the shape of the (raw) cube
response. Specifically, it includes values for missing elements, any
MR_CAT dimensions, and any prunable rows and columns.
"""
array = np.array(self._flat_values).reshape(self._all_dimensions.shape)
# ---must be read-only to avoid hard-to-find bugs---
array.flags.writeable = False
return array | [
"def",
"raw_cube_array",
"(",
"self",
")",
":",
"array",
"=",
"np",
".",
"array",
"(",
"self",
".",
"_flat_values",
")",
".",
"reshape",
"(",
"self",
".",
"_all_dimensions",
".",
"shape",
")",
"# ---must be read-only to avoid hard-to-find bugs---",
"array",
".",... | Return read-only ndarray of measure values from cube-response.
The shape of the ndarray mirrors the shape of the (raw) cube
response. Specifically, it includes values for missing elements, any
MR_CAT dimensions, and any prunable rows and columns. | [
"Return",
"read",
"-",
"only",
"ndarray",
"of",
"measure",
"values",
"from",
"cube",
"-",
"response",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1460-L1470 | train | 37,193 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | _MeanMeasure._flat_values | def _flat_values(self):
"""Return tuple of mean values as found in cube response.
Mean data may include missing items represented by a dict like
{'?': -1} in the cube response. These are replaced by np.nan in the
returned value.
"""
return tuple(
np.nan if type(x) is dict else x
for x in self._cube_dict["result"]["measures"]["mean"]["data"]
) | python | def _flat_values(self):
"""Return tuple of mean values as found in cube response.
Mean data may include missing items represented by a dict like
{'?': -1} in the cube response. These are replaced by np.nan in the
returned value.
"""
return tuple(
np.nan if type(x) is dict else x
for x in self._cube_dict["result"]["measures"]["mean"]["data"]
) | [
"def",
"_flat_values",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"np",
".",
"nan",
"if",
"type",
"(",
"x",
")",
"is",
"dict",
"else",
"x",
"for",
"x",
"in",
"self",
".",
"_cube_dict",
"[",
"\"result\"",
"]",
"[",
"\"measures\"",
"]",
"[",
"\"m... | Return tuple of mean values as found in cube response.
Mean data may include missing items represented by a dict like
{'?': -1} in the cube response. These are replaced by np.nan in the
returned value. | [
"Return",
"tuple",
"of",
"mean",
"values",
"as",
"found",
"in",
"cube",
"response",
"."
] | a837840755690eb14b2ec8e8d93b4104e01c854f | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1490-L1500 | train | 37,194 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/input_dataframe_generator.py | make_input_dataframe_by_entity | def make_input_dataframe_by_entity(tax_benefit_system, nb_persons, nb_groups):
"""
Generate a dictionnary of dataframes containing nb_persons persons spread in nb_groups groups.
:param TaxBenefitSystem tax_benefit_system: the tax_benefit_system to use
:param int nb_persons: the number of persons in the system
:param int nb_groups: the number of collective entities in the system
:returns: A dictionary whose keys are entities and values the corresponding data frames
Example:
>>> from openfisca_survey_manager.input_dataframe_generator import make_input_dataframe_by_entity
>>> from openfisca_country_template import CountryTaxBenefitSystem
>>> tbs = CountryTaxBenefitSystem()
>>> input_dataframe_by_entity = make_input_dataframe_by_entity(tbs, 400, 100)
>>> sorted(input_dataframe_by_entity['person'].columns.tolist())
['household_id', 'household_legacy_role', 'household_role', 'person_id']
>>> sorted(input_dataframe_by_entity['household'].columns.tolist())
[]
"""
input_dataframe_by_entity = dict()
person_entity = [entity for entity in tax_benefit_system.entities if entity.is_person][0]
person_id = np.arange(nb_persons)
input_dataframe_by_entity = dict()
input_dataframe_by_entity[person_entity.key] = pd.DataFrame({
person_entity.key + '_id': person_id,
})
input_dataframe_by_entity[person_entity.key].set_index('person_id')
#
adults = [0] + sorted(random.sample(range(1, nb_persons), nb_groups - 1))
members_entity_id = np.empty(nb_persons, dtype = int)
# A legacy role is an index that every person within an entity has.
# For instance, the 'first_parent' has legacy role 0, the 'second_parent' 1, the first 'child' 2, the second 3, etc.
members_legacy_role = np.empty(nb_persons, dtype = int)
id_group = -1
for id_person in range(nb_persons):
if id_person in adults:
id_group += 1
legacy_role = 0
else:
legacy_role = 2 if legacy_role == 0 else legacy_role + 1
members_legacy_role[id_person] = legacy_role
members_entity_id[id_person] = id_group
for entity in tax_benefit_system.entities:
if entity.is_person:
continue
key = entity.key
person_dataframe = input_dataframe_by_entity[person_entity.key]
person_dataframe[key + '_id'] = members_entity_id
person_dataframe[key + '_legacy_role'] = members_legacy_role
person_dataframe[key + '_role'] = np.where(
members_legacy_role == 0, entity.flattened_roles[0].key, entity.flattened_roles[-1].key)
input_dataframe_by_entity[key] = pd.DataFrame({
key + '_id': range(nb_groups)
})
input_dataframe_by_entity[key].set_index(key + '_id', inplace = True)
return input_dataframe_by_entity | python | def make_input_dataframe_by_entity(tax_benefit_system, nb_persons, nb_groups):
"""
Generate a dictionnary of dataframes containing nb_persons persons spread in nb_groups groups.
:param TaxBenefitSystem tax_benefit_system: the tax_benefit_system to use
:param int nb_persons: the number of persons in the system
:param int nb_groups: the number of collective entities in the system
:returns: A dictionary whose keys are entities and values the corresponding data frames
Example:
>>> from openfisca_survey_manager.input_dataframe_generator import make_input_dataframe_by_entity
>>> from openfisca_country_template import CountryTaxBenefitSystem
>>> tbs = CountryTaxBenefitSystem()
>>> input_dataframe_by_entity = make_input_dataframe_by_entity(tbs, 400, 100)
>>> sorted(input_dataframe_by_entity['person'].columns.tolist())
['household_id', 'household_legacy_role', 'household_role', 'person_id']
>>> sorted(input_dataframe_by_entity['household'].columns.tolist())
[]
"""
input_dataframe_by_entity = dict()
person_entity = [entity for entity in tax_benefit_system.entities if entity.is_person][0]
person_id = np.arange(nb_persons)
input_dataframe_by_entity = dict()
input_dataframe_by_entity[person_entity.key] = pd.DataFrame({
person_entity.key + '_id': person_id,
})
input_dataframe_by_entity[person_entity.key].set_index('person_id')
#
adults = [0] + sorted(random.sample(range(1, nb_persons), nb_groups - 1))
members_entity_id = np.empty(nb_persons, dtype = int)
# A legacy role is an index that every person within an entity has.
# For instance, the 'first_parent' has legacy role 0, the 'second_parent' 1, the first 'child' 2, the second 3, etc.
members_legacy_role = np.empty(nb_persons, dtype = int)
id_group = -1
for id_person in range(nb_persons):
if id_person in adults:
id_group += 1
legacy_role = 0
else:
legacy_role = 2 if legacy_role == 0 else legacy_role + 1
members_legacy_role[id_person] = legacy_role
members_entity_id[id_person] = id_group
for entity in tax_benefit_system.entities:
if entity.is_person:
continue
key = entity.key
person_dataframe = input_dataframe_by_entity[person_entity.key]
person_dataframe[key + '_id'] = members_entity_id
person_dataframe[key + '_legacy_role'] = members_legacy_role
person_dataframe[key + '_role'] = np.where(
members_legacy_role == 0, entity.flattened_roles[0].key, entity.flattened_roles[-1].key)
input_dataframe_by_entity[key] = pd.DataFrame({
key + '_id': range(nb_groups)
})
input_dataframe_by_entity[key].set_index(key + '_id', inplace = True)
return input_dataframe_by_entity | [
"def",
"make_input_dataframe_by_entity",
"(",
"tax_benefit_system",
",",
"nb_persons",
",",
"nb_groups",
")",
":",
"input_dataframe_by_entity",
"=",
"dict",
"(",
")",
"person_entity",
"=",
"[",
"entity",
"for",
"entity",
"in",
"tax_benefit_system",
".",
"entities",
... | Generate a dictionnary of dataframes containing nb_persons persons spread in nb_groups groups.
:param TaxBenefitSystem tax_benefit_system: the tax_benefit_system to use
:param int nb_persons: the number of persons in the system
:param int nb_groups: the number of collective entities in the system
:returns: A dictionary whose keys are entities and values the corresponding data frames
Example:
>>> from openfisca_survey_manager.input_dataframe_generator import make_input_dataframe_by_entity
>>> from openfisca_country_template import CountryTaxBenefitSystem
>>> tbs = CountryTaxBenefitSystem()
>>> input_dataframe_by_entity = make_input_dataframe_by_entity(tbs, 400, 100)
>>> sorted(input_dataframe_by_entity['person'].columns.tolist())
['household_id', 'household_legacy_role', 'household_role', 'person_id']
>>> sorted(input_dataframe_by_entity['household'].columns.tolist())
[] | [
"Generate",
"a",
"dictionnary",
"of",
"dataframes",
"containing",
"nb_persons",
"persons",
"spread",
"in",
"nb_groups",
"groups",
"."
] | bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358 | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/input_dataframe_generator.py#L25-L84 | train | 37,195 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/surveys.py | Survey.insert_table | def insert_table(self, label = None, name = None, **kwargs):
"""
Insert a table in the Survey object
"""
data_frame = kwargs.pop('data_frame', None)
if data_frame is None:
data_frame = kwargs.pop('dataframe', None)
to_hdf_kwargs = kwargs.pop('to_hdf_kwargs', dict())
if data_frame is not None:
assert isinstance(data_frame, pandas.DataFrame)
if data_frame is not None:
if label is None:
label = name
table = Table(label = label, name = name, survey = self)
assert table.survey.hdf5_file_path is not None
log.debug("Saving table {} in {}".format(name, table.survey.hdf5_file_path))
table.save_data_frame(data_frame, **to_hdf_kwargs)
if name not in self.tables:
self.tables[name] = dict()
for key, val in kwargs.items():
self.tables[name][key] = val | python | def insert_table(self, label = None, name = None, **kwargs):
"""
Insert a table in the Survey object
"""
data_frame = kwargs.pop('data_frame', None)
if data_frame is None:
data_frame = kwargs.pop('dataframe', None)
to_hdf_kwargs = kwargs.pop('to_hdf_kwargs', dict())
if data_frame is not None:
assert isinstance(data_frame, pandas.DataFrame)
if data_frame is not None:
if label is None:
label = name
table = Table(label = label, name = name, survey = self)
assert table.survey.hdf5_file_path is not None
log.debug("Saving table {} in {}".format(name, table.survey.hdf5_file_path))
table.save_data_frame(data_frame, **to_hdf_kwargs)
if name not in self.tables:
self.tables[name] = dict()
for key, val in kwargs.items():
self.tables[name][key] = val | [
"def",
"insert_table",
"(",
"self",
",",
"label",
"=",
"None",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"data_frame",
"=",
"kwargs",
".",
"pop",
"(",
"'data_frame'",
",",
"None",
")",
"if",
"data_frame",
"is",
"None",
":",
"data_f... | Insert a table in the Survey object | [
"Insert",
"a",
"table",
"in",
"the",
"Survey",
"object"
] | bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358 | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/surveys.py#L248-L272 | train | 37,196 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/variables.py | quantile | def quantile(q, variable, weight_variable = None, filter_variable = None):
"""
Return quantile of a variable with weight provided by a specific wieght variable potentially filtered
"""
def formula(entity, period):
value = entity(variable, period)
if weight_variable is not None:
weight = entity(weight_variable, period)
weight = entity.filled_array(1)
if filter_variable is not None:
filter_value = entity(filter_variable, period)
weight = filter_value * weight
labels = arange(1, q + 1)
quantile, _ = weightedcalcs_quantiles(
value,
labels,
weight,
return_quantiles = True,
)
if filter_variable is not None:
quantile = where(weight > 0, quantile, -1)
return quantile
return formula | python | def quantile(q, variable, weight_variable = None, filter_variable = None):
"""
Return quantile of a variable with weight provided by a specific wieght variable potentially filtered
"""
def formula(entity, period):
value = entity(variable, period)
if weight_variable is not None:
weight = entity(weight_variable, period)
weight = entity.filled_array(1)
if filter_variable is not None:
filter_value = entity(filter_variable, period)
weight = filter_value * weight
labels = arange(1, q + 1)
quantile, _ = weightedcalcs_quantiles(
value,
labels,
weight,
return_quantiles = True,
)
if filter_variable is not None:
quantile = where(weight > 0, quantile, -1)
return quantile
return formula | [
"def",
"quantile",
"(",
"q",
",",
"variable",
",",
"weight_variable",
"=",
"None",
",",
"filter_variable",
"=",
"None",
")",
":",
"def",
"formula",
"(",
"entity",
",",
"period",
")",
":",
"value",
"=",
"entity",
"(",
"variable",
",",
"period",
")",
"if... | Return quantile of a variable with weight provided by a specific wieght variable potentially filtered | [
"Return",
"quantile",
"of",
"a",
"variable",
"with",
"weight",
"provided",
"by",
"a",
"specific",
"wieght",
"variable",
"potentially",
"filtered"
] | bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358 | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/variables.py#L12-L36 | train | 37,197 |
mgaitan/waliki | docs/conf.py | _get_version | def _get_version():
"""Get the version from package itself."""
with open("../waliki/__init__.py") as fh:
for line in fh:
if line.startswith("__version__ = "):
return line.split("=")[-1].strip().strip("'").strip('"') | python | def _get_version():
"""Get the version from package itself."""
with open("../waliki/__init__.py") as fh:
for line in fh:
if line.startswith("__version__ = "):
return line.split("=")[-1].strip().strip("'").strip('"') | [
"def",
"_get_version",
"(",
")",
":",
"with",
"open",
"(",
"\"../waliki/__init__.py\"",
")",
"as",
"fh",
":",
"for",
"line",
"in",
"fh",
":",
"if",
"line",
".",
"startswith",
"(",
"\"__version__ = \"",
")",
":",
"return",
"line",
".",
"split",
"(",
"\"=\... | Get the version from package itself. | [
"Get",
"the",
"version",
"from",
"package",
"itself",
"."
] | 5baaf6f043275920a1174ff233726f7ff4bfb5cf | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/docs/conf.py#L27-L32 | train | 37,198 |
mgaitan/waliki | waliki/management/commands/moin_migration_cleanup.py | clean_meta | def clean_meta(rst_content):
"""remove moinmoin metada from the top of the file"""
rst = rst_content.split('\n')
for i, line in enumerate(rst):
if line.startswith('#'):
continue
break
return '\n'.join(rst[i:]) | python | def clean_meta(rst_content):
"""remove moinmoin metada from the top of the file"""
rst = rst_content.split('\n')
for i, line in enumerate(rst):
if line.startswith('#'):
continue
break
return '\n'.join(rst[i:]) | [
"def",
"clean_meta",
"(",
"rst_content",
")",
":",
"rst",
"=",
"rst_content",
".",
"split",
"(",
"'\\n'",
")",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"rst",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'#'",
")",
":",
"continue",
"break... | remove moinmoin metada from the top of the file | [
"remove",
"moinmoin",
"metada",
"from",
"the",
"top",
"of",
"the",
"file"
] | 5baaf6f043275920a1174ff233726f7ff4bfb5cf | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/management/commands/moin_migration_cleanup.py#L21-L29 | train | 37,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.