text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_child_of(self, chunk): """ Link one YAML chunk to another. Used when inserting a chunk of YAML into another chunk. """
if self.is_mapping(): for key, value in self.contents.items(): self.key(key, key).pointer.make_child_of(chunk.pointer) self.val(key).make_child_of(chunk) elif self.is_sequence(): for index, item in enumerate(self.contents): self.index(index).make_child_of(chunk) else: self.pointer.make_child_of(chunk.pointer)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _select(self, pointer): """ Get a YAMLChunk referenced by a pointer. """
return YAMLChunk( self._ruamelparsed, pointer=pointer, label=self._label, strictparsed=self._strictparsed, key_association=copy(self._key_association), )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def index(self, strictindex): """ Return a chunk in a sequence referenced by index. """
return self._select(self._pointer.index(self.ruamelindex(strictindex)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ruamelindex(self, strictindex): """ Get the ruamel equivalent of a strict parsed index. E.g. 0 -> 0, 1 -> 2, parsed-via-slugify -> Parsed via slugify """
return ( self.key_association.get(strictindex, strictindex) if self.is_mapping() else strictindex )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def val(self, strictkey): """ Return a chunk referencing a value in a mapping with the key 'key'. """
ruamelkey = self.ruamelindex(strictkey) return self._select(self._pointer.val(ruamelkey, strictkey))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def key(self, key, strictkey=None): """ Return a chunk referencing a key in a mapping with the name 'key'. """
return self._select(self._pointer.key(key, strictkey))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def textslice(self, start, end): """ Return a chunk referencing a slice of a scalar text value. """
return self._select(self._pointer.textslice(start, end))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flatten(items): """ Yield items from any nested iterable. [1, 2, 3, 4, 5, 6, 7] """
for x in items: if isinstance(x, Iterable) and not isinstance(x, (str, bytes)): for sub_x in flatten(x): yield sub_x else: yield x
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def comma_separated_positions(text): """ Start and end positions of comma separated text items. Commas and trailing spaces should not be included. [(0, 3), (5, 6), (7, 8)] """
chunks = [] start = 0 end = 0 for item in text.split(","): space_increment = 1 if item[0] == " " else 0 start += space_increment # Is there a space after the comma to ignore? ", " end += len(item.lstrip()) + space_increment chunks.append((start, end)) start += len(item.lstrip()) + 1 # Plus comma end = start return chunks
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ruamel_structure(data, validator=None): """ Take dicts and lists and return a ruamel.yaml style structure of CommentedMaps, CommentedSeqs and data. If a validator is presented and the type is unknown, it is checked against the validator to see if it will turn it back in to YAML. """
if isinstance(data, dict): if len(data) == 0: raise exceptions.CannotBuildDocumentsFromEmptyDictOrList( "Document must be built with non-empty dicts and lists" ) return CommentedMap( [ (ruamel_structure(key), ruamel_structure(value)) for key, value in data.items() ] ) elif isinstance(data, list): if len(data) == 0: raise exceptions.CannotBuildDocumentsFromEmptyDictOrList( "Document must be built with non-empty dicts and lists" ) return CommentedSeq([ruamel_structure(item) for item in data]) elif isinstance(data, bool): return u"yes" if data else u"no" elif isinstance(data, (int, float)): return str(data) else: if not is_string(data): raise exceptions.CannotBuildDocumentFromInvalidData( ( "Document must be built from a combination of:\n" "string, int, float, bool or nonempty list/dict\n\n" "Instead, found variable with type '{}': '{}'" ).format(type(data).__name__, data) ) return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rbdd(*keywords): """ Run story matching keywords and rewrite story if code changed. """
settings = _personal_settings().data settings["engine"]["rewrite"] = True _storybook(settings["engine"]).with_params( **{"python version": settings["params"]["python version"]} ).only_uninherited().shortcut(*keywords).play()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rerun(version="3.7.0"): """ Rerun last example code block with specified version of python. """
from commandlib import Command Command(DIR.gen.joinpath("py{0}".format(version), "bin", "python"))( DIR.gen.joinpath("state", "examplepythoncode.py") ).in_dir(DIR.gen.joinpath("state")).run()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data(self): """ Returns raw data representation of the document or document segment. Mappings are rendered as ordered dicts, sequences as lists and scalar values as whatever the validator returns (int, string, etc.). If no validators are used, scalar values are always returned as strings. """
if isinstance(self._value, CommentedMap): mapping = OrderedDict() for key, value in self._value.items(): mapping[key.data] = value.data return mapping elif isinstance(self._value, CommentedSeq): return [item.data for item in self._value] else: return self._value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_yaml(self): """ Render the YAML node and subnodes as string. """
dumped = dump(self.as_marked_up(), Dumper=StrictYAMLDumper, allow_unicode=True) return dumped if sys.version_info[0] == 3 else dumped.decode("utf8")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text(self): """ Return string value of scalar, whatever value it was parsed as. """
if isinstance(self._value, CommentedMap): raise TypeError("{0} is a mapping, has no text value.".format(repr(self))) if isinstance(self._value, CommentedSeq): raise TypeError("{0} is a sequence, has no text value.".format(repr(self))) return self._text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def partition_source(src): """Partitions source into a list of `CodePartition`s for import refactoring. """
# In python2, ast.parse(text_string_with_encoding_pragma) raises # SyntaxError: encoding declaration in Unicode string ast_obj = ast.parse(src.encode('UTF-8')) visitor = TopLevelImportVisitor() visitor.visit(ast_obj) line_offsets = get_line_offsets_by_line_no(src) chunks = [] startpos = 0 pending_chunk_type = None possible_ending_tokens = None seen_import = False for ( token_type, token_text, (srow, scol), (erow, ecol), _, ) in tokenize.generate_tokens(io.StringIO(src).readline): # Searching for a start of a chunk if pending_chunk_type is None: if not seen_import and token_type == tokenize.COMMENT: if 'noreorder' in token_text: chunks.append(CodePartition(CodeType.CODE, src[startpos:])) break else: pending_chunk_type = CodeType.PRE_IMPORT_CODE possible_ending_tokens = TERMINATES_COMMENT elif not seen_import and token_type == tokenize.STRING: pending_chunk_type = CodeType.PRE_IMPORT_CODE possible_ending_tokens = TERMINATES_DOCSTRING elif scol == 0 and srow in visitor.top_level_import_line_numbers: seen_import = True pending_chunk_type = CodeType.IMPORT possible_ending_tokens = TERMINATES_IMPORT elif token_type == tokenize.NL: # A NL token is a non-important newline, we'll immediately # append a NON_CODE partition endpos = line_offsets[erow] + ecol srctext = src[startpos:endpos] startpos = endpos chunks.append(CodePartition(CodeType.NON_CODE, srctext)) elif token_type == tokenize.COMMENT: if 'noreorder' in token_text: chunks.append(CodePartition(CodeType.CODE, src[startpos:])) break else: pending_chunk_type = CodeType.CODE possible_ending_tokens = TERMINATES_COMMENT elif token_type == tokenize.ENDMARKER: # Token ended right before end of file or file was empty pass else: # We've reached a `CODE` block, which spans the rest of the # file (intentionally timid). Let's append that block and be # done chunks.append(CodePartition(CodeType.CODE, src[startpos:])) break # Attempt to find ending of token elif token_type in possible_ending_tokens: endpos = line_offsets[erow] + ecol srctext = src[startpos:endpos] startpos = endpos chunks.append(CodePartition(pending_chunk_type, srctext)) pending_chunk_type = None possible_ending_tokens = None elif token_type == tokenize.COMMENT and 'noreorder' in token_text: chunks.append(CodePartition(CodeType.CODE, src[startpos:])) break chunks = [chunk for chunk in chunks if chunk.src] # Make sure we're not removing any code assert _partitions_to_src(chunks) == src return chunks
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def separate_comma_imports(partitions): """Turns `import a, b` into `import a` and `import b`"""
def _inner(): for partition in partitions: if partition.code_type is CodeType.IMPORT: import_obj = import_obj_from_str(partition.src) if import_obj.has_multiple_imports: for new_import_obj in import_obj.split_imports(): yield CodePartition( CodeType.IMPORT, new_import_obj.to_text(), ) else: yield partition else: yield partition return list(_inner())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _module_to_base_modules(s): """return all module names that would be imported due to this import-import """
parts = s.split('.') for i in range(1, len(parts)): yield '.'.join(parts[:i])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_thresholds(input, thresholds, choices): """ Return one of the choices depending on the input position compared to thresholds, for each input. array([10]) array([10]) array([15]) array([20]) array([0]) """
condlist = [input <= threshold for threshold in thresholds] if len(condlist) == len(choices) - 1: # If a choice is provided for input > highest threshold, last condition must be true to return it. condlist += [True] assert len(condlist) == len(choices), \ "apply_thresholds must be called with the same number of thresholds than choices, or one more choice" return np.select(condlist, choices)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, period = None, start = None, stop = None, value = None): """Change the value for a given period. :param period: Period where the value is modified. If set, `start` and `stop` should be `None`. :param start: Start of the period. Instance of `openfisca_core.periods.Instant`. If set, `period` should be `None`. :param stop: Stop of the period. Instance of `openfisca_core.periods.Instant`. If set, `period` should be `None`. :param value: New value. If `None`, the parameter is removed from the legislation parameters for the given period. """
if period is not None: if start is not None or stop is not None: raise TypeError("Wrong input for 'update' method: use either 'update(period, value = value)' or 'update(start = start, stop = stop, value = value)'. You cannot both use 'period' and 'start' or 'stop'.") if isinstance(period, str): period = periods.period(period) start = period.start stop = period.stop if start is None: raise ValueError("You must provide either a start or a period") start_str = str(start) stop_str = str(stop.offset(1, 'day')) if stop else None old_values = self.values_list new_values = [] n = len(old_values) i = 0 # Future intervals : not affected if stop_str: while (i < n) and (old_values[i].instant_str >= stop_str): new_values.append(old_values[i]) i += 1 # Right-overlapped interval if stop_str: if new_values and (stop_str == new_values[-1].instant_str): pass # such interval is empty else: if i < n: overlapped_value = old_values[i].value value_name = _compose_name(self.name, item_name = stop_str) new_interval = ParameterAtInstant(value_name, stop_str, data = {'value': overlapped_value}) new_values.append(new_interval) else: value_name = _compose_name(self.name, item_name = stop_str) new_interval = ParameterAtInstant(value_name, stop_str, data = {'value': None}) new_values.append(new_interval) # Insert new interval value_name = _compose_name(self.name, item_name = start_str) new_interval = ParameterAtInstant(value_name, start_str, data = {'value': value}) new_values.append(new_interval) # Remove covered intervals while (i < n) and (old_values[i].instant_str >= start_str): i += 1 # Past intervals : not affected while i < n: new_values.append(old_values[i]) i += 1 self.values_list = new_values
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge(self, other): """ Merges another ParameterNode into the current node. In case of child name conflict, the other node child will replace the current node child. """
for child_name, child in other.children.items(): self.add_child(child_name, child)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_child(self, name, child): """ Add a new child to the node. :param name: Name of the child that must be used to access that child. Should not contain anything that could interfere with the operator `.` (dot). :param child: The new child, an instance of :any:`Scale` or :any:`Parameter` or :any:`ParameterNode`. """
if name in self.children: raise ValueError("{} has already a child named {}".format(self.name, name)) if not (isinstance(child, ParameterNode) or isinstance(child, Parameter) or isinstance(child, Scale)): raise TypeError("child must be of type ParameterNode, Parameter, or Scale. Instead got {}".format(type(child))) self.children[name] = child setattr(self, name, child)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace_variable(self, variable): """ Replaces an existing OpenFisca variable in the tax and benefit system by a new one. The new variable must have the same name than the replaced one. If no variable with the given name exists in the tax and benefit system, no error will be raised and the new variable will be simply added. :param Variable variable: New variable to add. Must be a subclass of Variable. """
name = variable.__name__ if self.variables.get(name) is not None: del self.variables[name] self.load_variable(variable, update = False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_variables_from_file(self, file_path): """ Adds all OpenFisca variables contained in a given file to the tax and benefit system. """
try: file_name = path.splitext(path.basename(file_path))[0] # As Python remembers loaded modules by name, in order to prevent collisions, we need to make sure that: # - Files with the same name, but located in different directories, have a different module names. Hence the file path hash in the module name. # - The same file, loaded by different tax and benefit systems, has distinct module names. Hence the `id(self)` in the module name. module_name = '{}_{}_{}'.format(id(self), hash(path.abspath(file_path)), file_name) module_directory = path.dirname(file_path) try: module = load_module(module_name, *find_module(file_name, [module_directory])) except NameError as e: logging.error(str(e) + ": if this code used to work, this error might be due to a major change in OpenFisca-Core. Checkout the changelog to learn more: <https://github.com/openfisca/openfisca-core/blob/master/CHANGELOG.md>") raise potential_variables = [getattr(module, item) for item in dir(module) if not item.startswith('__')] for pot_variable in potential_variables: # We only want to get the module classes defined in this module (not imported) if isclass(pot_variable) and issubclass(pot_variable, Variable) and pot_variable.__module__ == module_name: self.add_variable(pot_variable) except Exception: log.error('Unable to load OpenFisca variables from file "{}"'.format(file_path)) raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_variables_from_directory(self, directory): """ Recursively explores a directory, and adds all OpenFisca variables found there to the tax and benefit system. """
py_files = glob.glob(path.join(directory, "*.py")) for py_file in py_files: self.add_variables_from_file(py_file) subdirectories = glob.glob(path.join(directory, "*/")) for subdirectory in subdirectories: self.add_variables_from_directory(subdirectory)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_extension(self, extension): """ Loads an extension to the tax and benefit system. :param string extension: The extension to load. Can be an absolute path pointing to an extension directory, or the name of an OpenFisca extension installed as a pip package. """
# Load extension from installed pip package try: package = importlib.import_module(extension) extension_directory = package.__path__[0] except ImportError: message = linesep.join([traceback.format_exc(), 'Error loading extension: `{}` is neither a directory, nor a package.'.format(extension), 'Are you sure it is installed in your environment? If so, look at the stack trace above to determine the origin of this error.', 'See more at <https://github.com/openfisca/openfisca-extension-template#installing>.']) raise ValueError(message) self.add_variables_from_directory(extension_directory) param_dir = path.join(extension_directory, 'parameters') if path.isdir(param_dir): extension_parameters = ParameterNode(directory_path = param_dir) self.parameters.merge(extension_parameters)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_reform(self, reform_path): """ Generates a new tax and benefit system applying a reform to the tax and benefit system. The current tax and benefit system is **not** mutated. :param string reform_path: The reform to apply. Must respect the format *installed_package.sub_module.reform* :returns: A reformed tax and benefit system. Example: """
from openfisca_core.reforms import Reform try: reform_package, reform_name = reform_path.rsplit('.', 1) except ValueError: raise ValueError('`{}` does not seem to be a path pointing to a reform. A path looks like `some_country_package.reforms.some_reform.`'.format(reform_path)) try: reform_module = importlib.import_module(reform_package) except ImportError: message = linesep.join([traceback.format_exc(), 'Could not import `{}`.'.format(reform_package), 'Are you sure of this reform module name? If so, look at the stack trace above to determine the origin of this error.']) raise ValueError(message) reform = getattr(reform_module, reform_name, None) if reform is None: raise ValueError('{} has no attribute {}'.format(reform_package, reform_name)) if not issubclass(reform, Reform): raise ValueError('`{}` does not seem to be a valid Openfisca reform.'.format(reform_path)) return reform(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_variable(self, variable_name, check_existence = False): """ Get a variable from the tax and benefit system. :param variable_name: Name of the requested variable. :param check_existence: If True, raise an error if the requested variable does not exist. """
variables = self.variables found = variables.get(variable_name) if not found and check_existence: raise VariableNotFound(variable_name, self) return found
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def neutralize_variable(self, variable_name): """ Neutralizes an OpenFisca variable existing in the tax and benefit system. A neutralized variable always returns its default value when computed. Trying to set inputs for a neutralized variable has no effect except raising a warning. """
self.variables[variable_name] = get_neutralized_variable(self.get_variable(variable_name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_parameters(self, path_to_yaml_dir): """ Loads the legislation parameter for a directory containing YAML parameters files. :param path_to_yaml_dir: Absolute path towards the YAML parameter directory. Example: """
parameters = ParameterNode('', directory_path = path_to_yaml_dir) if self.preprocess_parameters is not None: parameters = self.preprocess_parameters(parameters) self.parameters = parameters
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_parameters_at_instant(self, instant): """ Get the parameters of the legislation at a given instant :param instant: string of the format 'YYYY-MM-DD' or `openfisca_core.periods.Instant` instance. :returns: The parameters of the legislation at a given instant. :rtype: :any:`ParameterNodeAtInstant` """
if isinstance(instant, periods.Period): instant = instant.start elif isinstance(instant, (str, int)): instant = periods.instant(instant) else: assert isinstance(instant, periods.Instant), "Expected an Instant (e.g. Instant((2017, 1, 1)) ). Got: {}.".format(instant) parameters_at_instant = self._parameters_at_instant_cache.get(instant) if parameters_at_instant is None and self.parameters is not None: parameters_at_instant = self.parameters.get_at_instant(str(instant)) self._parameters_at_instant_cache[instant] = parameters_at_instant return parameters_at_instant
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_package_metadata(self): """ Gets metatada relative to the country package the tax and benefit system is built from. :returns: Country package metadata :rtype: dict Example: """
# Handle reforms if self.baseline: return self.baseline.get_package_metadata() fallback_metadata = { 'name': self.__class__.__name__, 'version': '', 'repository_url': '', 'location': '', } module = inspect.getmodule(self) if not module.__package__: return fallback_metadata package_name = module.__package__.split('.')[0] try: distribution = pkg_resources.get_distribution(package_name) except pkg_resources.DistributionNotFound: return fallback_metadata location = inspect.getsourcefile(module).split(package_name)[0].rstrip('/') home_page_metadatas = [ metadata.split(':', 1)[1].strip(' ') for metadata in distribution._get_metadata(distribution.PKG_INFO) if 'Home-page' in metadata ] repository_url = home_page_metadatas[0] if home_page_metadatas else '' return { 'name': distribution.key, 'version': distribution.version, 'repository_url': repository_url, 'location': location, }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_variables(self, entity = None): """ Gets all variables contained in a tax and benefit system. :param <Entity subclass> entity: If set, returns only the variable defined for the given entity. :returns: A dictionnary, indexed by variable names. :rtype: dict """
if not entity: return self.variables else: return { variable_name: variable for variable_name, variable in self.variables.items() # TODO - because entities are copied (see constructor) they can't be compared if variable.entity.key == entity.key }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_from_dict(self, tax_benefit_system, input_dict): """ Build a simulation from ``input_dict`` This method uses :any:`build_from_entities` if entities are fully specified, or :any:`build_from_variables` if not. :param dict input_dict: A dict represeting the input of the simulation :return: A :any:`Simulation` """
input_dict = self.explicit_singular_entities(tax_benefit_system, input_dict) if any(key in tax_benefit_system.entities_plural() for key in input_dict.keys()): return self.build_from_entities(tax_benefit_system, input_dict) else: return self.build_from_variables(tax_benefit_system, input_dict)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_from_entities(self, tax_benefit_system, input_dict): """ Build a simulation from a Python dict ``input_dict`` fully specifying entities. Examples: 'persons': {'Javier': { 'salary': {'2018-11': 2000}}}, 'households': {'household': {'parents': ['Javier']}} }) """
input_dict = deepcopy(input_dict) simulation = Simulation(tax_benefit_system, tax_benefit_system.instantiate_entities()) # Register variables so get_variable_entity can find them for (variable_name, _variable) in tax_benefit_system.variables.items(): self.register_variable(variable_name, simulation.get_variable_population(variable_name).entity) check_type(input_dict, dict, ['error']) axes = input_dict.pop('axes', None) unexpected_entities = [entity for entity in input_dict if entity not in tax_benefit_system.entities_plural()] if unexpected_entities: unexpected_entity = unexpected_entities[0] raise SituationParsingError([unexpected_entity], ''.join([ "Some entities in the situation are not defined in the loaded tax and benefit system.", "These entities are not found: {0}.", "The defined entities are: {1}."] ) .format( ', '.join(unexpected_entities), ', '.join(tax_benefit_system.entities_plural()) ) ) persons_json = input_dict.get(tax_benefit_system.person_entity.plural, None) if not persons_json: raise SituationParsingError([tax_benefit_system.person_entity.plural], 'No {0} found. At least one {0} must be defined to run a simulation.'.format(tax_benefit_system.person_entity.key)) persons_ids = self.add_person_entity(simulation.persons.entity, persons_json) for entity_class in tax_benefit_system.group_entities: instances_json = input_dict.get(entity_class.plural) if instances_json is not None: self.add_group_entity(self.persons_plural, persons_ids, entity_class, instances_json) else: self.add_default_group_entity(persons_ids, entity_class) if axes: self.axes = axes self.expand_axes() try: self.finalize_variables_init(simulation.persons) except PeriodMismatchError as e: self.raise_period_mismatch(simulation.persons.entity, persons_json, e) for entity_class in tax_benefit_system.group_entities: try: population = simulation.populations[entity_class.key] self.finalize_variables_init(population) except PeriodMismatchError as e: self.raise_period_mismatch(population.entity, instances_json, e) return simulation
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_from_variables(self, tax_benefit_system, input_dict): """ Build a simulation from a Python dict ``input_dict`` describing variables values without expliciting entities. This method uses :any:`build_default_simulation` to infer an entity structure Example: {'salary': {'2016-10': 12000}} ) """
count = _get_person_count(input_dict) simulation = self.build_default_simulation(tax_benefit_system, count) for variable, value in input_dict.items(): if not isinstance(value, dict): if self.default_period is None: raise SituationParsingError([variable], "Can't deal with type: expected object. Input variables should be set for specific periods. For instance: {'salary': {'2017-01': 2000, '2017-02': 2500}}, or {'birth_date': {'ETERNITY': '1980-01-01'}}.") simulation.set_input(variable, self.default_period, value) else: for period_str, dated_value in value.items(): simulation.set_input(variable, period_str, dated_value) return simulation
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def explicit_singular_entities(self, tax_benefit_system, input_dict): """ Preprocess ``input_dict`` to explicit entities defined using the single-entity shortcut Example: {'persons': {'Javier': {}, }, 'household': {'parents': ['Javier']}} ) """
singular_keys = set(input_dict).intersection(tax_benefit_system.entities_by_singular()) if not singular_keys: return input_dict result = { entity_id: entity_description for (entity_id, entity_description) in input_dict.items() if entity_id in tax_benefit_system.entities_plural() } # filter out the singular entities for singular in singular_keys: plural = tax_benefit_system.entities_by_singular()[singular].plural result[plural] = {singular: input_dict[singular]} return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_person_entity(self, entity, instances_json): """ Add the simulation's instances of the persons entity as described in ``instances_json``. """
check_type(instances_json, dict, [entity.plural]) entity_ids = list(map(str, instances_json.keys())) self.persons_plural = entity.plural self.entity_ids[self.persons_plural] = entity_ids self.entity_counts[self.persons_plural] = len(entity_ids) for instance_id, instance_object in instances_json.items(): check_type(instance_object, dict, [entity.plural, instance_id]) self.init_variable_values(entity, instance_object, str(instance_id)) return self.get_ids(entity.plural)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combine_tax_scales(node): """ Combine all the MarginalRateTaxScales in the node into a single MarginalRateTaxScale. """
combined_tax_scales = None for child_name in node: child = node[child_name] if not isinstance(child, AbstractTaxScale): log.info('Skipping {} with value {} because it is not a tax scale'.format(child_name, child)) continue if combined_tax_scales is None: combined_tax_scales = MarginalRateTaxScale(name = child_name) combined_tax_scales.add_bracket(0, 0) combined_tax_scales.add_tax_scale(child) return combined_tax_scales
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inverse(self): """Returns a new instance of MarginalRateTaxScale Invert a taxscale: Assume tax_scale composed of bracket which thresholds are expressed in term of brut revenue. The inverse is another MarginalTaxSclae which thresholds are expressed in terms of net revenue. If net = revbrut - tax_scale.calc(revbrut) then brut = tax_scale.inverse().calc(net) """
# threshold : threshold of brut revenue # net_threshold: threshold of net revenue # theta : ordonnée à l'origine des segments des différents seuils dans une # représentation du revenu imposable comme fonction linéaire par # morceaux du revenu brut # Actually 1 / (1- global_rate) inverse = self.__class__(name = self.name + "'", option = self.option, unit = self.unit) net_threshold = 0 for threshold, rate in zip(self.thresholds, self.rates): if threshold == 0: previous_rate = 0 theta = 0 # On calcule le seuil de revenu imposable de la tranche considérée. net_threshold = (1 - previous_rate) * threshold + theta inverse.add_bracket(net_threshold, 1 / (1 - rate)) theta = (rate - previous_rate) * threshold + theta previous_rate = rate return inverse
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scale_tax_scales(self, factor): """Scale all the MarginalRateTaxScales in the node."""
assert isinstance(factor, (float, int)) scaled_tax_scale = self.copy() return scaled_tax_scale.multiply_thresholds(factor)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode(self): """ Return the array of enum items corresponding to self """
return np.select([self == item.index for item in self.possible_values], [item for item in self.possible_values])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode_to_str(self): """ Return the array of string identifiers corresponding to self """
return np.select([self == item.index for item in self.possible_values], [item.name for item in self.possible_values])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def record_calculation_start(self, variable_name, period, **parameters): """ Record that OpenFisca started computing a variable. :param str variable_name: Name of the variable starting to be computed :param Period period: Period for which the variable is being computed :param list parameters: Parameter with which the variable is being computed """
key = self._get_key(variable_name, period, **parameters) if self.stack: # The variable is a dependency of another variable parent = self.stack[-1] self.trace[parent]['dependencies'].append(key) else: # The variable has been requested by the client self.requested_calculations.add(key) if not self.trace.get(key): self.trace[key] = {'dependencies': [], 'parameters': {}} self.stack.append(key) self._computation_log.append((key, len(self.stack))) self.usage_stats[variable_name]['nb_requests'] += 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def record_calculation_end(self, variable_name, period, result, **parameters): """ Record that OpenFisca finished computing a variable. :param str variable_name: Name of the variable starting to be computed :param Period period: Period for which the variable is being computed :param numpy.ndarray result: Result of the computation :param list parameters: Parameter with which the variable is being computed """
key = self._get_key(variable_name, period, **parameters) expected_key = self.stack.pop() if not key == expected_key: raise ValueError( "Something went wrong with the simulation tracer: result of '{0}' was expected, got results for '{1}' instead. This does not make sense as the last variable we started computing was '{0}'." .format(expected_key, key) ) self.trace[key]['value'] = result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_computation_log(self, aggregate = False): """ Print the computation log of a simulation. If ``aggregate`` is ``False`` (default), print the value of each computed vector. If ``aggregate`` is ``True``, only print the minimum, maximum, and average value of each computed vector. This mode is more suited for simulations on a large population. """
for line in self.computation_log(aggregate): print(line)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_simulation(tax_benefit_system, nb_persons, nb_groups, **kwargs): """ Generate a simulation containing nb_persons persons spread in nb_groups groups. Example: """
simulation = Simulation(tax_benefit_system = tax_benefit_system, **kwargs) simulation.persons.ids = np.arange(nb_persons) simulation.persons.count = nb_persons 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 'demandeur' has legacy role 0, the 'conjoint' 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 simulation.populations.values(): if not entity.is_person: entity.members_entity_id = members_entity_id entity.count = nb_groups entity.members_role = np.where(members_legacy_role == 0, entity.flattened_roles[0], entity.flattened_roles[-1]) return simulation
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modify_parameters(self, modifier_function): """ Make modifications on the parameters of the legislation Call this function in `apply()` if the reform asks for legislation parameter modifications. :param modifier_function: A function that takes an object of type :any:`ParameterNode` and should return an object of the same type. """
baseline_parameters = self.baseline.parameters baseline_parameters_copy = copy.deepcopy(baseline_parameters) reform_parameters = modifier_function(baseline_parameters_copy) if not isinstance(reform_parameters, ParameterNode): return ValueError( 'modifier_function {} in module {} must return a ParameterNode' .format(modifier_function.__name__, modifier_function.__module__,) ) self.parameters = reform_parameters self._parameters_at_instant_cache = {}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def date(self): """Convert instant to a date. datetime.date(2014, 1, 1) datetime.date(2014, 2, 1) datetime.date(2014, 2, 3) """
instant_date = date_by_instant_cache.get(self) if instant_date is None: date_by_instant_cache[self] = instant_date = datetime.date(*self) return instant_date
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def period(self, unit, size = 1): """Create a new period starting at instant. Period(('month', Instant((2014, 1, 1)), 1)) Period(('year', Instant((2014, 2, 1)), 2)) Period(('day', Instant((2014, 2, 3)), 2)) """
assert unit in (DAY, MONTH, YEAR), 'Invalid unit: {} of type {}'.format(unit, type(unit)) assert isinstance(size, int) and size >= 1, 'Invalid size: {} of type {}'.format(size, type(size)) return Period((unit, self, size))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_subperiods(self, unit): """ Return the list of all the periods of unit ``unit`` contained in self. Examples: """
if unit_weight(self.unit) < unit_weight(unit): raise ValueError('Cannot subdivide {0} into {1}'.format(self.unit, unit)) if unit == YEAR: return [self.this_year.offset(i, YEAR) for i in range(self.size)] if unit == MONTH: return [self.first_month.offset(i, MONTH) for i in range(self.size_in_months)] if unit == DAY: return [self.first_day.offset(i, DAY) for i in range(self.size_in_days)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def size_in_months(self): """Return the size of the period in months. 4 12 """
if (self[0] == MONTH): return self[2] if(self[0] == YEAR): return self[2] * 12 raise ValueError("Cannot calculate number of months in {0}".format(self[0]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def size_in_days(self): """Return the size of the period in days. 28 366 """
unit, instant, length = self if unit == DAY: return length if unit in [MONTH, YEAR]: last_day = self.start.offset(length, unit).offset(-1, DAY) return (last_day.date - self.start.date).days + 1 raise ValueError("Cannot calculate number of days in {0}".format(unit))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self): """Return the last day of the period as an Instant instance. Instant((2014, 12, 31)) Instant((2014, 12, 31)) Instant((2014, 12, 31)) Instant((2013, 2, 28)) Instant((2012, 3, 28)) Instant((2012, 2, 29)) Instant((2014, 2, 28)) Instant((2012, 4, 28)) Instant((2012, 3, 1)) """
unit, start_instant, size = self year, month, day = start_instant if unit == ETERNITY: return Instant((float("inf"), float("inf"), float("inf"))) if unit == 'day': if size > 1: day += size - 1 month_last_day = calendar.monthrange(year, month)[1] while day > month_last_day: month += 1 if month == 13: year += 1 month = 1 day -= month_last_day month_last_day = calendar.monthrange(year, month)[1] else: if unit == 'month': month += size while month > 12: year += 1 month -= 12 else: assert unit == 'year', 'Invalid unit: {} of type {}'.format(unit, type(unit)) year += size day -= 1 if day < 1: month -= 1 if month == 0: year -= 1 month = 12 day += calendar.monthrange(year, month)[1] else: month_last_day = calendar.monthrange(year, month)[1] if day > month_last_day: month += 1 if month == 13: year += 1 month = 1 day -= month_last_day return Instant((year, month, day))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_formula_name(self, attribute_name): """ Returns the starting date of a formula based on its name. Valid dated name formats are : 'formula', 'formula_YYYY', 'formula_YYYY_MM' and 'formula_YYYY_MM_DD' where YYYY, MM and DD are a year, month and day. By convention, the starting date of: - `formula` is `0001-01-01` (minimal date in Python) - `formula_YYYY` is `YYYY-01-01` - `formula_YYYY_MM` is `YYYY-MM-01` """
def raise_error(): raise ValueError( 'Unrecognized formula name in variable "{}". Expecting "formula_YYYY" or "formula_YYYY_MM" or "formula_YYYY_MM_DD where YYYY, MM and DD are year, month and day. Found: "{}".' .format(self.name, attribute_name)) if attribute_name == FORMULA_NAME_PREFIX: return date.min FORMULA_REGEX = r'formula_(\d{4})(?:_(\d{2}))?(?:_(\d{2}))?$' # YYYY or YYYY_MM or YYYY_MM_DD match = re.match(FORMULA_REGEX, attribute_name) if not match: raise_error() date_str = '-'.join([match.group(1), match.group(2) or '01', match.group(3) or '01']) try: return datetime.datetime.strptime(date_str, '%Y-%m-%d').date() except ValueError: # formula_2005_99_99 for instance raise_error()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_introspection_data(cls, tax_benefit_system): """ Get instrospection data about the code of the variable. :returns: (comments, source file path, source code, start line number) :rtype: tuple """
comments = inspect.getcomments(cls) # Handle dynamically generated variable classes or Jupyter Notebooks, which have no source. try: absolute_file_path = inspect.getsourcefile(cls) except TypeError: source_file_path = None else: source_file_path = absolute_file_path.replace(tax_benefit_system.get_package_metadata()['location'], '') try: source_lines, start_line_number = inspect.getsourcelines(cls) source_code = textwrap.dedent(''.join(source_lines)) except (IOError, TypeError): source_code, start_line_number = None, None return comments, source_file_path, source_code, start_line_number
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_formula(self, period = None): """ Returns the formula used to compute the variable at the given period. If no period is given and the variable has several formula, return the oldest formula. :returns: Formula used to compute the variable :rtype: function """
if not self.formulas: return None if period is None: return self.formulas.peekitem(index = 0)[1] # peekitem gets the 1st key-value tuple (the oldest start_date and formula). Return the formula. if isinstance(period, periods.Period): instant = period.start else: try: instant = periods.period(period).start except ValueError: instant = periods.instant(period) if self.end and instant.date > self.end: return None instant = str(instant) for start_date in reversed(self.formulas): if start_date <= instant: return self.formulas[start_date] return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_rank(self, entity, criteria, condition = True): """ Get the rank of a person within an entity according to a criteria. The person with rank 0 has the minimum value of criteria. If condition is specified, then the persons who don't respect it are not taken into account and their rank is -1. Example: """
# If entity is for instance 'person.household', we get the reference entity 'household' behind the projector entity = entity if not isinstance(entity, Projector) else entity.reference_entity positions = entity.members_position biggest_entity_size = np.max(positions) + 1 filtered_criteria = np.where(condition, criteria, np.inf) ids = entity.members_entity_id # Matrix: the value in line i and column j is the value of criteria for the jth person of the ith entity matrix = np.asarray([ entity.value_nth_person(k, filtered_criteria, default = np.inf) for k in range(biggest_entity_size) ]).transpose() # We double-argsort all lines of the matrix. # Double-argsorting gets the rank of each value once sorted # For instance, if x = [3,1,6,4,0], y = np.argsort(x) is [4, 1, 0, 3, 2] (because the value with index 4 is the smallest one, the value with index 1 the second smallest, etc.) and z = np.argsort(y) is [2, 1, 4, 3, 0], the rank of each value. sorted_matrix = np.argsort(np.argsort(matrix)) # Build the result vector by taking for each person the value in the right line (corresponding to its household id) and the right column (corresponding to its position) result = sorted_matrix[ids, positions] # Return -1 for the persons who don't respect the condition return np.where(condition, result, -1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ordered_members_map(self): """ Mask to group the persons by entity This function only caches the map value, to see what the map is used for, see value_nth_person method. """
if self._ordered_members_map is None: return np.argsort(self.members_entity_id) return self._ordered_members_map
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sum(self, array, role = None): """ Return the sum of ``array`` for the members of the entity. ``array`` must have the dimension of the number of persons in the simulation If ``role`` is provided, only the entity member with the given role are taken into account. Example: """
self.entity.check_role_validity(role) self.members.check_array_compatible_with_entity(array) if role is not None: role_filter = self.members.has_role(role) return np.bincount( self.members_entity_id[role_filter], weights = array[role_filter], minlength = self.count) else: return np.bincount(self.members_entity_id, weights = array)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def any(self, array, role = None): """ Return ``True`` if ``array`` is ``True`` for any members of the entity. ``array`` must have the dimension of the number of persons in the simulation If ``role`` is provided, only the entity member with the given role are taken into account. Example: """
sum_in_entity = self.sum(array, role = role) return (sum_in_entity > 0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def all(self, array, role = None): """ Return ``True`` if ``array`` is ``True`` for all members of the entity. ``array`` must have the dimension of the number of persons in the simulation If ``role`` is provided, only the entity member with the given role are taken into account. Example: """
return self.reduce(array, reducer = np.logical_and, neutral_element = True, role = role)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max(self, array, role = None): """ Return the maximum value of ``array`` for the entity members. ``array`` must have the dimension of the number of persons in the simulation If ``role`` is provided, only the entity member with the given role are taken into account. Example: """
return self.reduce(array, reducer = np.maximum, neutral_element = - np.infty, role = role)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def min(self, array, role = None): """ Return the minimum value of ``array`` for the entity members. ``array`` must have the dimension of the number of persons in the simulation If ``role`` is provided, only the entity member with the given role are taken into account. Example: """
return self.reduce(array, reducer = np.minimum, neutral_element = np.infty, role = role)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nb_persons(self, role = None): """ Returns the number of persons contained in the entity. If ``role`` is provided, only the entity member with the given role are taken into account. """
if role: if role.subroles: role_condition = np.logical_or.reduce([self.members_role == subrole for subrole in role.subroles]) else: role_condition = self.members_role == role return self.sum(role_condition) else: return np.bincount(self.members_entity_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def value_from_person(self, array, role, default = 0): """ Get the value of ``array`` for the person with the unique role ``role``. ``array`` must have the dimension of the number of persons in the simulation If such a person does not exist, return ``default`` instead The result is a vector which dimension is the number of entities """
self.entity.check_role_validity(role) if role.max != 1: raise Exception( 'You can only use value_from_person with a role that is unique in {}. Role {} is not unique.' .format(self.key, role.key) ) self.members.check_array_compatible_with_entity(array) members_map = self.ordered_members_map result = self.filled_array(default, dtype = array.dtype) if isinstance(array, EnumArray): result = EnumArray(result, array.possible_values) role_filter = self.members.has_role(role) entity_filter = self.any(role_filter) result[entity_filter] = array[members_map][role_filter[members_map]] return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def value_nth_person(self, n, array, default = 0): """ Get the value of array for the person whose position in the entity is n. Note that this position is arbitrary, and that members are not sorted. If the nth person does not exist, return ``default`` instead. The result is a vector which dimension is the number of entities. """
self.members.check_array_compatible_with_entity(array) positions = self.members_position nb_persons_per_entity = self.nb_persons() members_map = self.ordered_members_map result = self.filled_array(default, dtype = array.dtype) # For households that have at least n persons, set the result as the value of criteria for the person for which the position is n. # The map is needed b/c the order of the nth persons of each household in the persons vector is not necessarily the same than the household order. result[nb_persons_per_entity > n] = array[members_map][positions[members_map] == n] return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data_storage_dir(self): """ Temporary folder used to store intermediate calculation data in case the memory is saturated """
if self._data_storage_dir is None: self._data_storage_dir = tempfile.mkdtemp(prefix = "openfisca_") log.warn(( "Intermediate results will be stored on disk in {} in case of memory overflow. " "You should remove this directory once you're done with your simulation." ).format(self._data_storage_dir)) return self._data_storage_dir
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate(self, variable_name, period, **parameters): """ Calculate the variable ``variable_name`` for the period ``period``, using the variable formula if it exists. :returns: A numpy array containing the result of the calculation """
population = self.get_variable_population(variable_name) holder = population.get_holder(variable_name) variable = self.tax_benefit_system.get_variable(variable_name, check_existence = True) if period is not None and not isinstance(period, periods.Period): period = periods.period(period) if self.trace: self.tracer.record_calculation_start(variable.name, period, **parameters) self._check_period_consistency(period, variable) # First look for a value already cached cached_array = holder.get_array(period) if cached_array is not None: if self.trace: self.tracer.record_calculation_end(variable.name, period, cached_array, **parameters) return cached_array array = None # First, try to run a formula try: self._check_for_cycle(variable, period) array = self._run_formula(variable, population, period) # If no result, use the default value and cache it if array is None: array = holder.default_array() array = self._cast_formula_result(array, variable) holder.put_in_cache(array, period) except SpiralError: array = holder.default_array() finally: if self.trace: self.tracer.record_calculation_end(variable.name, period, array, **parameters) self._clean_cycle_detection_data(variable.name) self.purge_cache_of_invalid_values() return array
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_output(self, variable_name, period): """ Calculate the value of a variable using the ``calculate_output`` attribute of the variable. """
variable = self.tax_benefit_system.get_variable(variable_name, check_existence = True) if variable.calculate_output is None: return self.calculate(variable_name, period) return variable.calculate_output(self, variable_name, period)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_formula(self, variable, population, period): """ Find the ``variable`` formula for the given ``period`` if it exists, and apply it to ``population``. """
formula = variable.get_formula(period) if formula is None: return None if self.trace: parameters_at = self.trace_parameters_at_instant else: parameters_at = self.tax_benefit_system.get_parameters_at_instant if formula.__code__.co_argcount == 2: array = formula(population, period) else: array = formula(population, period, parameters_at) self._check_formula_result(array, variable, population, period) return array
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_period_consistency(self, period, variable): """ Check that a period matches the variable definition_period """
if variable.definition_period == periods.ETERNITY: return # For variables which values are constant in time, all periods are accepted if variable.definition_period == periods.MONTH and period.unit != periods.MONTH: raise ValueError("Unable to compute variable '{0}' for period {1}: '{0}' must be computed for a whole month. You can use the ADD option to sum '{0}' over the requested period, or change the requested period to 'period.first_month'.".format( variable.name, period )) if variable.definition_period == periods.YEAR and period.unit != periods.YEAR: raise ValueError("Unable to compute variable '{0}' for period {1}: '{0}' must be computed for a whole year. You can use the DIVIDE option to get an estimate of {0} by dividing the yearly value by 12, or change the requested period to 'period.this_year'.".format( variable.name, period )) if period.size != 1: raise ValueError("Unable to compute variable '{0}' for period {1}: '{0}' must be computed for a whole {2}. You can use the ADD option to sum '{0}' over the requested period.".format( variable.name, period, 'month' if variable.definition_period == periods.MONTH else 'year' ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_memory_usage(self, variables = None): """ Get data about the virtual memory usage of the simulation """
result = dict( total_nb_bytes = 0, by_variable = {} ) for entity in self.populations.values(): entity_memory_usage = entity.get_memory_usage(variables = variables) result['total_nb_bytes'] += entity_memory_usage['total_nb_bytes'] result['by_variable'].update(entity_memory_usage['by_variable']) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_input(self, variable_name, period, value): """ Set a variable's value for a given period :param variable: the variable to be set :param value: the input value for the variable :param period: the period for which the value is setted Example: array([12, 14], dtype=int32) If a ``set_input`` property has been set for the variable, this method may accept inputs for periods not matching the ``definition_period`` of the variable. To read more about this, check the `documentation <https://openfisca.org/doc/coding-the-legislation/35_periods.html#automatically-process-variable-inputs-defined-for-periods-not-matching-the-definitionperiod>`_. """
variable = self.tax_benefit_system.get_variable(variable_name, check_existence = True) period = periods.period(period) if ((variable.end is not None) and (period.start.date > variable.end)): return self.get_holder(variable_name).set_input(period, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clone(self, debug = False, trace = False): """ Copy the simulation just enough to be able to run the copy without modifying the original simulation """
new = empty_clone(self) new_dict = new.__dict__ for key, value in self.__dict__.items(): if key not in ('debug', 'trace', 'tracer'): new_dict[key] = value new.persons = self.persons.clone(new) setattr(new, new.persons.entity.key, new.persons) new.populations = {new.persons.entity.key: new.persons} for entity in self.tax_benefit_system.group_entities: population = self.populations[entity.key].clone(new) new.populations[entity.key] = population setattr(new, entity.key, population) # create shortcut simulation.household (for instance) new.debug = debug new.trace = trace return new
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clone(self, population): """ Copy the holder just enough to be able to run a new simulation without modifying the original simulation. """
new = empty_clone(self) new_dict = new.__dict__ for key, value in self.__dict__.items(): if key not in ('population', 'formula', 'simulation'): new_dict[key] = value new_dict['population'] = population new_dict['simulation'] = population.simulation return new
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_arrays(self, period = None): """ If ``period`` is ``None``, remove all known values of the variable. If ``period`` is not ``None``, only remove all values for any period included in period (e.g. if period is "2017", values for "2017-01", "2017-07", etc. would be removed) """
self._memory_storage.delete(period) if self._disk_storage: self._disk_storage.delete(period)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_array(self, period): """ Get the value of the variable for the given period. If the value is not known, return ``None``. """
if self.variable.is_neutralized: return self.default_array() value = self._memory_storage.get(period) if value is not None: return value if self._disk_storage: return self._disk_storage.get(period)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_memory_usage(self): """ Get data about the virtual memory usage of the holder. :returns: Memory usage data :rtype: dict Example: """
usage = dict( nb_cells_by_array = self.population.count, dtype = self.variable.dtype, ) usage.update(self._memory_storage.get_memory_usage()) if self.simulation.trace: usage_stats = self.simulation.tracer.usage_stats[self.variable.name] usage.update(dict( nb_requests = usage_stats['nb_requests'], nb_requests_by_array = usage_stats['nb_requests'] / float(usage['nb_arrays']) if usage['nb_arrays'] > 0 else np.nan )) return usage
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_known_periods(self): """ Get the list of periods the variable value is known for. """
return list(self._memory_storage.get_known_periods()) + list(( self._disk_storage.get_known_periods() if self._disk_storage else []))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump_simulation(simulation, directory): """ Write simulation data to directory, so that it can be restored later. """
parent_directory = os.path.abspath(os.path.join(directory, os.pardir)) if not os.path.isdir(parent_directory): # To deal with reforms os.mkdir(parent_directory) if not os.path.isdir(directory): os.mkdir(directory) if os.listdir(directory): raise ValueError("Directory '{}' is not empty".format(directory)) entities_dump_dir = os.path.join(directory, "__entities__") os.mkdir(entities_dump_dir) for entity in simulation.populations.values(): # Dump entity structure _dump_entity(entity, entities_dump_dir) # Dump variable values for holder in entity._holders.values(): _dump_holder(holder, directory)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore_simulation(directory, tax_benefit_system, **kwargs): """ Restore simulation from directory """
simulation = Simulation(tax_benefit_system, tax_benefit_system.instantiate_entities()) entities_dump_dir = os.path.join(directory, "__entities__") for population in simulation.populations.values(): if population.entity.is_person: continue person_count = _restore_entity(population, entities_dump_dir) for population in simulation.populations.values(): if not population.entity.is_person: continue _restore_entity(population, entities_dump_dir) population.count = person_count variables_to_restore = (variable for variable in os.listdir(directory) if variable != "__entities__") for variable in variables_to_restore: _restore_holder(simulation, variable, directory) return simulation
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def are_forms_valid(self, forms): """ Check if all forms defined in `form_classes` are valid. """
for form in six.itervalues(forms): if not form.is_valid(): return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_context_data(self, **kwargs): """ Add forms into the context dictionary. """
context = {} if 'forms' not in kwargs: context['forms'] = self.get_forms() else: context['forms'] = kwargs['forms'] return context
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_form_kwargs(self): """ Build the keyword arguments required to instantiate the form. """
kwargs = {} for key in six.iterkeys(self.form_classes): if self.request.method in ('POST', 'PUT'): kwargs[key] = { 'data': self.request.POST, 'files': self.request.FILES, } else: kwargs[key] = {} return kwargs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_initial(self): """ Returns a copy of `initial` with empty initial data dictionaries for each form. """
initial = super(MultiFormView, self).get_initial() for key in six.iterkeys(self.form_classes): initial[key] = {} return initial
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_objects(self): """ Returns dictionary with the instance objects for each form. Keys should match the corresponding form. """
objects = {} for key in six.iterkeys(self.form_classes): objects[key] = None return objects
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ratio_split(amount, ratios): """ Split in_value according to the ratios specified in `ratios` This is special in that it ensures the returned values always sum to in_value (i.e. we avoid losses or gains due to rounding errors). As a result, this method returns a list of `Decimal` values with length equal to that of `ratios`. Examples: .. code-block:: python [Decimal('3.33'), Decimal('6.67')] Note the returned values sum to the original input of ``10``. If we were to do this calculation in a naive fashion then the returned values would likely be ``3.33`` and ``6.66``, which would sum to ``9.99``, thereby loosing ``0.01``. Args: amount (Decimal): The amount to be split ratios (list[Decimal]): The ratios that will determine the split Returns: list(Decimal) """
ratio_total = sum(ratios) divided_value = amount / ratio_total values = [] for ratio in ratios: value = divided_value * ratio values.append(value) # Now round the values, keeping track of the bits we cut off rounded = [v.quantize(Decimal("0.01")) for v in values] remainders = [v - rounded[i] for i, v in enumerate(values)] remainder = sum(remainders) # Give the last person the (positive or negative) remainder rounded[-1] = (rounded[-1] + remainder).quantize(Decimal("0.01")) assert sum(rounded) == amount return rounded
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_columns(self): """For each column in file create a TransactionCsvImportColumn"""
reader = self._get_csv_reader() headings = six.next(reader) try: examples = six.next(reader) except StopIteration: examples = [] found_fields = set() for i, value in enumerate(headings): if i >= 20: break infer_field = self.has_headings and value not in found_fields to_field = ( { "date": "date", "amount": "amount", "description": "description", "memo": "description", "notes": "description", }.get(value.lower(), "") if infer_field else "" ) if to_field: found_fields.add(to_field) TransactionCsvImportColumn.objects.update_or_create( transaction_import=self, column_number=i + 1, column_heading=value if self.has_headings else "", to_field=to_field, example=examples[i].strip() if examples else "", )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_num_similar_objects(self, obj): """Get any statement lines which would be considered a duplicate of obj"""
return StatementLine.objects.filter( date=obj.date, amount=obj.amount, description=obj.description ).count()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_num_similar_rows(self, row, until=None): """Get the number of rows similar to row which precede the index `until`"""
return len(list(filter(lambda r: row == r, self.dataset[:until])))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_import(token, account_uuid, bank_account, since=None): """Import data from teller.io Returns the created StatementImport """
response = requests.get( url="https://api.teller.io/accounts/{}/transactions".format(account_uuid), headers={"Authorization": "Bearer {}".format(token)}, ) response.raise_for_status() data = response.json() statement_import = StatementImport.objects.create( source="teller.io", extra={"account_uuid": account_uuid}, bank_account=bank_account ) for line_data in data: uuid = UUID(hex=line_data["id"]) if StatementLine.objects.filter(uuid=uuid): continue description = ", ".join(filter(bool, [line_data["counterparty"], line_data["description"]])) date = datetime.date(*map(int, line_data["date"].split("-"))) if not since or date >= since: StatementLine.objects.create( uuid=uuid, date=line_data["date"], statement_import=statement_import, amount=line_data["amount"], type=line_data["type"], description=description, source_data=line_data, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_accounting_equation(cls): """Check that all accounts sum to 0"""
balances = [account.balance(raw=True) for account in Account.objects.root_nodes()] if sum(balances, Balance()) != 0: raise exceptions.AccountingEquationViolationError( "Account balances do not sum to zero. They sum to {}".format(sum(balances)) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sign(self): """ Returns 1 if a credit should increase the value of the account, or -1 if a credit should decrease the value of the account. This is based on the account type as is standard accounting practice. The signs can be derrived from the following expanded form of the accounting equation: Assets = Liabilities + Equity + (Income - Expenses) Which can be rearranged as: 0 = Liabilities + Equity + Income - Expenses - Assets Further details here: https://en.wikipedia.org/wiki/Debits_and_credits """
return -1 if self.type in (Account.TYPES.asset, Account.TYPES.expense) else 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def balance(self, as_of=None, raw=False, leg_query=None, **kwargs): """Get the balance for this account, including child accounts Args: as_of (Date): Only include transactions on or before this date raw (bool): If true the returned balance should not have its sign adjusted for display purposes. kwargs (dict): Will be used to filter the transaction legs Returns: Balance See Also: :meth:`simple_balance()` """
balances = [ account.simple_balance(as_of=as_of, raw=raw, leg_query=leg_query, **kwargs) for account in self.get_descendants(include_self=True) ] return sum(balances, Balance())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simple_balance(self, as_of=None, raw=False, leg_query=None, **kwargs): """Get the balance for this account, ignoring all child accounts Args: as_of (Date): Only include transactions on or before this date raw (bool): If true the returned balance should not have its sign adjusted for display purposes. leg_query (models.Q): Django Q-expression, will be used to filter the transaction legs. allows for more complex filtering than that provided by **kwargs. kwargs (dict): Will be used to filter the transaction legs Returns: Balance """
legs = self.legs if as_of: legs = legs.filter(transaction__date__lte=as_of) if leg_query or kwargs: leg_query = leg_query or models.Q() legs = legs.filter(leg_query, **kwargs) return legs.sum_to_balance() * (1 if raw else self.sign) + self._zero_balance()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transfer_to(self, to_account, amount, **transaction_kwargs): """Create a transaction which transfers amount to to_account This is a shortcut utility method which simplifies the process of transferring between accounts. This method attempts to perform the transaction in an intuitive manner. For example: * Transferring income -> income will result in the former decreasing and the latter increasing * Transferring asset (i.e. bank) -> income will result in the balance of both increasing * Transferring asset -> asset will result in the former decreasing and the latter increasing .. note:: Transfers in any direction between ``{asset | expense} <-> {income | liability | equity}`` will always result in both balances increasing. This may change in future if it is found to be unhelpful. Transfers to trading accounts will always behave as normal. Args: to_account (Account): The destination account. amount (Money): The amount to be transferred. transaction_kwargs: Passed through to transaction creation. Useful for setting the transaction `description` field. """
if not isinstance(amount, Money): raise TypeError("amount must be of type Money") if to_account.sign == 1 and to_account.type != self.TYPES.trading: # Transferring from two positive-signed accounts implies that # the caller wants to reduce the first account and increase the second # (which is opposite to the implicit behaviour) direction = -1 elif self.type == self.TYPES.liability and to_account.type == self.TYPES.expense: # Transfers from liability -> asset accounts should reduce both. # For example, moving money from Rent Payable (liability) to your Rent (expense) account # should use the funds you've built up in the liability account to pay off the expense account. direction = -1 else: direction = 1 transaction = Transaction.objects.create(**transaction_kwargs) Leg.objects.create(transaction=transaction, account=self, amount=+amount * direction) Leg.objects.create(transaction=transaction, account=to_account, amount=-amount * direction) return transaction
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sum_to_balance(self): """Sum the Legs of the QuerySet to get a `Balance`_ object """
result = self.values("amount_currency").annotate(total=models.Sum("amount")) return Balance([Money(r["total"], r["amount_currency"]) for r in result])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def account_balance_after(self): """Get the balance of the account associated with this leg following the transaction"""
# TODO: Consider moving to annotation, particularly once we can count on Django 1.11's subquery support transaction_date = self.transaction.date return self.account.balance( leg_query=( models.Q(transaction__date__lt=transaction_date) | ( models.Q(transaction__date=transaction_date) & models.Q(transaction_id__lte=self.transaction_id) ) ) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def account_balance_before(self): """Get the balance of the account associated with this leg before the transaction"""
# TODO: Consider moving to annotation, particularly once we can count on Django 1.11's subquery support transaction_date = self.transaction.date return self.account.balance( leg_query=( models.Q(transaction__date__lt=transaction_date) | ( models.Q(transaction__date=transaction_date) & models.Q(transaction_id__lt=self.transaction_id) ) ) )