repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_documentation_string stringlengths 1 47.2k | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|
ihmeuw/vivarium | src/vivarium/interface/interactive.py | setup_simulation | def setup_simulation(components: List, input_config: Mapping=None,
plugin_config: Mapping=None) -> InteractiveContext:
"""Construct a simulation from a list of components and call its setup
method.
Parameters
----------
components
A list of initialized simulation compon... | python | def setup_simulation(components: List, input_config: Mapping=None,
plugin_config: Mapping=None) -> InteractiveContext:
"""Construct a simulation from a list of components and call its setup
method.
Parameters
----------
components
A list of initialized simulation compon... | Construct a simulation from a list of components and call its setup
method.
Parameters
----------
components
A list of initialized simulation components. Corresponds to the
components block of a model specification.
input_config
A nested dictionary with any additional simula... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interface/interactive.py#L230-L258 |
ihmeuw/vivarium | src/vivarium/interface/interactive.py | initialize_simulation_from_model_specification | def initialize_simulation_from_model_specification(model_specification_file: str) -> InteractiveContext:
"""Construct a simulation from a model specification file.
The simulation context returned by this method still needs to be setup by
calling its setup method. It is mostly useful for testing and debuggi... | python | def initialize_simulation_from_model_specification(model_specification_file: str) -> InteractiveContext:
"""Construct a simulation from a model specification file.
The simulation context returned by this method still needs to be setup by
calling its setup method. It is mostly useful for testing and debuggi... | Construct a simulation from a model specification file.
The simulation context returned by this method still needs to be setup by
calling its setup method. It is mostly useful for testing and debugging.
Parameters
----------
model_specification_file
The path to a model specification file.
... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interface/interactive.py#L261-L286 |
ihmeuw/vivarium | src/vivarium/interface/interactive.py | setup_simulation_from_model_specification | def setup_simulation_from_model_specification(model_specification_file: str) -> InteractiveContext:
"""Construct a simulation from a model specification file and call its setup
method.
Parameters
----------
model_specification_file
The path to a model specification file.
Returns
--... | python | def setup_simulation_from_model_specification(model_specification_file: str) -> InteractiveContext:
"""Construct a simulation from a model specification file and call its setup
method.
Parameters
----------
model_specification_file
The path to a model specification file.
Returns
--... | Construct a simulation from a model specification file and call its setup
method.
Parameters
----------
model_specification_file
The path to a model specification file.
Returns
-------
A simulation context that is setup and ready to run. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interface/interactive.py#L289-L305 |
ihmeuw/vivarium | src/vivarium/interface/interactive.py | InteractiveContext.setup | def setup(self):
"""Setup the simulation and initialize its population."""
super().setup()
self._start_time = self.clock.time
self.initialize_simulants() | python | def setup(self):
"""Setup the simulation and initialize its population."""
super().setup()
self._start_time = self.clock.time
self.initialize_simulants() | Setup the simulation and initialize its population. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interface/interactive.py#L28-L32 |
ihmeuw/vivarium | src/vivarium/interface/interactive.py | InteractiveContext.initialize_simulants | def initialize_simulants(self):
"""Initialize this simulation's population. Should not be called
directly."""
super().initialize_simulants()
self._initial_population = self.population.get_population(True) | python | def initialize_simulants(self):
"""Initialize this simulation's population. Should not be called
directly."""
super().initialize_simulants()
self._initial_population = self.population.get_population(True) | Initialize this simulation's population. Should not be called
directly. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interface/interactive.py#L34-L38 |
ihmeuw/vivarium | src/vivarium/interface/interactive.py | InteractiveContext.reset | def reset(self):
"""Reset the simulation to its initial state."""
warnings.warn("This reset method is very crude. It should work for "
"many simple simulations, but we make no guarantees. In "
"particular, if you have components that manage their "
... | python | def reset(self):
"""Reset the simulation to its initial state."""
warnings.warn("This reset method is very crude. It should work for "
"many simple simulations, but we make no guarantees. In "
"particular, if you have components that manage their "
... | Reset the simulation to its initial state. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interface/interactive.py#L40-L47 |
ihmeuw/vivarium | src/vivarium/interface/interactive.py | InteractiveContext.run | def run(self, with_logging: bool=True) -> int:
"""Run the simulation for the time duration specified in the
configuration
Parameters
----------
with_logging
Whether or not to log the simulation steps. Only works in an ipython
environment.
Returns... | python | def run(self, with_logging: bool=True) -> int:
"""Run the simulation for the time duration specified in the
configuration
Parameters
----------
with_logging
Whether or not to log the simulation steps. Only works in an ipython
environment.
Returns... | Run the simulation for the time duration specified in the
configuration
Parameters
----------
with_logging
Whether or not to log the simulation steps. Only works in an ipython
environment.
Returns
-------
The number of steps the simul... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interface/interactive.py#L50-L64 |
ihmeuw/vivarium | src/vivarium/interface/interactive.py | InteractiveContext.run_for | def run_for(self, duration: Timedelta, with_logging: bool=True) -> int:
"""Run the simulation for the given time duration.
Parameters
----------
duration
The length of time to run the simulation for. Should be the same
type as the simulation clock's step size (u... | python | def run_for(self, duration: Timedelta, with_logging: bool=True) -> int:
"""Run the simulation for the given time duration.
Parameters
----------
duration
The length of time to run the simulation for. Should be the same
type as the simulation clock's step size (u... | Run the simulation for the given time duration.
Parameters
----------
duration
The length of time to run the simulation for. Should be the same
type as the simulation clock's step size (usually a pandas
Timedelta).
with_logging
Whether or... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interface/interactive.py#L67-L85 |
ihmeuw/vivarium | src/vivarium/interface/interactive.py | InteractiveContext.run_until | def run_until(self, end_time: Time, with_logging=True) -> int:
"""Run the simulation until the provided end time.
Parameters
----------
end_time
The time to run the simulation until. The simulation will run until
its clock is greater than or equal to the provided... | python | def run_until(self, end_time: Time, with_logging=True) -> int:
"""Run the simulation until the provided end time.
Parameters
----------
end_time
The time to run the simulation until. The simulation will run until
its clock is greater than or equal to the provided... | Run the simulation until the provided end time.
Parameters
----------
end_time
The time to run the simulation until. The simulation will run until
its clock is greater than or equal to the provided end time.
with_logging
Whether or not to log the simu... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interface/interactive.py#L88-L110 |
ihmeuw/vivarium | src/vivarium/interface/interactive.py | InteractiveContext.step | def step(self, step_size: Timedelta=None):
"""Advance the simulation one step.
Parameters
----------
step_size
An optional size of step to take. Must be the same type as the
simulation clock's step size (usually a pandas.Timedelta).
"""
old_step_s... | python | def step(self, step_size: Timedelta=None):
"""Advance the simulation one step.
Parameters
----------
step_size
An optional size of step to take. Must be the same type as the
simulation clock's step size (usually a pandas.Timedelta).
"""
old_step_s... | Advance the simulation one step.
Parameters
----------
step_size
An optional size of step to take. Must be the same type as the
simulation clock's step size (usually a pandas.Timedelta). | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interface/interactive.py#L113-L128 |
ihmeuw/vivarium | src/vivarium/interface/interactive.py | InteractiveContext.take_steps | def take_steps(self, number_of_steps: int=1, step_size: Timedelta=None, with_logging: bool=True):
"""Run the simulation for the given number of steps.
Parameters
----------
number_of_steps
The number of steps to take.
step_size
An optional size of step to... | python | def take_steps(self, number_of_steps: int=1, step_size: Timedelta=None, with_logging: bool=True):
"""Run the simulation for the given number of steps.
Parameters
----------
number_of_steps
The number of steps to take.
step_size
An optional size of step to... | Run the simulation for the given number of steps.
Parameters
----------
number_of_steps
The number of steps to take.
step_size
An optional size of step to take. Must be the same type as the
simulation clock's step size (usually a pandas.Timedelta).
... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interface/interactive.py#L131-L153 |
ihmeuw/vivarium | src/vivarium/interface/interactive.py | InteractiveContext.get_population | def get_population(self, untracked: bool=False) -> pd.DataFrame:
"""Get a copy of the population state table."""
return self.population.get_population(untracked) | python | def get_population(self, untracked: bool=False) -> pd.DataFrame:
"""Get a copy of the population state table."""
return self.population.get_population(untracked) | Get a copy of the population state table. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interface/interactive.py#L156-L158 |
ihmeuw/vivarium | src/vivarium/interface/interactive.py | InteractiveContext.get_listeners | def get_listeners(self, event_type: str) -> List[Callable]:
"""Get all listeners of a particular type of event."""
if event_type not in self.events:
raise ValueError(f'No event {event_type} in system.')
return self.events.get_listeners(event_type) | python | def get_listeners(self, event_type: str) -> List[Callable]:
"""Get all listeners of a particular type of event."""
if event_type not in self.events:
raise ValueError(f'No event {event_type} in system.')
return self.events.get_listeners(event_type) | Get all listeners of a particular type of event. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interface/interactive.py#L176-L180 |
ihmeuw/vivarium | src/vivarium/interface/interactive.py | InteractiveContext.get_emitter | def get_emitter(self, event_type: str) -> Callable:
"""Get the callable that emits the given type of events."""
if event_type not in self.events:
raise ValueError(f'No event {event_type} in system.')
return self.events.get_emitter(event_type) | python | def get_emitter(self, event_type: str) -> Callable:
"""Get the callable that emits the given type of events."""
if event_type not in self.events:
raise ValueError(f'No event {event_type} in system.')
return self.events.get_emitter(event_type) | Get the callable that emits the given type of events. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interface/interactive.py#L183-L187 |
ihmeuw/vivarium | src/vivarium/interface/interactive.py | InteractiveContext.get_components | def get_components(self) -> List:
"""Get a list of all components in the simulation."""
return [component for component in self.component_manager._components + self.component_manager._managers] | python | def get_components(self) -> List:
"""Get a list of all components in the simulation."""
return [component for component in self.component_manager._components + self.component_manager._managers] | Get a list of all components in the simulation. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interface/interactive.py#L190-L192 |
ihmeuw/vivarium | src/vivarium/framework/lookup.py | LookupTableInterface.build_table | def build_table(self, data, key_columns=('sex',), parameter_columns=(['age', 'age_group_start', 'age_group_end'],
['year', 'year_start', 'year_end']),
value_columns=None) -> LookupTable:
"""Construct a LookupTable from ... | python | def build_table(self, data, key_columns=('sex',), parameter_columns=(['age', 'age_group_start', 'age_group_end'],
['year', 'year_start', 'year_end']),
value_columns=None) -> LookupTable:
"""Construct a LookupTable from ... | Construct a LookupTable from input data.
If data is a ``pandas.DataFrame``, an interpolation function of the specified
order will be calculated for each permutation of the set of key_columns.
The columns in parameter_columns will be used as parameters for the interpolation
functions whi... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/lookup.py#L242-L276 |
ihmeuw/vivarium | src/vivarium/interpolation.py | check_data_complete | def check_data_complete(data, parameter_columns):
""" For any parameters specified with edges, make sure edges
don't overlap and don't have any gaps. Assumes that edges are
specified with ends and starts overlapping (but one exclusive and
the other inclusive) so can check that end of previous == start
... | python | def check_data_complete(data, parameter_columns):
""" For any parameters specified with edges, make sure edges
don't overlap and don't have any gaps. Assumes that edges are
specified with ends and starts overlapping (but one exclusive and
the other inclusive) so can check that end of previous == start
... | For any parameters specified with edges, make sure edges
don't overlap and don't have any gaps. Assumes that edges are
specified with ends and starts overlapping (but one exclusive and
the other inclusive) so can check that end of previous == start
of current.
If multiple parameters, make sure all ... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interpolation.py#L144-L185 |
ihmeuw/vivarium | src/vivarium/framework/results_writer.py | ResultsWriter.add_sub_directory | def add_sub_directory(self, key, path):
"""Adds a sub-directory to the results directory.
Parameters
----------
key: str
A look-up key for the directory path.
path: str
The relative path from the root of the results directory to the sub-directory.
... | python | def add_sub_directory(self, key, path):
"""Adds a sub-directory to the results directory.
Parameters
----------
key: str
A look-up key for the directory path.
path: str
The relative path from the root of the results directory to the sub-directory.
... | Adds a sub-directory to the results directory.
Parameters
----------
key: str
A look-up key for the directory path.
path: str
The relative path from the root of the results directory to the sub-directory.
Returns
-------
str:
... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/results_writer.py#L30-L48 |
ihmeuw/vivarium | src/vivarium/framework/results_writer.py | ResultsWriter.write_output | def write_output(self, data, file_name, key=None):
"""Writes output data to disk.
Parameters
----------
data: pandas.DataFrame or dict
The data to write to disk.
file_name: str
The name of the file to write.
key: str, optional
The look... | python | def write_output(self, data, file_name, key=None):
"""Writes output data to disk.
Parameters
----------
data: pandas.DataFrame or dict
The data to write to disk.
file_name: str
The name of the file to write.
key: str, optional
The look... | Writes output data to disk.
Parameters
----------
data: pandas.DataFrame or dict
The data to write to disk.
file_name: str
The name of the file to write.
key: str, optional
The lookup key for the sub_directory to write results to, if any. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/results_writer.py#L50-L79 |
ihmeuw/vivarium | src/vivarium/framework/results_writer.py | ResultsWriter.copy_file | def copy_file(self, src_path, file_name, key=None):
"""Copies a file unmodified to a location inside the ouput directory.
Parameters
----------
src_path: str
Path to the src file
file_name: str
name of the destination file
"""
path = os.pa... | python | def copy_file(self, src_path, file_name, key=None):
"""Copies a file unmodified to a location inside the ouput directory.
Parameters
----------
src_path: str
Path to the src file
file_name: str
name of the destination file
"""
path = os.pa... | Copies a file unmodified to a location inside the ouput directory.
Parameters
----------
src_path: str
Path to the src file
file_name: str
name of the destination file | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/results_writer.py#L81-L92 |
casastorta/python-sar | sar/multiparser.py | Multiparser.load_file | def load_file(self):
'''
Loads combined SAR format logfile in ASCII format.
:return: ``True`` if loading and parsing of file went fine, \
``False`` if it failed (at any point)
'''
daychunks = self.__split_file()
if (daychunks):
maxcount = len... | python | def load_file(self):
'''
Loads combined SAR format logfile in ASCII format.
:return: ``True`` if loading and parsing of file went fine, \
``False`` if it failed (at any point)
'''
daychunks = self.__split_file()
if (daychunks):
maxcount = len... | Loads combined SAR format logfile in ASCII format.
:return: ``True`` if loading and parsing of file went fine, \
``False`` if it failed (at any point) | https://github.com/casastorta/python-sar/blob/e6d8bb86524102d677f37e985302fad34e3297c1/sar/multiparser.py#L44-L79 |
casastorta/python-sar | sar/multiparser.py | Multiparser.__get_chunk | def __get_chunk(self, start=0, end=None):
'''
Gets chunk from the sar combo file, from start to end
:param start: where to start a pulled chunk
:type start: int.
:param end: where to end a pulled chunk
:type end: int.
:return: str.
'''
... | python | def __get_chunk(self, start=0, end=None):
'''
Gets chunk from the sar combo file, from start to end
:param start: where to start a pulled chunk
:type start: int.
:param end: where to end a pulled chunk
:type end: int.
:return: str.
'''
... | Gets chunk from the sar combo file, from start to end
:param start: where to start a pulled chunk
:type start: int.
:param end: where to end a pulled chunk
:type end: int.
:return: str. | https://github.com/casastorta/python-sar/blob/e6d8bb86524102d677f37e985302fad34e3297c1/sar/multiparser.py#L88-L130 |
casastorta/python-sar | sar/multiparser.py | Multiparser.__split_file | def __split_file(self):
'''
Splits combined SAR output file (in ASCII format) in order to
extract info we need for it, in the format we want.
:return: ``List``-style of SAR file sections separated by
the type of info they contain (SAR file sections) without
... | python | def __split_file(self):
'''
Splits combined SAR output file (in ASCII format) in order to
extract info we need for it, in the format we want.
:return: ``List``-style of SAR file sections separated by
the type of info they contain (SAR file sections) without
... | Splits combined SAR output file (in ASCII format) in order to
extract info we need for it, in the format we want.
:return: ``List``-style of SAR file sections separated by
the type of info they contain (SAR file sections) without
parsing what is exactly what at this p... | https://github.com/casastorta/python-sar/blob/e6d8bb86524102d677f37e985302fad34e3297c1/sar/multiparser.py#L132-L180 |
casastorta/python-sar | sar/multiparser.py | Multiparser.__get_part_date | def __get_part_date(self, part=''):
'''
Retrieves date of the combo part from the file
:param part: Part of the combo file (parsed out whole SAR file
from the combo
:type part: str.
:return: string containing date in ISO format (YYY-MM-DD)
'''
... | python | def __get_part_date(self, part=''):
'''
Retrieves date of the combo part from the file
:param part: Part of the combo file (parsed out whole SAR file
from the combo
:type part: str.
:return: string containing date in ISO format (YYY-MM-DD)
'''
... | Retrieves date of the combo part from the file
:param part: Part of the combo file (parsed out whole SAR file
from the combo
:type part: str.
:return: string containing date in ISO format (YYY-MM-DD) | https://github.com/casastorta/python-sar/blob/e6d8bb86524102d677f37e985302fad34e3297c1/sar/multiparser.py#L182-L209 |
datosgobar/pydatajson | pydatajson/ckan_reader.py | read_ckan_catalog | def read_ckan_catalog(portal_url):
"""Convierte los metadatos de un portal disponibilizados por la Action API
v3 de CKAN al estándar data.json.
Args:
portal_url (str): URL de un portal de datos CKAN que soporte la API v3.
Returns:
dict: Representación interna de un catálogo para uso en... | python | def read_ckan_catalog(portal_url):
"""Convierte los metadatos de un portal disponibilizados por la Action API
v3 de CKAN al estándar data.json.
Args:
portal_url (str): URL de un portal de datos CKAN que soporte la API v3.
Returns:
dict: Representación interna de un catálogo para uso en... | Convierte los metadatos de un portal disponibilizados por la Action API
v3 de CKAN al estándar data.json.
Args:
portal_url (str): URL de un portal de datos CKAN que soporte la API v3.
Returns:
dict: Representación interna de un catálogo para uso en las funciones
de esta librerí... | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/ckan_reader.py#L39-L92 |
datosgobar/pydatajson | pydatajson/ckan_reader.py | map_status_to_catalog | def map_status_to_catalog(status):
"""Convierte el resultado de action.status_show() en metadata a nivel de
catálogo."""
catalog = dict()
catalog_mapping = {
"site_title": "title",
"site_description": "description"
}
for status_key, catalog_key in iteritems(catalog_mapping):
... | python | def map_status_to_catalog(status):
"""Convierte el resultado de action.status_show() en metadata a nivel de
catálogo."""
catalog = dict()
catalog_mapping = {
"site_title": "title",
"site_description": "description"
}
for status_key, catalog_key in iteritems(catalog_mapping):
... | Convierte el resultado de action.status_show() en metadata a nivel de
catálogo. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/ckan_reader.py#L95-L136 |
datosgobar/pydatajson | pydatajson/ckan_reader.py | map_package_to_dataset | def map_package_to_dataset(package, portal_url):
"""Mapea un diccionario con metadatos de cierto 'package' de CKAN a un
diccionario con metadatos de un 'dataset' según el estándar data.json."""
dataset = dict()
resources = package["resources"]
groups = package["groups"]
tags = package["tags"]
... | python | def map_package_to_dataset(package, portal_url):
"""Mapea un diccionario con metadatos de cierto 'package' de CKAN a un
diccionario con metadatos de un 'dataset' según el estándar data.json."""
dataset = dict()
resources = package["resources"]
groups = package["groups"]
tags = package["tags"]
... | Mapea un diccionario con metadatos de cierto 'package' de CKAN a un
diccionario con metadatos de un 'dataset' según el estándar data.json. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/ckan_reader.py#L145-L219 |
datosgobar/pydatajson | pydatajson/ckan_reader.py | map_resource_to_distribution | def map_resource_to_distribution(resource, portal_url):
"""Mapea un diccionario con metadatos de cierto 'resource' CKAN a dicts
con metadatos de una 'distribution' según el estándar data.json."""
distribution = dict()
distribution_mapping = {
'url': 'downloadURL',
'name': 'title',
... | python | def map_resource_to_distribution(resource, portal_url):
"""Mapea un diccionario con metadatos de cierto 'resource' CKAN a dicts
con metadatos de una 'distribution' según el estándar data.json."""
distribution = dict()
distribution_mapping = {
'url': 'downloadURL',
'name': 'title',
... | Mapea un diccionario con metadatos de cierto 'resource' CKAN a dicts
con metadatos de una 'distribution' según el estándar data.json. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/ckan_reader.py#L348-L387 |
datosgobar/pydatajson | pydatajson/ckan_reader.py | map_group_to_theme | def map_group_to_theme(group):
"""Mapea un diccionario con metadatos de cierto 'group' de CKAN a un
diccionario con metadatos de un 'theme' según el estándar data.json."""
theme = dict()
theme_mapping = {
'name': 'id',
'title': 'label',
'description': 'description'
}
fo... | python | def map_group_to_theme(group):
"""Mapea un diccionario con metadatos de cierto 'group' de CKAN a un
diccionario con metadatos de un 'theme' según el estándar data.json."""
theme = dict()
theme_mapping = {
'name': 'id',
'title': 'label',
'description': 'description'
}
fo... | Mapea un diccionario con metadatos de cierto 'group' de CKAN a un
diccionario con metadatos de un 'theme' según el estándar data.json. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/ckan_reader.py#L395-L415 |
datosgobar/pydatajson | pydatajson/writers.py | write_tables | def write_tables(tables, path, column_styles=None, cell_styles=None,
tables_fields=None, tables_names=None):
""" Exporta un reporte con varias tablas en CSV o XLSX.
Si la extensión es ".csv" se crean varias tablas agregando el nombre de la
tabla al final del "path". Si la extensión es ".xl... | python | def write_tables(tables, path, column_styles=None, cell_styles=None,
tables_fields=None, tables_names=None):
""" Exporta un reporte con varias tablas en CSV o XLSX.
Si la extensión es ".csv" se crean varias tablas agregando el nombre de la
tabla al final del "path". Si la extensión es ".xl... | Exporta un reporte con varias tablas en CSV o XLSX.
Si la extensión es ".csv" se crean varias tablas agregando el nombre de la
tabla al final del "path". Si la extensión es ".xlsx" todas las tablas se
escriben en el mismo excel.
Args:
table (dict of (list of dicts)): Conjunto de tablas a ser e... | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/writers.py#L29-L66 |
datosgobar/pydatajson | pydatajson/writers.py | write_table | def write_table(table, path, column_styles=None, cell_styles=None):
""" Exporta una tabla en el formato deseado (CSV o XLSX).
La extensión del archivo debe ser ".csv" o ".xlsx", y en función de
ella se decidirá qué método usar para escribirlo.
Args:
table (list of dicts): Tabla a ser exportada... | python | def write_table(table, path, column_styles=None, cell_styles=None):
""" Exporta una tabla en el formato deseado (CSV o XLSX).
La extensión del archivo debe ser ".csv" o ".xlsx", y en función de
ella se decidirá qué método usar para escribirlo.
Args:
table (list of dicts): Tabla a ser exportada... | Exporta una tabla en el formato deseado (CSV o XLSX).
La extensión del archivo debe ser ".csv" o ".xlsx", y en función de
ella se decidirá qué método usar para escribirlo.
Args:
table (list of dicts): Tabla a ser exportada.
path (str): Path al archivo CSV o XLSX de exportación. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/writers.py#L69-L100 |
datosgobar/pydatajson | pydatajson/writers.py | write_json | def write_json(obj, path):
"""Escribo un objeto a un archivo JSON con codificación UTF-8."""
obj_str = text_type(json.dumps(obj, indent=4, separators=(",", ": "),
ensure_ascii=False))
helpers.ensure_dir_exists(os.path.dirname(path))
with io.open(path, "w", encoding='... | python | def write_json(obj, path):
"""Escribo un objeto a un archivo JSON con codificación UTF-8."""
obj_str = text_type(json.dumps(obj, indent=4, separators=(",", ": "),
ensure_ascii=False))
helpers.ensure_dir_exists(os.path.dirname(path))
with io.open(path, "w", encoding='... | Escribo un objeto a un archivo JSON con codificación UTF-8. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/writers.py#L245-L253 |
datosgobar/pydatajson | pydatajson/writers.py | write_xlsx_catalog | def write_xlsx_catalog(catalog, path, xlsx_fields=None):
"""Escribe el catálogo en Excel.
Args:
catalog (DataJson): Catálogo de datos.
path (str): Directorio absoluto donde se crea el archivo XLSX.
xlsx_fields (dict): Orden en que los campos del perfil de metadatos
se escrib... | python | def write_xlsx_catalog(catalog, path, xlsx_fields=None):
"""Escribe el catálogo en Excel.
Args:
catalog (DataJson): Catálogo de datos.
path (str): Directorio absoluto donde se crea el archivo XLSX.
xlsx_fields (dict): Orden en que los campos del perfil de metadatos
se escrib... | Escribe el catálogo en Excel.
Args:
catalog (DataJson): Catálogo de datos.
path (str): Directorio absoluto donde se crea el archivo XLSX.
xlsx_fields (dict): Orden en que los campos del perfil de metadatos
se escriben en cada hoja del Excel. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/writers.py#L468-L494 |
datosgobar/pydatajson | pydatajson/download.py | download | def download(url, tries=DEFAULT_TRIES, retry_delay=RETRY_DELAY,
try_timeout=None, proxies=None, verify=True):
"""
Descarga un archivo a través del protocolo HTTP, en uno o más intentos.
Args:
url (str): URL (schema HTTP) del archivo a descargar.
tries (int): Intentos a realizar... | python | def download(url, tries=DEFAULT_TRIES, retry_delay=RETRY_DELAY,
try_timeout=None, proxies=None, verify=True):
"""
Descarga un archivo a través del protocolo HTTP, en uno o más intentos.
Args:
url (str): URL (schema HTTP) del archivo a descargar.
tries (int): Intentos a realizar... | Descarga un archivo a través del protocolo HTTP, en uno o más intentos.
Args:
url (str): URL (schema HTTP) del archivo a descargar.
tries (int): Intentos a realizar (default: 1).
retry_delay (int o float): Tiempo a esperar, en segundos, entre cada
intento.
try_timeout (i... | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/download.py#L19-L47 |
datosgobar/pydatajson | pydatajson/download.py | download_to_file | def download_to_file(url, file_path, **kwargs):
"""
Descarga un archivo a través del protocolo HTTP, en uno o más intentos, y
escribe el contenido descargado el el path especificado.
Args:
url (str): URL (schema HTTP) del archivo a descargar.
file_path (str): Path del archivo a escribir... | python | def download_to_file(url, file_path, **kwargs):
"""
Descarga un archivo a través del protocolo HTTP, en uno o más intentos, y
escribe el contenido descargado el el path especificado.
Args:
url (str): URL (schema HTTP) del archivo a descargar.
file_path (str): Path del archivo a escribir... | Descarga un archivo a través del protocolo HTTP, en uno o más intentos, y
escribe el contenido descargado el el path especificado.
Args:
url (str): URL (schema HTTP) del archivo a descargar.
file_path (str): Path del archivo a escribir. Si un archivo ya existe
en el path especificad... | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/download.py#L50-L63 |
ihmeuw/vivarium | src/vivarium/framework/values.py | replace_combiner | def replace_combiner(value, mutator, *args, **kwargs):
"""Replaces the output of the source or mutator with the output
of the subsequent mutator. This is the default combiner.
"""
args = list(args) + [value]
return mutator(*args, **kwargs) | python | def replace_combiner(value, mutator, *args, **kwargs):
"""Replaces the output of the source or mutator with the output
of the subsequent mutator. This is the default combiner.
"""
args = list(args) + [value]
return mutator(*args, **kwargs) | Replaces the output of the source or mutator with the output
of the subsequent mutator. This is the default combiner. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/values.py#L23-L28 |
ihmeuw/vivarium | src/vivarium/framework/values.py | set_combiner | def set_combiner(value, mutator, *args, **kwargs):
"""Expects the output of the source to be a set to which
the result of each mutator is added.
"""
value.add(mutator(*args, **kwargs))
return value | python | def set_combiner(value, mutator, *args, **kwargs):
"""Expects the output of the source to be a set to which
the result of each mutator is added.
"""
value.add(mutator(*args, **kwargs))
return value | Expects the output of the source to be a set to which
the result of each mutator is added. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/values.py#L31-L36 |
ihmeuw/vivarium | src/vivarium/framework/values.py | list_combiner | def list_combiner(value, mutator, *args, **kwargs):
"""Expects the output of the source to be a list to which
the result of each mutator is appended.
"""
value.append(mutator(*args, **kwargs))
return value | python | def list_combiner(value, mutator, *args, **kwargs):
"""Expects the output of the source to be a list to which
the result of each mutator is appended.
"""
value.append(mutator(*args, **kwargs))
return value | Expects the output of the source to be a list to which
the result of each mutator is appended. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/values.py#L39-L44 |
ihmeuw/vivarium | src/vivarium/framework/values.py | joint_value_post_processor | def joint_value_post_processor(a, _):
"""The final step in calculating joint values like disability weights.
If the combiner is list_combiner then the effective formula is:
.. math::
value(args) = 1 - \prod_{i=1}^{mutator count} 1-mutator_{i}(args)
Parameters
----------
a : List[pd.S... | python | def joint_value_post_processor(a, _):
"""The final step in calculating joint values like disability weights.
If the combiner is list_combiner then the effective formula is:
.. math::
value(args) = 1 - \prod_{i=1}^{mutator count} 1-mutator_{i}(args)
Parameters
----------
a : List[pd.S... | The final step in calculating joint values like disability weights.
If the combiner is list_combiner then the effective formula is:
.. math::
value(args) = 1 - \prod_{i=1}^{mutator count} 1-mutator_{i}(args)
Parameters
----------
a : List[pd.Series]
a is a list of series, indexed... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/values.py#L54-L79 |
ihmeuw/vivarium | src/vivarium/framework/values.py | ValuesInterface.register_value_producer | def register_value_producer(self, value_name: str, source: Callable[..., pd.DataFrame]=None,
preferred_combiner: Callable=replace_combiner,
preferred_post_processor: Callable[..., pd.DataFrame]=None) -> Pipeline:
"""Marks a ``Callable`` as the prod... | python | def register_value_producer(self, value_name: str, source: Callable[..., pd.DataFrame]=None,
preferred_combiner: Callable=replace_combiner,
preferred_post_processor: Callable[..., pd.DataFrame]=None) -> Pipeline:
"""Marks a ``Callable`` as the prod... | Marks a ``Callable`` as the producer of a named value.
Parameters
----------
value_name :
The name of the new dynamic value pipeline.
source :
A callable source for the dynamic value pipeline.
preferred_combiner :
A strategy for combining the ... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/values.py#L183-L211 |
ihmeuw/vivarium | src/vivarium/framework/values.py | ValuesInterface.register_rate_producer | def register_rate_producer(self, rate_name: str, source: Callable[..., pd.DataFrame]=None) -> Pipeline:
"""Marks a ``Callable`` as the producer of a named rate.
This is a convenience wrapper around ``register_value_producer`` that makes sure
rate data is appropriately scaled to the size of the ... | python | def register_rate_producer(self, rate_name: str, source: Callable[..., pd.DataFrame]=None) -> Pipeline:
"""Marks a ``Callable`` as the producer of a named rate.
This is a convenience wrapper around ``register_value_producer`` that makes sure
rate data is appropriately scaled to the size of the ... | Marks a ``Callable`` as the producer of a named rate.
This is a convenience wrapper around ``register_value_producer`` that makes sure
rate data is appropriately scaled to the size of the simulation time step.
It is equivalent to ``register_value_producer(value_name, source,
preferred_c... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/values.py#L213-L233 |
ihmeuw/vivarium | src/vivarium/framework/values.py | ValuesInterface.register_value_modifier | def register_value_modifier(self, value_name: str, modifier: Callable, priority: int=5):
"""Marks a ``Callable`` as the modifier of a named value.
Parameters
----------
value_name :
The name of the dynamic value pipeline to be modified.
modifier :
A funct... | python | def register_value_modifier(self, value_name: str, modifier: Callable, priority: int=5):
"""Marks a ``Callable`` as the modifier of a named value.
Parameters
----------
value_name :
The name of the dynamic value pipeline to be modified.
modifier :
A funct... | Marks a ``Callable`` as the modifier of a named value.
Parameters
----------
value_name :
The name of the dynamic value pipeline to be modified.
modifier :
A function that modifies the source of the dynamic value pipeline when called.
If the pipeline ... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/values.py#L235-L254 |
ihmeuw/vivarium | src/vivarium/interface/cli.py | run | def run(model_specification, results_directory, verbose, log, with_debugger):
"""Run a simulation from the command line.
The simulation itself is defined by the given MODEL_SPECIFICATION yaml file.
Within the results directory, which defaults to ~/vivarium_results if none
is provided, a subdirectory w... | python | def run(model_specification, results_directory, verbose, log, with_debugger):
"""Run a simulation from the command line.
The simulation itself is defined by the given MODEL_SPECIFICATION yaml file.
Within the results directory, which defaults to ~/vivarium_results if none
is provided, a subdirectory w... | Run a simulation from the command line.
The simulation itself is defined by the given MODEL_SPECIFICATION yaml file.
Within the results directory, which defaults to ~/vivarium_results if none
is provided, a subdirectory will be created with the same name as the
MODEL_SPECIFICATION if one does not exis... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interface/cli.py#L39-L63 |
ihmeuw/vivarium | src/vivarium/interface/cli.py | profile | def profile(model_specification, results_directory, process):
"""Run a simulation based on the provided MODEL_SPECIFICATION and profile
the run.
"""
model_specification = Path(model_specification)
results_directory = Path(results_directory)
out_stats_file = results_directory / f'{model_specific... | python | def profile(model_specification, results_directory, process):
"""Run a simulation based on the provided MODEL_SPECIFICATION and profile
the run.
"""
model_specification = Path(model_specification)
results_directory = Path(results_directory)
out_stats_file = results_directory / f'{model_specific... | Run a simulation based on the provided MODEL_SPECIFICATION and profile
the run. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interface/cli.py#L98-L114 |
ihmeuw/vivarium | src/vivarium/framework/event.py | Event.split | def split(self, new_index):
"""Create a new event which is a copy of this one but with a new index.
"""
new_event = Event(new_index, self.user_data)
new_event.time = self.time
new_event.step_size = self.step_size
return new_event | python | def split(self, new_index):
"""Create a new event which is a copy of this one but with a new index.
"""
new_event = Event(new_index, self.user_data)
new_event.time = self.time
new_event.step_size = self.step_size
return new_event | Create a new event which is a copy of this one but with a new index. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/event.py#L24-L30 |
ihmeuw/vivarium | src/vivarium/framework/event.py | _EventChannel.emit | def emit(self, event):
"""Notifies all listeners to this channel that an event has occurred.
Parameters
----------
event : Event
The event to be emitted.
"""
if hasattr(event, 'time'):
event.step_size = self.manager.step_size()
event.t... | python | def emit(self, event):
"""Notifies all listeners to this channel that an event has occurred.
Parameters
----------
event : Event
The event to be emitted.
"""
if hasattr(event, 'time'):
event.step_size = self.manager.step_size()
event.t... | Notifies all listeners to this channel that an event has occurred.
Parameters
----------
event : Event
The event to be emitted. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/event.py#L45-L60 |
ihmeuw/vivarium | src/vivarium/framework/event.py | EventManager.setup | def setup(self, builder):
"""Performs this components simulation setup.
Parameters
----------
builder : vivarium.framework.engine.Builder
Object giving access to core framework functionality.
"""
self.clock = builder.time.clock()
self.step_size = buil... | python | def setup(self, builder):
"""Performs this components simulation setup.
Parameters
----------
builder : vivarium.framework.engine.Builder
Object giving access to core framework functionality.
"""
self.clock = builder.time.clock()
self.step_size = buil... | Performs this components simulation setup.
Parameters
----------
builder : vivarium.framework.engine.Builder
Object giving access to core framework functionality. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/event.py#L79-L88 |
ihmeuw/vivarium | src/vivarium/framework/event.py | EventManager.register_listener | def register_listener(self, name, listener, priority=5):
"""Registers a new listener to the named event.
Parameters
----------
name : str
The name of the event.
listener : Callable
The consumer of the named event.
priority : int
Number... | python | def register_listener(self, name, listener, priority=5):
"""Registers a new listener to the named event.
Parameters
----------
name : str
The name of the event.
listener : Callable
The consumer of the named event.
priority : int
Number... | Registers a new listener to the named event.
Parameters
----------
name : str
The name of the event.
listener : Callable
The consumer of the named event.
priority : int
Number in range(10) used to assign the ordering in which listeners process... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/event.py#L106-L118 |
ihmeuw/vivarium | src/vivarium/framework/event.py | EventInterface.get_emitter | def get_emitter(self, name: str) -> Callable[[Event], Event]:
"""Gets and emitter for a named event.
Parameters
----------
name :
The name of the event he requested emitter will emit.
Users may provide their own named events by requesting an emitter with this fun... | python | def get_emitter(self, name: str) -> Callable[[Event], Event]:
"""Gets and emitter for a named event.
Parameters
----------
name :
The name of the event he requested emitter will emit.
Users may provide their own named events by requesting an emitter with this fun... | Gets and emitter for a named event.
Parameters
----------
name :
The name of the event he requested emitter will emit.
Users may provide their own named events by requesting an emitter with this function,
but should do so with caution as it makes time much mo... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/event.py#L150-L165 |
ihmeuw/vivarium | src/vivarium/framework/event.py | EventInterface.register_listener | def register_listener(self, name: str, listener: Callable[[Event], None], priority: int=5) -> None:
"""Registers a callable as a listener to a events with the given name.
The listening callable will be called with a named ``Event`` as it's only argument any time the
event emitter is invoked fro... | python | def register_listener(self, name: str, listener: Callable[[Event], None], priority: int=5) -> None:
"""Registers a callable as a listener to a events with the given name.
The listening callable will be called with a named ``Event`` as it's only argument any time the
event emitter is invoked fro... | Registers a callable as a listener to a events with the given name.
The listening callable will be called with a named ``Event`` as it's only argument any time the
event emitter is invoked from somewhere in the simulation.
The framework creates the following events and emits them at different ... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/event.py#L167-L191 |
ihmeuw/vivarium | src/vivarium/examples/disease_model/disease.py | DiseaseState.setup | def setup(self, builder):
"""Performs this component's simulation setup.
Parameters
----------
builder : `engine.Builder`
Interface to several simulation tools.
"""
super().setup(builder)
self.clock = builder.time.clock()
self.excess_mortalit... | python | def setup(self, builder):
"""Performs this component's simulation setup.
Parameters
----------
builder : `engine.Builder`
Interface to several simulation tools.
"""
super().setup(builder)
self.clock = builder.time.clock()
self.excess_mortalit... | Performs this component's simulation setup.
Parameters
----------
builder : `engine.Builder`
Interface to several simulation tools. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/examples/disease_model/disease.py#L38-L62 |
ihmeuw/vivarium | src/vivarium/framework/population.py | PopulationView.get | def get(self, index: pd.Index, query: str='', omit_missing_columns: bool=False) -> pd.DataFrame:
"""For the rows in ``index`` get the columns from the simulation's population which this view is configured.
The result may be further filtered by the view's query.
Parameters
----------
... | python | def get(self, index: pd.Index, query: str='', omit_missing_columns: bool=False) -> pd.DataFrame:
"""For the rows in ``index`` get the columns from the simulation's population which this view is configured.
The result may be further filtered by the view's query.
Parameters
----------
... | For the rows in ``index`` get the columns from the simulation's population which this view is configured.
The result may be further filtered by the view's query.
Parameters
----------
index :
Index of the population to get.
query :
Conditions used to filt... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/population.py#L58-L97 |
ihmeuw/vivarium | src/vivarium/framework/population.py | PopulationView.update | def update(self, pop: Union[pd.DataFrame, pd.Series]):
"""Update the simulation's state to match ``pop``
Parameters
----------
pop :
The data which should be copied into the simulation's state. If ``pop`` is a DataFrame only those columns
included in the view... | python | def update(self, pop: Union[pd.DataFrame, pd.Series]):
"""Update the simulation's state to match ``pop``
Parameters
----------
pop :
The data which should be copied into the simulation's state. If ``pop`` is a DataFrame only those columns
included in the view... | Update the simulation's state to match ``pop``
Parameters
----------
pop :
The data which should be copied into the simulation's state. If ``pop`` is a DataFrame only those columns
included in the view's columns will be used. If ``pop`` is a Series it must have a nam... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/population.py#L99-L150 |
ihmeuw/vivarium | src/vivarium/framework/population.py | PopulationManager.get_view | def get_view(self, columns: Sequence[str], query: str=None) -> PopulationView:
"""Return a configured PopulationView
Notes
-----
Client code should only need this (and only through the version exposed as
``population_view`` on the builder during setup) if it uses dynamically
... | python | def get_view(self, columns: Sequence[str], query: str=None) -> PopulationView:
"""Return a configured PopulationView
Notes
-----
Client code should only need this (and only through the version exposed as
``population_view`` on the builder during setup) if it uses dynamically
... | Return a configured PopulationView
Notes
-----
Client code should only need this (and only through the version exposed as
``population_view`` on the builder during setup) if it uses dynamically
generated column names that aren't known at definition time. Otherwise
compon... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/population.py#L188-L201 |
ihmeuw/vivarium | src/vivarium/framework/population.py | PopulationInterface.get_view | def get_view(self, columns: Sequence[str], query: str = None) -> PopulationView:
"""Get a time-varying view of the population state table.
The requested population view can be used to view the current state or to update the state
with new values.
Parameters
----------
c... | python | def get_view(self, columns: Sequence[str], query: str = None) -> PopulationView:
"""Get a time-varying view of the population state table.
The requested population view can be used to view the current state or to update the state
with new values.
Parameters
----------
c... | Get a time-varying view of the population state table.
The requested population view can be used to view the current state or to update the state
with new values.
Parameters
----------
columns :
A subset of the state table columns that will be available in the retur... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/population.py#L297-L318 |
ihmeuw/vivarium | src/vivarium/framework/population.py | PopulationInterface.get_simulant_creator | def get_simulant_creator(self) -> Callable[[int, Union[Mapping[str, Any], None]], pd.Index]:
"""Grabs a reference to the function that creates new simulants (adds rows to the state table).
Returns
-------
Callable
The simulant creator function. The creator function takes the ... | python | def get_simulant_creator(self) -> Callable[[int, Union[Mapping[str, Any], None]], pd.Index]:
"""Grabs a reference to the function that creates new simulants (adds rows to the state table).
Returns
-------
Callable
The simulant creator function. The creator function takes the ... | Grabs a reference to the function that creates new simulants (adds rows to the state table).
Returns
-------
Callable
The simulant creator function. The creator function takes the number of simulants to be
created as it's first argument and a dict or other mapping of popul... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/population.py#L320-L334 |
ihmeuw/vivarium | src/vivarium/framework/population.py | PopulationInterface.initializes_simulants | def initializes_simulants(self, initializer: Callable[[SimulantData], None],
creates_columns: Sequence[str]=(),
requires_columns: Sequence[str]=()):
"""Marks a callable as a source of initial state information for new simulants.
Parameters
... | python | def initializes_simulants(self, initializer: Callable[[SimulantData], None],
creates_columns: Sequence[str]=(),
requires_columns: Sequence[str]=()):
"""Marks a callable as a source of initial state information for new simulants.
Parameters
... | Marks a callable as a source of initial state information for new simulants.
Parameters
----------
initializer :
A callable that adds or updates initial state information about new simulants.
creates_columns :
A list of the state table columns that the given init... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/population.py#L336-L351 |
datosgobar/pydatajson | pydatajson/helpers.py | title_to_name | def title_to_name(title, decode=True, max_len=None, use_complete_words=True):
"""Convierte un título en un nombre normalizado para generar urls."""
# decodifica y pasa a minúsculas
if decode:
title = unidecode(title)
title = title.lower()
# remueve caracteres no permitidos
filtered_titl... | python | def title_to_name(title, decode=True, max_len=None, use_complete_words=True):
"""Convierte un título en un nombre normalizado para generar urls."""
# decodifica y pasa a minúsculas
if decode:
title = unidecode(title)
title = title.lower()
# remueve caracteres no permitidos
filtered_titl... | Convierte un título en un nombre normalizado para generar urls. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/helpers.py#L75-L101 |
datosgobar/pydatajson | pydatajson/helpers.py | validate_url | def validate_url(uri_string):
"""Valida si un string es una URI válida."""
try:
result = urlparse(uri_string)
has_elements = all([result.scheme, result.netloc, result.path])
is_http = result.scheme == "http" or result.scheme == "https"
return True if has_elements and is_http else... | python | def validate_url(uri_string):
"""Valida si un string es una URI válida."""
try:
result = urlparse(uri_string)
has_elements = all([result.scheme, result.netloc, result.path])
is_http = result.scheme == "http" or result.scheme == "https"
return True if has_elements and is_http else... | Valida si un string es una URI válida. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/helpers.py#L137-L146 |
datosgobar/pydatajson | pydatajson/helpers.py | ensure_dir_exists | def ensure_dir_exists(directory):
"""Se asegura de que un directorio exista."""
if directory and not os.path.exists(directory):
os.makedirs(directory) | python | def ensure_dir_exists(directory):
"""Se asegura de que un directorio exista."""
if directory and not os.path.exists(directory):
os.makedirs(directory) | Se asegura de que un directorio exista. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/helpers.py#L149-L152 |
datosgobar/pydatajson | pydatajson/helpers.py | traverse_dict | def traverse_dict(dicc, keys, default_value=None):
"""Recorre un diccionario siguiendo una lista de claves, y devuelve
default_value en caso de que alguna de ellas no exista.
Args:
dicc (dict): Diccionario a ser recorrido.
keys (list): Lista de claves a ser recorrida. Puede contener
... | python | def traverse_dict(dicc, keys, default_value=None):
"""Recorre un diccionario siguiendo una lista de claves, y devuelve
default_value en caso de que alguna de ellas no exista.
Args:
dicc (dict): Diccionario a ser recorrido.
keys (list): Lista de claves a ser recorrida. Puede contener
... | Recorre un diccionario siguiendo una lista de claves, y devuelve
default_value en caso de que alguna de ellas no exista.
Args:
dicc (dict): Diccionario a ser recorrido.
keys (list): Lista de claves a ser recorrida. Puede contener
índices de listas y claves de diccionarios mezcladas.... | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/helpers.py#L155-L181 |
datosgobar/pydatajson | pydatajson/helpers.py | is_list_of_matching_dicts | def is_list_of_matching_dicts(list_of_dicts, expected_keys=None):
"""Comprueba que una lista esté compuesta únicamente por diccionarios,
que comparten exactamente las mismas claves.
Args:
list_of_dicts (list): Lista de diccionarios a comparar.
expected_keys (set): Conjunto de las claves que... | python | def is_list_of_matching_dicts(list_of_dicts, expected_keys=None):
"""Comprueba que una lista esté compuesta únicamente por diccionarios,
que comparten exactamente las mismas claves.
Args:
list_of_dicts (list): Lista de diccionarios a comparar.
expected_keys (set): Conjunto de las claves que... | Comprueba que una lista esté compuesta únicamente por diccionarios,
que comparten exactamente las mismas claves.
Args:
list_of_dicts (list): Lista de diccionarios a comparar.
expected_keys (set): Conjunto de las claves que cada diccionario debe
tener. Si no se incluye, se asume que ... | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/helpers.py#L184-L215 |
datosgobar/pydatajson | pydatajson/helpers.py | parse_value | def parse_value(cell):
"""Extrae el valor de una celda de Excel como texto."""
value = cell.value
# stripea espacios en strings
if isinstance(value, string_types):
value = value.strip()
# convierte a texto ISO 8601 las fechas
if isinstance(value, (datetime)):
value = value.isof... | python | def parse_value(cell):
"""Extrae el valor de una celda de Excel como texto."""
value = cell.value
# stripea espacios en strings
if isinstance(value, string_types):
value = value.strip()
# convierte a texto ISO 8601 las fechas
if isinstance(value, (datetime)):
value = value.isof... | Extrae el valor de una celda de Excel como texto. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/helpers.py#L218-L230 |
datosgobar/pydatajson | pydatajson/helpers.py | sheet_to_table | def sheet_to_table(worksheet):
"""Transforma una hoja de libro de Excel en una lista de diccionarios.
Args:
worksheet (Workbook.worksheet): Hoja de cálculo de un archivo XLSX
según los lee `openpyxl`
Returns:
list_of_dicts: Lista de diccionarios, con tantos elementos como
... | python | def sheet_to_table(worksheet):
"""Transforma una hoja de libro de Excel en una lista de diccionarios.
Args:
worksheet (Workbook.worksheet): Hoja de cálculo de un archivo XLSX
según los lee `openpyxl`
Returns:
list_of_dicts: Lista de diccionarios, con tantos elementos como
... | Transforma una hoja de libro de Excel en una lista de diccionarios.
Args:
worksheet (Workbook.worksheet): Hoja de cálculo de un archivo XLSX
según los lee `openpyxl`
Returns:
list_of_dicts: Lista de diccionarios, con tantos elementos como
registros incluya la hoja, y co... | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/helpers.py#L233-L277 |
datosgobar/pydatajson | pydatajson/helpers.py | string_to_list | def string_to_list(string, sep=",", filter_empty=False):
"""Transforma una string con elementos separados por `sep` en una lista."""
return [value.strip() for value in string.split(sep)
if (not filter_empty or value)] | python | def string_to_list(string, sep=",", filter_empty=False):
"""Transforma una string con elementos separados por `sep` en una lista."""
return [value.strip() for value in string.split(sep)
if (not filter_empty or value)] | Transforma una string con elementos separados por `sep` en una lista. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/helpers.py#L280-L283 |
datosgobar/pydatajson | pydatajson/helpers.py | add_dicts | def add_dicts(one_dict, other_dict):
"""Suma clave a clave los dos diccionarios. Si algún valor es un
diccionario, llama recursivamente a la función. Ambos diccionarios deben
tener exactamente las mismas claves, y los valores asociados deben ser
sumables, o diccionarios.
Args:
one_dict (dic... | python | def add_dicts(one_dict, other_dict):
"""Suma clave a clave los dos diccionarios. Si algún valor es un
diccionario, llama recursivamente a la función. Ambos diccionarios deben
tener exactamente las mismas claves, y los valores asociados deben ser
sumables, o diccionarios.
Args:
one_dict (dic... | Suma clave a clave los dos diccionarios. Si algún valor es un
diccionario, llama recursivamente a la función. Ambos diccionarios deben
tener exactamente las mismas claves, y los valores asociados deben ser
sumables, o diccionarios.
Args:
one_dict (dict)
other_dict (dict)
Returns:
... | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/helpers.py#L286-L312 |
datosgobar/pydatajson | pydatajson/helpers.py | parse_repeating_time_interval_to_days | def parse_repeating_time_interval_to_days(date_str):
"""Parsea un string con un intervalo de tiempo con repetición especificado
por la norma ISO 8601 en una cantidad de días que representa ese intervalo.
Devuelve 0 en caso de que el intervalo sea inválido.
"""
intervals = {
'Y': 365,
... | python | def parse_repeating_time_interval_to_days(date_str):
"""Parsea un string con un intervalo de tiempo con repetición especificado
por la norma ISO 8601 en una cantidad de días que representa ese intervalo.
Devuelve 0 en caso de que el intervalo sea inválido.
"""
intervals = {
'Y': 365,
... | Parsea un string con un intervalo de tiempo con repetición especificado
por la norma ISO 8601 en una cantidad de días que representa ese intervalo.
Devuelve 0 en caso de que el intervalo sea inválido. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/helpers.py#L328-L361 |
datosgobar/pydatajson | pydatajson/helpers.py | parse_repeating_time_interval_to_str | def parse_repeating_time_interval_to_str(date_str):
"""Devuelve descripción humana de un intervalo de repetición.
TODO: Por ahora sólo interpreta una lista fija de intervalos. Debería poder
parsear cualquier caso.
"""
with open(os.path.join(ABSOLUTE_SCHEMA_DIR,
"accrualP... | python | def parse_repeating_time_interval_to_str(date_str):
"""Devuelve descripción humana de un intervalo de repetición.
TODO: Por ahora sólo interpreta una lista fija de intervalos. Debería poder
parsear cualquier caso.
"""
with open(os.path.join(ABSOLUTE_SCHEMA_DIR,
"accrualP... | Devuelve descripción humana de un intervalo de repetición.
TODO: Por ahora sólo interpreta una lista fija de intervalos. Debería poder
parsear cualquier caso. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/helpers.py#L364-L376 |
datosgobar/pydatajson | pydatajson/helpers.py | find_ws_name | def find_ws_name(wb, name):
"""Busca una hoja en un workbook sin importar mayúsculas/minúsculas."""
if isinstance(wb, string_types):
# FIXME: importar o borrar segun corresponda
wb = load_workbook(wb, read_only=True, data_only=True)
for sheetname in wb.sheetnames:
if sheetname.lower... | python | def find_ws_name(wb, name):
"""Busca una hoja en un workbook sin importar mayúsculas/minúsculas."""
if isinstance(wb, string_types):
# FIXME: importar o borrar segun corresponda
wb = load_workbook(wb, read_only=True, data_only=True)
for sheetname in wb.sheetnames:
if sheetname.lower... | Busca una hoja en un workbook sin importar mayúsculas/minúsculas. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/helpers.py#L384-L394 |
datosgobar/pydatajson | pydatajson/helpers.py | datasets_equal | def datasets_equal(dataset, other, fields_dataset=None,
fields_distribution=None, return_diff=False):
"""Función de igualdad de dos datasets: se consideran iguales si
los valores de los campos 'title', 'publisher.name',
'accrualPeriodicity' e 'issued' son iguales en ambos.
Args:
... | python | def datasets_equal(dataset, other, fields_dataset=None,
fields_distribution=None, return_diff=False):
"""Función de igualdad de dos datasets: se consideran iguales si
los valores de los campos 'title', 'publisher.name',
'accrualPeriodicity' e 'issued' son iguales en ambos.
Args:
... | Función de igualdad de dos datasets: se consideran iguales si
los valores de los campos 'title', 'publisher.name',
'accrualPeriodicity' e 'issued' son iguales en ambos.
Args:
dataset (dict): un dataset, generado por la lectura de un catálogo
other (dict): idem anterior
Returns:
... | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/helpers.py#L446-L525 |
datosgobar/pydatajson | pydatajson/transformation.py | generate_distribution_ids | def generate_distribution_ids(catalog):
"""Genera identificadores para las distribuciones que no los tienen.
Los identificadores de distribuciones se generan concatenando el id del
dataset al que pertenecen con el índice posicional de la distribución en el
dataset: distribution_identifier = "{dataset_i... | python | def generate_distribution_ids(catalog):
"""Genera identificadores para las distribuciones que no los tienen.
Los identificadores de distribuciones se generan concatenando el id del
dataset al que pertenecen con el índice posicional de la distribución en el
dataset: distribution_identifier = "{dataset_i... | Genera identificadores para las distribuciones que no los tienen.
Los identificadores de distribuciones se generan concatenando el id del
dataset al que pertenecen con el índice posicional de la distribución en el
dataset: distribution_identifier = "{dataset_identifier}_{index}". | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/transformation.py#L12-L25 |
datosgobar/pydatajson | pydatajson/ckan_utils.py | _get_theme_label | def _get_theme_label(catalog, theme):
"""Intenta conseguir el theme por id o por label."""
try:
label = catalog.get_theme(identifier=theme)['label']
except BaseException:
try:
label = catalog.get_theme(label=theme)['label']
except BaseException:
raise ce.Theme... | python | def _get_theme_label(catalog, theme):
"""Intenta conseguir el theme por id o por label."""
try:
label = catalog.get_theme(identifier=theme)['label']
except BaseException:
try:
label = catalog.get_theme(label=theme)['label']
except BaseException:
raise ce.Theme... | Intenta conseguir el theme por id o por label. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/ckan_utils.py#L102-L114 |
datosgobar/pydatajson | pydatajson/backup.py | make_catalogs_backup | def make_catalogs_backup(catalogs, local_catalogs_dir="",
include_metadata=True, include_data=True,
include_metadata_xlsx=False, use_short_path=False):
"""Realiza una copia local de los datos y metadatos de un catálogo.
Args:
catalogs (list or dict): Li... | python | def make_catalogs_backup(catalogs, local_catalogs_dir="",
include_metadata=True, include_data=True,
include_metadata_xlsx=False, use_short_path=False):
"""Realiza una copia local de los datos y metadatos de un catálogo.
Args:
catalogs (list or dict): Li... | Realiza una copia local de los datos y metadatos de un catálogo.
Args:
catalogs (list or dict): Lista de catálogos (elementos que pueden
ser interpretados por DataJson como catálogos) o diccionario
donde las keys se interpretan como los catalog_identifier:
{
... | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/backup.py#L22-L77 |
datosgobar/pydatajson | pydatajson/backup.py | make_catalog_backup | def make_catalog_backup(catalog, catalog_id=None, local_catalogs_dir="",
include_metadata=True, include_data=True,
include_datasets=None,
include_distribution_formats=['CSV', 'XLS'],
include_metadata_xlsx=True, use_short_pat... | python | def make_catalog_backup(catalog, catalog_id=None, local_catalogs_dir="",
include_metadata=True, include_data=True,
include_datasets=None,
include_distribution_formats=['CSV', 'XLS'],
include_metadata_xlsx=True, use_short_pat... | Realiza una copia local de los datos y metadatos de un catálogo.
Args:
catalog (dict or str): Representación externa/interna de un catálogo.
Una representación _externa_ es un path local o una URL remota a un
archivo con la metadata de un catálogo, en formato JSON o XLSX. La
... | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/backup.py#L80-L176 |
datosgobar/pydatajson | pydatajson/backup.py | get_distribution_dir | def get_distribution_dir(catalog_id, dataset_id, distribution_id,
catalogs_dir=CATALOGS_DIR, use_short_path=False):
"""Genera el path estándar de un catálogo en un filesystem."""
if use_short_path:
catalog_path = os.path.join(catalogs_dir, "catalog", catalog_id)
distribu... | python | def get_distribution_dir(catalog_id, dataset_id, distribution_id,
catalogs_dir=CATALOGS_DIR, use_short_path=False):
"""Genera el path estándar de un catálogo en un filesystem."""
if use_short_path:
catalog_path = os.path.join(catalogs_dir, "catalog", catalog_id)
distribu... | Genera el path estándar de un catálogo en un filesystem. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/backup.py#L179-L191 |
datosgobar/pydatajson | pydatajson/backup.py | get_distribution_path | def get_distribution_path(catalog_id, dataset_id, distribution_id,
distribution_file_name, catalogs_dir=CATALOGS_DIR,
use_short_path=False):
"""Genera el path estándar de un catálogo en un filesystem."""
if use_short_path:
distribution_dir = get_distri... | python | def get_distribution_path(catalog_id, dataset_id, distribution_id,
distribution_file_name, catalogs_dir=CATALOGS_DIR,
use_short_path=False):
"""Genera el path estándar de un catálogo en un filesystem."""
if use_short_path:
distribution_dir = get_distri... | Genera el path estándar de un catálogo en un filesystem. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/backup.py#L194-L211 |
datosgobar/pydatajson | pydatajson/backup.py | get_catalog_path | def get_catalog_path(catalog_id, catalogs_dir=CATALOGS_DIR, fmt="json"):
"""Genera el path estándar de un catálogo en un filesystem."""
base_path = os.path.join(catalogs_dir, "catalog", catalog_id)
if fmt == "json":
return os.path.join(base_path, "data.json")
elif fmt == "xlsx":
return ... | python | def get_catalog_path(catalog_id, catalogs_dir=CATALOGS_DIR, fmt="json"):
"""Genera el path estándar de un catálogo en un filesystem."""
base_path = os.path.join(catalogs_dir, "catalog", catalog_id)
if fmt == "json":
return os.path.join(base_path, "data.json")
elif fmt == "xlsx":
return ... | Genera el path estándar de un catálogo en un filesystem. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/backup.py#L214-L224 |
datosgobar/pydatajson | pydatajson/backup.py | main | def main(catalogs, include_data=True, use_short_path=True):
"""Permite hacer backups de uno o más catálogos por línea de comandos.
Args:
catalogs (str): Lista de catálogos separados por coma (URLs o paths
locales) para hacer backups.
"""
include_data = bool(int(include_data))
ma... | python | def main(catalogs, include_data=True, use_short_path=True):
"""Permite hacer backups de uno o más catálogos por línea de comandos.
Args:
catalogs (str): Lista de catálogos separados por coma (URLs o paths
locales) para hacer backups.
"""
include_data = bool(int(include_data))
ma... | Permite hacer backups de uno o más catálogos por línea de comandos.
Args:
catalogs (str): Lista de catálogos separados por coma (URLs o paths
locales) para hacer backups. | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/backup.py#L227-L236 |
datosgobar/pydatajson | pydatajson/catalog_readme.py | generate_readme | def generate_readme(catalog, export_path=None):
"""Genera una descripción textual en formato Markdown sobre los
metadatos generales de un catálogo (título, editor, fecha de
publicación, et cetera), junto con:
- estado de los metadatos a nivel catálogo,
- estado global de los metadatos,
... | python | def generate_readme(catalog, export_path=None):
"""Genera una descripción textual en formato Markdown sobre los
metadatos generales de un catálogo (título, editor, fecha de
publicación, et cetera), junto con:
- estado de los metadatos a nivel catálogo,
- estado global de los metadatos,
... | Genera una descripción textual en formato Markdown sobre los
metadatos generales de un catálogo (título, editor, fecha de
publicación, et cetera), junto con:
- estado de los metadatos a nivel catálogo,
- estado global de los metadatos,
- cantidad de datasets federados y no federados,
... | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/catalog_readme.py#L32-L113 |
ihmeuw/vivarium | src/vivarium/examples/disease_model/population.py | BasePopulation.setup | def setup(self, builder: Builder):
"""Performs this component's simulation setup.
The ``setup`` method is automatically called by the simulation
framework. The framework passes in a ``builder`` object which
provides access to a variety of framework subsystems and metadata.
Para... | python | def setup(self, builder: Builder):
"""Performs this component's simulation setup.
The ``setup`` method is automatically called by the simulation
framework. The framework passes in a ``builder`` object which
provides access to a variety of framework subsystems and metadata.
Para... | Performs this component's simulation setup.
The ``setup`` method is automatically called by the simulation
framework. The framework passes in a ``builder`` object which
provides access to a variety of framework subsystems and metadata.
Parameters
----------
builder :
... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/examples/disease_model/population.py#L28-L59 |
ihmeuw/vivarium | src/vivarium/examples/disease_model/population.py | BasePopulation.on_initialize_simulants | def on_initialize_simulants(self, pop_data: SimulantData):
"""Called by the simulation whenever new simulants are added.
This component is responsible for creating and filling four columns
in the population state table:
'age' :
The age of the simulant in fractional years.
... | python | def on_initialize_simulants(self, pop_data: SimulantData):
"""Called by the simulation whenever new simulants are added.
This component is responsible for creating and filling four columns
in the population state table:
'age' :
The age of the simulant in fractional years.
... | Called by the simulation whenever new simulants are added.
This component is responsible for creating and filling four columns
in the population state table:
'age' :
The age of the simulant in fractional years.
'sex' :
The sex of the simulant. One of {'Male', 'F... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/examples/disease_model/population.py#L61-L111 |
ihmeuw/vivarium | src/vivarium/examples/disease_model/population.py | BasePopulation.age_simulants | def age_simulants(self, event: Event):
"""Updates simulant age on every time step.
Parameters
----------
event :
An event object emitted by the simulation containing an index
representing the simulants affected by the event and timing
information.
... | python | def age_simulants(self, event: Event):
"""Updates simulant age on every time step.
Parameters
----------
event :
An event object emitted by the simulation containing an index
representing the simulants affected by the event and timing
information.
... | Updates simulant age on every time step.
Parameters
----------
event :
An event object emitted by the simulation containing an index
representing the simulants affected by the event and timing
information. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/examples/disease_model/population.py#L113-L125 |
datosgobar/pydatajson | pydatajson/indicators.py | generate_catalogs_indicators | def generate_catalogs_indicators(catalogs, central_catalog=None,
identifier_search=False,
validator=None):
"""Genera una lista de diccionarios con varios indicadores sobre
los catálogos provistos, tales como la cantidad de datasets válidos,
d... | python | def generate_catalogs_indicators(catalogs, central_catalog=None,
identifier_search=False,
validator=None):
"""Genera una lista de diccionarios con varios indicadores sobre
los catálogos provistos, tales como la cantidad de datasets válidos,
d... | Genera una lista de diccionarios con varios indicadores sobre
los catálogos provistos, tales como la cantidad de datasets válidos,
días desde su última fecha actualizada, entre otros.
Args:
catalogs (str o list): uno o más catalogos sobre los que se quiera
obtener indicadores
ce... | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/indicators.py#L45-L110 |
datosgobar/pydatajson | pydatajson/indicators.py | _generate_indicators | def _generate_indicators(catalog, validator=None, only_numeric=False):
"""Genera los indicadores de un catálogo individual.
Args:
catalog (dict): diccionario de un data.json parseado
Returns:
dict: diccionario con los indicadores del catálogo provisto
"""
result = {}
# Obteng... | python | def _generate_indicators(catalog, validator=None, only_numeric=False):
"""Genera los indicadores de un catálogo individual.
Args:
catalog (dict): diccionario de un data.json parseado
Returns:
dict: diccionario con los indicadores del catálogo provisto
"""
result = {}
# Obteng... | Genera los indicadores de un catálogo individual.
Args:
catalog (dict): diccionario de un data.json parseado
Returns:
dict: diccionario con los indicadores del catálogo provisto | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/indicators.py#L113-L157 |
datosgobar/pydatajson | pydatajson/indicators.py | _federation_indicators | def _federation_indicators(catalog, central_catalog,
identifier_search=False):
"""Cuenta la cantidad de datasets incluídos tanto en la lista
'catalogs' como en el catálogo central, y genera indicadores a partir
de esa información.
Args:
catalog (dict): catálogo ya par... | python | def _federation_indicators(catalog, central_catalog,
identifier_search=False):
"""Cuenta la cantidad de datasets incluídos tanto en la lista
'catalogs' como en el catálogo central, y genera indicadores a partir
de esa información.
Args:
catalog (dict): catálogo ya par... | Cuenta la cantidad de datasets incluídos tanto en la lista
'catalogs' como en el catálogo central, y genera indicadores a partir
de esa información.
Args:
catalog (dict): catálogo ya parseado
central_catalog (str o dict): ruta a catálogo central, o un dict
con el catálogo ya par... | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/indicators.py#L160-L209 |
datosgobar/pydatajson | pydatajson/indicators.py | _network_indicator_percentages | def _network_indicator_percentages(fields, network_indicators):
"""Encapsula el cálculo de indicadores de porcentaje (de errores,
de campos recomendados/optativos utilizados, de datasets actualizados)
sobre la red de nodos entera.
Args:
fields (dict): Diccionario con claves 'recomendado', 'opta... | python | def _network_indicator_percentages(fields, network_indicators):
"""Encapsula el cálculo de indicadores de porcentaje (de errores,
de campos recomendados/optativos utilizados, de datasets actualizados)
sobre la red de nodos entera.
Args:
fields (dict): Diccionario con claves 'recomendado', 'opta... | Encapsula el cálculo de indicadores de porcentaje (de errores,
de campos recomendados/optativos utilizados, de datasets actualizados)
sobre la red de nodos entera.
Args:
fields (dict): Diccionario con claves 'recomendado', 'optativo',
'total_recomendado', 'total_optativo', cada uno con ... | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/indicators.py#L212-L263 |
datosgobar/pydatajson | pydatajson/indicators.py | _generate_status_indicators | def _generate_status_indicators(catalog, validator=None):
"""Genera indicadores básicos sobre el estado de un catálogo
Args:
catalog (dict): diccionario de un data.json parseado
Returns:
dict: indicadores básicos sobre el catálogo, tal como la cantidad
de datasets, distribuciones y... | python | def _generate_status_indicators(catalog, validator=None):
"""Genera indicadores básicos sobre el estado de un catálogo
Args:
catalog (dict): diccionario de un data.json parseado
Returns:
dict: indicadores básicos sobre el catálogo, tal como la cantidad
de datasets, distribuciones y... | Genera indicadores básicos sobre el estado de un catálogo
Args:
catalog (dict): diccionario de un data.json parseado
Returns:
dict: indicadores básicos sobre el catálogo, tal como la cantidad
de datasets, distribuciones y número de errores | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/indicators.py#L266-L332 |
datosgobar/pydatajson | pydatajson/indicators.py | _generate_date_indicators | def _generate_date_indicators(catalog, tolerance=0.2, only_numeric=False):
"""Genera indicadores relacionados a las fechas de publicación
y actualización del catálogo pasado por parámetro. La evaluación de si
un catálogo se encuentra actualizado o no tiene un porcentaje de
tolerancia hasta que se lo con... | python | def _generate_date_indicators(catalog, tolerance=0.2, only_numeric=False):
"""Genera indicadores relacionados a las fechas de publicación
y actualización del catálogo pasado por parámetro. La evaluación de si
un catálogo se encuentra actualizado o no tiene un porcentaje de
tolerancia hasta que se lo con... | Genera indicadores relacionados a las fechas de publicación
y actualización del catálogo pasado por parámetro. La evaluación de si
un catálogo se encuentra actualizado o no tiene un porcentaje de
tolerancia hasta que se lo considere como tal, dado por el parámetro
tolerance.
Args:
catalog (... | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/indicators.py#L335-L441 |
datosgobar/pydatajson | pydatajson/indicators.py | _days_from_last_update | def _days_from_last_update(catalog, date_field="modified"):
"""Calcula días desde la última actualización del catálogo.
Args:
catalog (dict): Un catálogo.
date_field (str): Campo de metadatos a utilizar para considerar
los días desde la última actualización del catálogo.
Return... | python | def _days_from_last_update(catalog, date_field="modified"):
"""Calcula días desde la última actualización del catálogo.
Args:
catalog (dict): Un catálogo.
date_field (str): Campo de metadatos a utilizar para considerar
los días desde la última actualización del catálogo.
Return... | Calcula días desde la última actualización del catálogo.
Args:
catalog (dict): Un catálogo.
date_field (str): Campo de metadatos a utilizar para considerar
los días desde la última actualización del catálogo.
Returns:
int or None: Cantidad de días desde la última actualizac... | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/indicators.py#L444-L480 |
datosgobar/pydatajson | pydatajson/indicators.py | _count_required_and_optional_fields | def _count_required_and_optional_fields(catalog):
"""Cuenta los campos obligatorios/recomendados/requeridos usados en
'catalog', junto con la cantidad máxima de dichos campos.
Args:
catalog (str o dict): path a un catálogo, o un dict de python que
contenga a un catálogo ya leído
Re... | python | def _count_required_and_optional_fields(catalog):
"""Cuenta los campos obligatorios/recomendados/requeridos usados en
'catalog', junto con la cantidad máxima de dichos campos.
Args:
catalog (str o dict): path a un catálogo, o un dict de python que
contenga a un catálogo ya leído
Re... | Cuenta los campos obligatorios/recomendados/requeridos usados en
'catalog', junto con la cantidad máxima de dichos campos.
Args:
catalog (str o dict): path a un catálogo, o un dict de python que
contenga a un catálogo ya leído
Returns:
dict: diccionario con las claves 'recomend... | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/indicators.py#L483-L506 |
datosgobar/pydatajson | pydatajson/indicators.py | _count_fields_recursive | def _count_fields_recursive(dataset, fields):
"""Cuenta la información de campos optativos/recomendados/requeridos
desde 'fields', y cuenta la ocurrencia de los mismos en 'dataset'.
Args:
dataset (dict): diccionario con claves a ser verificadas.
fields (dict): diccionario con los campos a v... | python | def _count_fields_recursive(dataset, fields):
"""Cuenta la información de campos optativos/recomendados/requeridos
desde 'fields', y cuenta la ocurrencia de los mismos en 'dataset'.
Args:
dataset (dict): diccionario con claves a ser verificadas.
fields (dict): diccionario con los campos a v... | Cuenta la información de campos optativos/recomendados/requeridos
desde 'fields', y cuenta la ocurrencia de los mismos en 'dataset'.
Args:
dataset (dict): diccionario con claves a ser verificadas.
fields (dict): diccionario con los campos a verificar en dataset
como claves, y 'optat... | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/indicators.py#L509-L562 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | random | def random(key: str, index: Index, index_map: IndexMap=None) -> pd.Series:
"""Produces an indexed `pandas.Series` of uniformly distributed random numbers.
The index passed in typically corresponds to a subset of rows in a
`pandas.DataFrame` for which a probabilistic draw needs to be made.
Parameters
... | python | def random(key: str, index: Index, index_map: IndexMap=None) -> pd.Series:
"""Produces an indexed `pandas.Series` of uniformly distributed random numbers.
The index passed in typically corresponds to a subset of rows in a
`pandas.DataFrame` for which a probabilistic draw needs to be made.
Parameters
... | Produces an indexed `pandas.Series` of uniformly distributed random numbers.
The index passed in typically corresponds to a subset of rows in a
`pandas.DataFrame` for which a probabilistic draw needs to be made.
Parameters
----------
key :
A string used to create a seed for the random numb... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L185-L226 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | get_hash | def get_hash(key: str) -> int:
"""Gets a hash of the provided key.
Parameters
----------
key :
A string used to create a seed for the random number generator.
Returns
-------
int
A hash of the provided key.
"""
# 4294967295 == 2**32 - 1 which is the maximum allowabl... | python | def get_hash(key: str) -> int:
"""Gets a hash of the provided key.
Parameters
----------
key :
A string used to create a seed for the random number generator.
Returns
-------
int
A hash of the provided key.
"""
# 4294967295 == 2**32 - 1 which is the maximum allowabl... | Gets a hash of the provided key.
Parameters
----------
key :
A string used to create a seed for the random number generator.
Returns
-------
int
A hash of the provided key. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L229-L243 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | choice | def choice(key: str, index: Index, choices: Array, p: Array=None, index_map: IndexMap=None) -> pd.Series:
"""Decides between a weighted or unweighted set of choices.
Given a a set of choices with or without corresponding weights,
returns an indexed set of decisions from those choices. This is
simply a ... | python | def choice(key: str, index: Index, choices: Array, p: Array=None, index_map: IndexMap=None) -> pd.Series:
"""Decides between a weighted or unweighted set of choices.
Given a a set of choices with or without corresponding weights,
returns an indexed set of decisions from those choices. This is
simply a ... | Decides between a weighted or unweighted set of choices.
Given a a set of choices with or without corresponding weights,
returns an indexed set of decisions from those choices. This is
simply a vectorized way to make decisions with some book-keeping.
Parameters
----------
key :
A strin... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L246-L296 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | _set_residual_probability | def _set_residual_probability(p: np.ndarray) -> np.ndarray:
"""Turns any use of `RESIDUAL_CHOICE` into a residual probability.
Parameters
----------
p :
Array where each row is a set of probability weights and potentially
a `RESIDUAL_CHOICE` placeholder.
Returns
-------
np.... | python | def _set_residual_probability(p: np.ndarray) -> np.ndarray:
"""Turns any use of `RESIDUAL_CHOICE` into a residual probability.
Parameters
----------
p :
Array where each row is a set of probability weights and potentially
a `RESIDUAL_CHOICE` placeholder.
Returns
-------
np.... | Turns any use of `RESIDUAL_CHOICE` into a residual probability.
Parameters
----------
p :
Array where each row is a set of probability weights and potentially
a `RESIDUAL_CHOICE` placeholder.
Returns
-------
np.ndarray
Array where each row is a set of normalized probabi... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L308-L336 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | filter_for_probability | def filter_for_probability(key: str, population: Union[pd.DataFrame, pd.Series, Index],
probability: Array, index_map: IndexMap=None) -> Union[pd.DataFrame, pd.Series, Index]:
"""Decide an event outcome for each individual in a population from probabilities.
Given a population or its... | python | def filter_for_probability(key: str, population: Union[pd.DataFrame, pd.Series, Index],
probability: Array, index_map: IndexMap=None) -> Union[pd.DataFrame, pd.Series, Index]:
"""Decide an event outcome for each individual in a population from probabilities.
Given a population or its... | Decide an event outcome for each individual in a population from probabilities.
Given a population or its index and an array of associated probabilities
for some event to happen, we create and return the sub-population for whom
the event occurred.
Parameters
----------
key :
A string u... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L339-L375 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | IndexMap.update | def update(self, new_keys: Index):
"""Adds the new keys to the mapping.
Parameters
----------
new_keys :
The new index to hash.
"""
if not self._map.index.intersection(new_keys).empty:
raise KeyError("Non-unique keys in index.")
mapping_u... | python | def update(self, new_keys: Index):
"""Adds the new keys to the mapping.
Parameters
----------
new_keys :
The new index to hash.
"""
if not self._map.index.intersection(new_keys).empty:
raise KeyError("Non-unique keys in index.")
mapping_u... | Adds the new keys to the mapping.
Parameters
----------
new_keys :
The new index to hash. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L59-L82 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | IndexMap.hash_ | def hash_(self, keys: Index, salt: int = 0) -> pd.Series:
"""Hashes the given index into an integer index in the range [0, self.stride]
Parameters
----------
keys :
The new index to hash.
salt :
An integer used to perturb the hash in a deterministic way. ... | python | def hash_(self, keys: Index, salt: int = 0) -> pd.Series:
"""Hashes the given index into an integer index in the range [0, self.stride]
Parameters
----------
keys :
The new index to hash.
salt :
An integer used to perturb the hash in a deterministic way. ... | Hashes the given index into an integer index in the range [0, self.stride]
Parameters
----------
keys :
The new index to hash.
salt :
An integer used to perturb the hash in a deterministic way. Useful
in dealing with collisions.
Returns
... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L84-L118 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | IndexMap.convert_to_ten_digit_int | def convert_to_ten_digit_int(self, column: pd.Series) -> pd.Series:
"""Converts a column of datetimes, integers, or floats into a column of 10 digit integers.
Parameters
----------
column :
A series of datetimes, integers, or floats.
Returns
-------
... | python | def convert_to_ten_digit_int(self, column: pd.Series) -> pd.Series:
"""Converts a column of datetimes, integers, or floats into a column of 10 digit integers.
Parameters
----------
column :
A series of datetimes, integers, or floats.
Returns
-------
... | Converts a column of datetimes, integers, or floats into a column of 10 digit integers.
Parameters
----------
column :
A series of datetimes, integers, or floats.
Returns
-------
pd.Series
A series of ten digit integers based on the input data.
... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L120-L149 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | IndexMap.digit | def digit(m: Union[int, pd.Series], n: int) -> Union[int, pd.Series]:
"""Returns the nth digit of each number in m."""
return (m // (10 ** n)) % 10 | python | def digit(m: Union[int, pd.Series], n: int) -> Union[int, pd.Series]:
"""Returns the nth digit of each number in m."""
return (m // (10 ** n)) % 10 | Returns the nth digit of each number in m. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L152-L154 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.