sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
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=(...
Perform the insertions of place-holding rows and cols for insertions.
entailment
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_...
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
entailment
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 N...
Compute and return the variable values for period and baseline or reform tax_benefit_system
entailment
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...
Filter the input data frame from variables that won't be used or are set to be computed
entailment
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. ...
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.
entailment
def init_entity(self, entity = None, input_data_frame = None, period = None, simulation = None): """ Initialize the simulation period with current input_data_frame """ assert entity is not None assert input_data_frame is not None assert period is not None assert s...
Initialize the simulation period with current input_data_frame
entailment
def init_simulation_with_data_frame(self, input_data_frame = None, period = None, simulation = None, entity = None): """ Initialize the simulation period with current input_data_frame for an entity if specified """ assert input_data_frame is not None assert period is not None ...
Initialize the simulation period with current input_data_frame for an entity if specified
entailment
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 s...
Neutralizing input variables not in input dataframe and keep some crucial variables
entailment
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 i...
Set the tax and benefit system and eventually the baseline tax and benefit system
entailment
def summarize_variable(self, variable = None, use_baseline = False, weighted = False, force_compute = False): """ Prints a summary of a variable including its memory usage. :param string variable: the variable being summarized :param bool use_baseline: the tax-benefit-system...
Prints a summary of a variable including its memory usage. :param string variable: the variable being summarized :param bool use_baseline: the tax-benefit-system considered :param bool weighted: whether the produced statistics should be weigthted or not :param bool force...
entailment
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....
Identify and set the good ids for the different entities
entailment
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.ta...
Identify and set the good roles for the different entities
entailment
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.us...
Identify and set the good input variables for the different entities
entailment
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)
tuple of dimension objects in this collection. This composed tuple is the source for the dimension objects in this collection.
entailment
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 )
Generate Dimension object for each dimension dict.
entailment
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 )
Sequence of _RawDimension objects wrapping each dimension dict.
entailment
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() ...
Return member of DIMENSION_TYPE appropriate to dimension_dict.
entailment
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. """ ...
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.
entailment
def _next_raw_dimension(self): """_RawDimension for next *dimension_dict* in sequence or None for last. Returns None if this dimension is the last in sequence for this cube. """ dimension_dicts = self._dimension_dicts this_idx = dimension_dicts.index(self._dimension_dict) ...
_RawDimension for next *dimension_dict* in sequence or None for last. Returns None if this dimension is the last in sequence for this cube.
entailment
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'). ...
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').
entailment
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...
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 (h...
entailment
def hs_indices(self): """tuple of (anchor_idx, addend_idxs) pair for each subtotal. Example:: ( (2, (0, 1, 2)), (3, (3,)), ('bottom', (4, 5)) ) Note that the `anchor_idx` item in the first position of each pair ca...
tuple of (anchor_idx, addend_idxs) pair for each subtotal. Example:: ( (2, (0, 1, 2)), (3, (3,)), ('bottom', (4, 5)) ) Note that the `anchor_idx` item in the first position of each pair can be 'top' or 'bottom' as well as...
entailment
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--- ...
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.
entailment
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}
True if adding counts across this dimension axis is meaningful.
entailment
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...
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).
entailment
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...
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 or...
entailment
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 {}, t...
_Subtotals sequence object for this dimension. The subtotals sequence provides access to any subtotal insertions defined on this dimension.
entailment
def _element_makings(self): """(ElementCls, element_dicts) pair for this dimension's elements. All the elements of a given dimension are the same type. This method determines the type (class) and source dicts for the elements of this dimension and provides them for the element factory. ...
(ElementCls, element_dicts) pair for this dimension's elements. All the elements of a given dimension are the same type. This method determines the type (class) and source dicts for the elements of this dimension and provides them for the element factory.
entailment
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) )
Composed tuple storing actual sequence of element objects.
entailment
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
Numeric value assigned to element by user, np.nan if absent.
entailment
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_...
str display-name for this element, '' when absent from cube response. This property handles numeric, datetime and text variables, but also subvar dimensions
entailment
def iter_for_anchor(self, anchor): """Generate each subtotal having matching *anchor*.""" return (subtotal for subtotal in self._subtotals if subtotal.anchor == anchor)
Generate each subtotal having matching *anchor*.
entailment
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-subt...
Generate each insertion dict that represents a valid subtotal.
entailment
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() )
Composed tuple storing actual sequence of _Subtotal objects.
entailment
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 default...
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 r...
entailment
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)....
int or str representing index of anchor element in dimension. When the anchor is an operation, like 'top' or 'bottom'
entailment
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", []) ...
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.
entailment
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( ...
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.
entailment
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) ...
Browse subdirectories to extract stata and sas files
entailment
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 ...
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. ...
entailment
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
Return numberic count of rows considered for cube response.
entailment
def get_slices(self, ca_as_0th=False): """Return list of :class:`.CubeSlice` objects. The number of slice objects in the returned list depends on the dimensionality of this cube. A 1D or 2D cube will return a list containing one slice object. A 3D cube will return a list of slices ...
Return list of :class:`.CubeSlice` objects. The number of slice objects in the returned list depends on the dimensionality of this cube. A 1D or 2D cube will return a list containing one slice object. A 3D cube will return a list of slices the same length as the first dimension.
entailment
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 cube index measurement. This function is deprecated. Use index_table from CubeSlice.
entailment
def inserted_hs_indices(self, prune=False): """Get indices of the inserted H&S (for formatting purposes).""" if self.ndim == 2 and prune: # If pruning is applied, we need to subtract from the H&S indes # the number of pruned rows (cols) that come before that index. pr...
Get indices of the inserted H&S (for formatting purposes).
entailment
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}
True if cube only contains a CA dimension-pair, in either order.
entailment
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 [ ...
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
entailment
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 selecte...
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. ...
entailment
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 ...
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 ...
entailment
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...
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 a...
entailment
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 ...
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 selecte...
entailment
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 in...
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.
entailment
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...
Get cube means.
entailment
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 ...
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. :para...
entailment
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 perf...
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 implemen...
entailment
def _adjust_axis(self, axis): """Return raw axis/axes corresponding to apparent axis/axes. This method adjusts user provided 'axis' parameter, for some of the cube operations, mainly 'margin'. The user never sees the MR selections dimension, and treats all MRs as single dimensions. Thus...
Return raw axis/axes corresponding to apparent axis/axes. This method adjusts user provided 'axis' parameter, for some of the cube operations, mainly 'margin'. The user never sees the MR selections dimension, and treats all MRs as single dimensions. Thus we need to adjust the values of ...
entailment
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(p...
Adjust inserted indices, if there are pruned elements.
entailment
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...
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* ...
entailment
def _apply_subtotals(self, res, include_transforms_for_dims): """* Insert subtotals (and perhaps other insertions later) for dimensions having their apparent dimension-idx in *include_transforms_for_dims*. """ if not include_transforms_for_dims: return res ...
* Insert subtotals (and perhaps other insertions later) for dimensions having their apparent dimension-idx in *include_transforms_for_dims*.
entailment
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...
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...
entailment
def _calculate_constraints_sum(cls, prop_table, prop_margin, axis): """Calculate sum of constraints (part of the standard error equation). This method calculates the sum of the cell proportions multiplied by row (or column) marginal proportions (margins divide by the total count). It do...
Calculate sum of constraints (part of the standard error equation). This method calculates the sum of the cell proportions multiplied by row (or column) marginal proportions (margins divide by the total count). It does this by utilizing the matrix multiplication, which directly translat...
entailment
def _counts(self, weighted): """Return _BaseMeasure subclass for *weighted* counts. The return value is a _WeightedCountMeasure object if *weighted* is True and the cube response is weighted. Otherwise it is an _UnweightedCountMeasure object. Any means measure that may be present ...
Return _BaseMeasure subclass for *weighted* counts. The return value is a _WeightedCountMeasure object if *weighted* is True and the cube response is weighted. Otherwise it is an _UnweightedCountMeasure object. Any means measure that may be present is not considered. Contrast with `._me...
entailment
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...
dict containing raw cube response, parsed from JSON payload.
entailment
def _drop_mr_cat_dims(self, array, fix_valids=False): """Return ndarray reflecting *array* with MR_CAT dims dropped. If any (except 1st) dimension has a single element, it is flattened in the resulting array (which is more convenient for the users of the CrunchCube). If the ori...
Return ndarray reflecting *array* with MR_CAT dims dropped. If any (except 1st) dimension has a single element, it is flattened in the resulting array (which is more convenient for the users of the CrunchCube). If the original shape of the cube is needed (e.g. to calculate the ...
entailment
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(sort...
Add indices for H&S inserted elements.
entailment
def _insertions(self, result, dimension, dimension_index): """Return list of (idx, sum) pairs representing subtotals. *idx* is the int offset at which to insert the ndarray subtotal in *sum*. """ def iter_insertions(): for anchor_idx, addend_idxs in dimension.hs_ind...
Return list of (idx, sum) pairs representing subtotals. *idx* is the int offset at which to insert the ndarray subtotal in *sum*.
entailment
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 ...
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.
entailment
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 tha...
_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-...
entailment
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_indi...
Return masked array where mask indicates pruned vectors. *res* is an ndarray (result). *transforms* is a list of ...
entailment
def _prune_body(self, res, transforms=None): """Return a masked version of *res* where pruned rows/cols are masked. Return value is an `np.ma.MaskedArray` object. Pruning is the removal of rows or columns whose corresponding marginal elements are either 0 or not defined (np.nan). ...
Return a masked version of *res* where pruned rows/cols are masked. Return value is an `np.ma.MaskedArray` object. Pruning is the removal of rows or columns whose corresponding marginal elements are either 0 or not defined (np.nan).
entailment
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...
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). ...
entailment
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) d...
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 corr...
entailment
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 re...
Insert subtotals into resulting ndarray.
entailment
def is_weighted(self): """True if weights have been applied to the measure(s) for this cube. Unweighted counts are available for all cubes. Weighting applies to any other measures provided by the cube. """ cube_dict = self._cube_dict if cube_dict.get("query", {}).get("we...
True if weights have been applied to the measure(s) for this cube. Unweighted counts are available for all cubes. Weighting applies to any other measures provided by the cube.
entailment
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: ...
_MeanMeasure object providing access to means values. None when the cube response does not contain a mean measure.
entailment
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)
numeric representing count of missing rows in cube response.
entailment
def population_fraction(self): """The filtered/unfiltered ratio for cube response. This value is required for properly calculating population on a cube where a filter has been applied. Returns 1.0 for an unfiltered cube. Returns `np.nan` if the unfiltered count is zero, which would ...
The filtered/unfiltered ratio for cube response. This value is required for properly calculating population on a cube where a filter has been applied. Returns 1.0 for an unfiltered cube. Returns `np.nan` if the unfiltered count is zero, which would otherwise result in a divide-by-zero e...
entailment
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_we...
_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.
entailment
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"]))
float count of returned rows adjusted for weighting.
entailment
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. """...
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.
entailment
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 ty...
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.
entailment
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 pe...
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 syst...
entailment
def randomly_init_variable(tax_benefit_system, input_dataframe_by_entity, variable_name, max_value, condition = None, seed = None): """ Initialise a variable with random values (from 0 to max_value). If a condition vector is provided, only set the value of persons or groups for which condition is Tr...
Initialise a variable with random values (from 0 to max_value). If a condition vector is provided, only set the value of persons or groups for which condition is True. Exemple: >>> from openfisca_survey_manager.input_dataframe_generator import make_input_dataframe_by_entity >>> from op...
entailment
def get_value(self, variable = None, table = None): """ Get value Parameters ---------- variable : string name of the variable table : string, default None name of the table hosting the variable Returns ------- df...
Get value Parameters ---------- variable : string name of the variable table : string, default None name of the table hosting the variable Returns ------- df : DataFrame, default None A DataFrame containing the varia...
entailment
def get_values(self, variables = None, table = None, lowercase = False, rename_ident = True): """ Get values Parameters ---------- variables : list of strings, default None list of variables names, if None return the whole table table : string, defaul...
Get values Parameters ---------- variables : list of strings, default None list of variables names, if None return the whole table table : string, default None name of the table hosting the variables lowercase : boolean, deflault True ...
entailment
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',...
Insert a table in the Survey object
entailment
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: ...
Return quantile of a variable with weight provided by a specific wieght variable potentially filtered
entailment
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('"')
Get the version from package itself.
entailment
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:])
remove moinmoin metada from the top of the file
entailment
def entry_point(context, block_name): """include an snippet at the bottom of a block, if it exists For example, if the plugin with slug 'attachments' is registered waliki/attachments_edit_content.html will be included with {% entry_point 'edit_content' %} which is declared at the bottom ...
include an snippet at the bottom of a block, if it exists For example, if the plugin with slug 'attachments' is registered waliki/attachments_edit_content.html will be included with {% entry_point 'edit_content' %} which is declared at the bottom of the block 'content' in edit.html
entailment
def check_perms(parser, token): """ Returns a list of permissions (as ``codename`` strings) for a given ``user``/``group`` and ``obj`` (Model instance). Parses ``check_perms`` tag which should be in format:: {% check_perms "perm1[, perm2, ...]" for user in slug as "context_var" %} or ...
Returns a list of permissions (as ``codename`` strings) for a given ``user``/``group`` and ``obj`` (Model instance). Parses ``check_perms`` tag which should be in format:: {% check_perms "perm1[, perm2, ...]" for user in slug as "context_var" %} or {% check_perms "perm1[, perm2, ...]" fo...
entailment
def waliki_box(context, slug, show_edit=True, *args, **kwargs): """ A templatetag to render a wiki page content as a box in any webpage, and allow rapid edition if you have permission. It's inspired in `django-boxes`_ .. _django-boxes: https://github.com/eldarion/django-boxes """ request ...
A templatetag to render a wiki page content as a box in any webpage, and allow rapid edition if you have permission. It's inspired in `django-boxes`_ .. _django-boxes: https://github.com/eldarion/django-boxes
entailment
def check_perms(perms, user, slug, raise_exception=False): """a helper user to check if a user has the permissions for a given slug""" if isinstance(perms, string_types): perms = {perms} else: perms = set(perms) allowed_users = ACLRule.get_users_for(perms, slug) if allowed_user...
a helper user to check if a user has the permissions for a given slug
entailment
def permission_required(perms, login_url=None, raise_exception=False, redirect_field_name=REDIRECT_FIELD_NAME): """ this is analog to django's builtin ``permission_required`` decorator, but improved to check per slug ACLRules and default permissions for anonymous and logged in users if there is a r...
this is analog to django's builtin ``permission_required`` decorator, but improved to check per slug ACLRules and default permissions for anonymous and logged in users if there is a rule affecting a slug, the user needs to be part of the rule's allowed users. If there isn't a matching rule, defaults pe...
entailment
def get_module(app, modname, verbose=False, failfast=False): """ Internal function to load a module from a single app. taken from https://github.com/ojii/django-load. """ module_name = '%s.%s' % (app, modname) try: module = import_module(module_name) except ImportError as e: ...
Internal function to load a module from a single app. taken from https://github.com/ojii/django-load.
entailment
def load(modname, verbose=False, failfast=False): """ Loads all modules with name 'modname' from all installed apps. If verbose is True, debug information will be printed to stdout. If failfast is True, import errors will not be surpressed. """ for app in settings.INSTALLED_APPS: get_mod...
Loads all modules with name 'modname' from all installed apps. If verbose is True, debug information will be printed to stdout. If failfast is True, import errors will not be surpressed.
entailment
def register(PluginClass): """ Register a plugin class. This function will call back your plugin's constructor. """ if PluginClass in _cache.keys(): raise Exception("Plugin class already registered") plugin = PluginClass() _cache[PluginClass] = plugin if getattr(PluginClass, 'ex...
Register a plugin class. This function will call back your plugin's constructor.
entailment
def render_form(form): """same than {{ form|crispy }} if crispy_forms is installed. render using a bootstrap3 templating otherwise""" if 'crispy_forms' in settings.INSTALLED_APPS: from crispy_forms.templatetags.crispy_forms_filters import as_crispy_form return as_crispy_form(form) tem...
same than {{ form|crispy }} if crispy_forms is installed. render using a bootstrap3 templating otherwise
entailment
def settings(request): """inject few waliki's settings to the context to be used in templates""" from waliki.settings import WALIKI_USE_MATHJAX # NOQA return {k: v for (k, v) in locals().items() if k.startswith('WALIKI')}
inject few waliki's settings to the context to be used in templates
entailment
def smart_encode_str(s): """Create a UTF-16 encoded PDF string literal for `s`.""" try: utf16 = s.encode('utf_16_be') except AttributeError: # ints and floats utf16 = str(s).encode('utf_16_be') safe = utf16.replace(b'\x00)', b'\x00\\)').replace(b'\x00(', b'\x00\\(') return b''.join(...
Create a UTF-16 encoded PDF string literal for `s`.
entailment
def forge_fdf(pdf_form_url=None, fdf_data_strings=[], fdf_data_names=[], fields_hidden=[], fields_readonly=[], checkbox_checked_name=b"Yes"): """Generates fdf string from fields specified * pdf_form_url (default: None): just the url for the form. * fdf_data_strings (default: [])...
Generates fdf string from fields specified * pdf_form_url (default: None): just the url for the form. * fdf_data_strings (default: []): array of (string, value) tuples for the form fields (or dicts). Value is passed as a UTF-16 encoded string, unless True/False, in which case it is assumed to be a ...
entailment