Skip to content

demographics_base

DemographicsBase

Bases: BaseInputFile

Base class for :py:obj:emod_api:emod_api.demographics.Demographics and :py:obj:emod_api:emod_api.demographics.DemographicsOverlay.

Source code in emod_api/demographics/demographics_base.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
class DemographicsBase(BaseInputFile):
    """
    Base class for :py:obj:`emod_api:emod_api.demographics.Demographics` and
        :py:obj:`emod_api:emod_api.demographics.DemographicsOverlay`.
    """

    DEFAULT_NODE_NAME = 'default_node'

    class UnknownNodeException(ValueError):
        pass

    class DuplicateNodeIdException(Exception):
        pass

    class DuplicateNodeNameException(Exception):
        pass

    def __init__(self, nodes: list[Node], idref: str = None, default_node: Node = None):
        """
        Passed-in default nodes are optional. If one is not passed in, one will be created.
        """
        super().__init__(idref=idref)
        self.nodes = nodes
        self.implicits = list()
        self.migration_files = list()

        # verify that the provided non-default nodes have ids > 0
        for node in self.nodes:
            if node.id <= 0:
                raise InvalidNodeIdException(f"Non-default nodes must have integer ids > 0 . Found id: {node.id}")

        # Build the default node if not provided and then perform some setup/verification
        default_node = self._generate_default_node() if default_node is None else default_node
        self.default_node = default_node
        self.default_node.name = self.DEFAULT_NODE_NAME
        if self.default_node.id != 0:
            raise InvalidNodeIdException(f"Default nodes must have an id of 0. It is {self.default_node.id} .")
        self.metadata = self.generate_headers()
        # TODO: remove the following setting of birth_rate on the default node once this EMOD binary issue is fixed
        #  https://github.com/InstituteforDiseaseModeling/DtkTrunk/issues/4009
        if self.default_node.birth_rate is None:
            self.default_node.birth_rate = 0

        # enforce unique node ids and names
        self.verify_demographics_integrity()

    def _generate_default_node(self) -> Node:
        default_node = Node(lat=0, lon=0, pop=0, name=self.DEFAULT_NODE_NAME, forced_id=0)
        # TODO: remove the following setting of birth_rate on the default node once this EMOD binary issue is fixed
        #  https://github.com/InstituteforDiseaseModeling/DtkTrunk/issues/4009
        default_node.birth_rate = 0
        return default_node

    def apply_overlay(self, overlay_nodes: list[Node]) -> None:
        """
        Overlays a set of nodes onto the demographics object. Only overlay nodes with ids matching current demographic
        node_ids will be overlayed (extending/overriding exisiting node data).

        Args:
            overlay_nodes (list[Node]): a list of Node objects that will overlay/override data in the demographics
                object.

        Returns:
            Nothing
        """
        existing_nodes_by_id = self._all_nodes_by_id
        for overlay_node in overlay_nodes:
            if overlay_node.id in existing_nodes_by_id:
                self.get_node_by_id(node_id=overlay_node.id).update(overlay_node)

    @property
    def node_ids(self):
        """
        Return the list of (geographic) node ids.
        """
        return [node.id for node in self.nodes]

    @property
    def node_count(self):
        """
        Return the number of (geographic) nodes.
        """
        message = "node_count is a deprecated property of Node objects, use len(demog.nodes) instead."
        warnings.warn(message=message, category=DeprecationWarning, stacklevel=2)
        return len(self.nodes)

    def get_node(self, nodeid: int) -> Node:
        """
        Return the node with node.id equal to nodeid.

        Args:
            nodeid: an id to use in retrieving the requested Node object. None or 0 for 'the default node'.

        Returns:
            a Node object
        """
        message = "get_node() is a deprecated function of Node objects, use get_node_by_id() instead. " \
                  "(For example, demographics.get_node_by_id(node_id=4))"
        warnings.warn(message=message, category=DeprecationWarning, stacklevel=2)
        return self.get_node_by_id(node_id=nodeid)

    def verify_demographics_integrity(self):
        """
        One stop shopping for making sure a demographics object doesn't have known invalid settings.
        """
        self._verify_node_id_uniqueness()
        self._verify_node_name_uniqueness()

    @staticmethod
    def _duplicates_check(items: Iterable) -> list:
        """
        Simple function that detects and returns the duplicates in an provide iterable.
        Args:
            items: a collection of items to search for duplicates

        Returns: a list of duplicated items from the provided list
        """
        usage_count = Counter(items)
        return [item for item in usage_count.keys() if usage_count[item] > 1]

    def _verify_node_id_uniqueness(self):
        nodes = self._all_nodes
        node_ids = [node.id for node in nodes]
        duplicate_items = self._duplicates_check(items=node_ids)
        if len(duplicate_items) > 0:
            duplicate_items_str = [str(item) for item in duplicate_items]
            duplicates_str = ", ".join(duplicate_items_str)
            raise self.DuplicateNodeIdException(f"Duplicate node ids detected: {duplicates_str}")

    def _verify_node_name_uniqueness(self):
        nodes = self._all_nodes
        node_names = [node.name for node in nodes]
        duplicate_items = self._duplicates_check(items=node_names)
        if len(duplicate_items) > 0:
            duplicate_items_str = [str(item) for item in duplicate_items]
            duplicates_str = ", ".join(duplicate_items_str)
            raise self.DuplicateNodeNameException(f"Duplicate node names detected: {duplicates_str}")

    @property
    def _all_nodes(self) -> list[Node]:
        all_nodes = self.nodes + [self.default_node]
        return all_nodes

    @property
    def _all_node_names(self) -> list[int]:
        return [node.name for node in self._all_nodes]

    @property
    def _all_nodes_by_name(self) -> dict[int, Node]:
        return {node.name: node for node in self._all_nodes}

    @property
    def _all_node_ids(self) -> list[int]:
        return [node.id for node in self._all_nodes]

    @property
    def _all_nodes_by_id(self) -> dict[int, Node]:
        return {node.id: node for node in self._all_nodes}

    def get_node_by_id(self, node_id: int) -> Node:
        """
        Returns the Node object requested by its node id.

        Args:
            node_id: a node_id to use in retrieving the requested Node object. None or 0 for 'the default node'.

        Returns:
            a Node object
        """
        return list(self.get_nodes_by_id(node_ids=[node_id]).values())[0]

    def get_nodes_by_id(self, node_ids: list[int]) -> dict[int, Node]:
        """
        Returns the Node objects requested by their node id.

        Args:
            node_ids: a list of node ids to use in retrieving Node objects. None or 0 for 'the default node'.

        Returns:
            a dict with id: node entries
        """
        # replace a None id (default node) request with 0
        if node_ids is None:
            node_ids = [0]
        if None in node_ids:
            node_ids.remove(None)
            node_ids.append(0)

        missing_node_ids = [node_id for node_id in node_ids if node_id not in self._all_node_ids]
        if len(missing_node_ids) > 0:
            msg = ', '.join([str(node_id) for node_id in missing_node_ids])
            raise self.UnknownNodeException(f"The following node id(s) were requested but do not exist in this demographics "
                                            f"object:\n{msg}")
        requested_nodes = {node_id: node for node_id, node in self._all_nodes_by_id.items() if node_id in node_ids}
        return requested_nodes

    def get_node_by_name(self, node_name: str) -> Node:
        """
        Returns the Node object requested by its node name.

        Args:
            node_name: a node_name to use in retrieving the requested Node object. None for 'the default node'.

        Returns:
            a Node object
        """
        return list(self.get_nodes_by_name(node_names=[node_name]).values())[0]

    def get_nodes_by_name(self, node_names: list[str]) -> dict[str, Node]:
        """
        Returns the Node objects requested by their node name.

        Args:
            node_names: a list of node names to use in retrieving Node objects. None for 'the default node'.

        Returns:
            a dict with name: node entries
        """
        # replace a None name (default node) request with the default node's name
        if node_names is None:
            node_names = [self.default_node.name]
        if None in node_names:
            node_names.remove(None)
            node_names.append(self.default_node.name)

        missing_node_names = [node_name for node_name in node_names if node_name not in self._all_node_names]
        if len(missing_node_names) > 0:
            msg = ', '.join([str(node_name) for node_name in missing_node_names])
            raise self.UnknownNodeException(f"The following node name(s) were requested but do not exist in this demographics "
                                            f"object:\n{msg}")
        requested_nodes = {node_name: node for node_name, node in self._all_nodes_by_name.items()
                           if node_name in node_names}
        return requested_nodes

    def set_demographics_filenames(self, filenames: list[str]):
        """
        Set paths to demographic file.

        Args:
            filenames: Paths to demographic files.
        """
        from emod_api.demographics.implicit_functions import _set_demographic_filenames

        self.implicits.append(partial(_set_demographic_filenames, filenames=filenames))

    def to_dict(self) -> dict:
        self.verify_demographics_integrity()
        demographics_dict = {
            'Defaults': self.default_node.to_dict(),
            'Nodes': [node.to_dict() for node in self.nodes],
            'Metadata': self.metadata
        }
        demographics_dict["Metadata"]["NodeCount"] = len(self.nodes)
        return demographics_dict

    def set_birth_rate(self, rate: float, node_ids: list[int] = None):
        """
        Sets a specified population-dependent birth rate value on the target node(s). Automatically handles any
        necessary config updates.

        Args:
            rate: (float) The birth rate to set in units of births/year/1000-women
            node_ids: (list[int]) The node id(s) to apply changes to. None or 0 means the default node.

        Returns:

        """
        from emod_api.demographics.implicit_functions import _set_population_dependent_birth_rate

        rate = rate / 365 / 1000  # converting to births/day/woman, which is what EMOD internally uses.
        nodes = self.get_nodes_by_id(node_ids=node_ids)
        for _, node in nodes.items():
            node.birth_rate = rate
        self.implicits.append(_set_population_dependent_birth_rate)

    #
    # These distribution setters accept either a simple or complex distribution
    #

    def set_age_distribution(self,
                             distribution: Union[BaseDistribution, AgeDistribution],
                             node_ids: list[int] = None) -> None:
        """
        Set the distribution from which the initial ages of the population will be drawn. At initialization, each person
        will be randomly assigned an age from the given distribution. Automatically handles any necessary config
        updates.

        Args:
            distribution: The distribution to set. Can either be a BaseDistribution object for a simple distribution
                or AgeDistribution object for complex.
            node_ids: The node id(s) to apply changes to. None or 0 means the default node.

        Returns:
            Nothing
        """
        from emod_api.demographics.implicit_functions import _set_age_simple, _set_age_complex

        self._set_distribution(distribution=distribution,
                               use_case='age',
                               simple_distribution_implicits=[_set_age_simple],
                               complex_distribution_implicits=[_set_age_complex],
                               node_ids=node_ids)

    def set_susceptibility_distribution(self,
                                        distribution: Union[BaseDistribution, SusceptibilityDistribution],
                                        node_ids: list[int] = None) -> None:
        """
        Set a distribution that will impact the probability that a person will acquire an infection based on immunity.
        The SusceptibilityDistribution is used to define an age-based distribution from which a probability is selected
        to determine if a person is susceptible or not. The older ages of the distribution are only used during
        initialization. Automatically handles any necessary config updates. Susceptibility distributions are NOT
        compatible or supported for Malaria or HIV simulations.


        Args:
            distribution: The distribution to set. Can either be a BaseDistribution object for a simple distribution
                or SusceptibilityDistribution object for complex.
            node_ids: The node id(s) to apply changes to. None or 0 means the default node.

        Returns:
            Nothing
        """
        from emod_api.demographics.implicit_functions import _set_suscept_simple, _set_suscept_complex

        self._set_distribution(distribution=distribution,
                               use_case='susceptibility',
                               simple_distribution_implicits=[_set_suscept_simple],
                               complex_distribution_implicits=[_set_suscept_complex],
                               node_ids=node_ids)

    #
    # These distribution setters only accept simple distributions
    #

    def set_prevalence_distribution(self,
                                    distribution: BaseDistribution,
                                    node_ids: list[int] = None) -> None:
        """
        Sets a prevalence distribution on the demographics object. Automatically handles any necessary config updates.
        Initial prevalence distributions are not compatible with HIV EMOD simulations.

        Args:
            distribution: The distribution to set. Must be a BaseDistribution object for a simple distribution.
            node_ids: The node id(s) to apply changes to. None or 0 means the default node.

        Returns:
            Nothing
        """
        from emod_api.demographics.implicit_functions import _set_init_prev

        self._set_distribution(distribution=distribution,
                               use_case='prevalence',
                               simple_distribution_implicits=[_set_init_prev],
                               node_ids=node_ids)

    def set_migration_heterogeneity_distribution(self,
                                                 distribution: BaseDistribution,
                                                 node_ids: list[int] = None) -> None:
        """
        Sets a migration heterogeneity distribution on the demographics object. Automatically handles any necessary
        config updates.

        Args:
            distribution: The distribution to set. Must be a BaseDistribution object for a simple distribution.
            node_ids: The node id(s) to apply changes to. None or 0 means the default node.

        Returns:
            Nothing
        """

        from emod_api.demographics.implicit_functions import _set_migration_model_fixed_rate
        from emod_api.demographics.implicit_functions import _set_enable_migration_model_heterogeneity

        implicits = [_set_migration_model_fixed_rate, _set_enable_migration_model_heterogeneity]
        self._set_distribution(distribution=distribution,
                               use_case='migration_heterogeneity',
                               simple_distribution_implicits=implicits,
                               node_ids=node_ids)

    # TODO: This belongs in emodpy-malaria, as that is the one disease that uses this set of parameters.
    #  Should be moved into a subclass of emodpy Demographics inside emodpy-malaria during a 2.0 conversion of it.
    #  https://github.com/EMOD-Hub/emodpy-malaria/issues/126
    # def set_innate_immune_distribution(self,
    #                                    distribution: BaseDistribution,
    #                                    innate_immune_variation_type: str,
    #                                    node_ids: list[int] = None) -> None:
    #     """
    #     Sets a innate immune distribution on the demographics object. Automatically handles any necessary config
    #     updates.
    #
    #     Args:
    #         distribution: The distribution to set. Must be a BaseDistribution object for a simple distribution.
    #         innate_immune_variation_type: the variation type to configure in EMOD. Must be either CYTOKINE_KILLING
    #             or PYROGENIC_THRESHOLD to be compatible with setting a innate immune distribution.
    #         node_ids: The node id(s) to apply changes to. None or 0 means the default node.
    #
    #     Returns:
    #         Nothing
    #     """
    #     from emod_api.demographics.implicit_functions import _set_immune_variation_type_cytokine_killing, \
    #         _set_immune_variation_type_pyrogenic_threshold
    #
    #     valid_types = [self.CYTOKINE_KILLING, self.PYROGENIC_THRESHOLD]
    #     if innate_immune_variation_type == self.CYTOKINE_KILLING:
    #         implicits = [_set_immune_variation_type_cytokine_killing]
    #     elif innate_immune_variation_type == self.PYROGENIC_THRESHOLD:
    #         implicits = [_set_immune_variation_type_pyrogenic_threshold]
    #     else:
    #         valid_types_str = ', '.join(valid_types)
    #         raise ValueError(f'innate_immune_variation_type must be one of: {valid_types_str} ... to allow use of a '
    #                          f'distribution.')
    #
    #     self._set_distribution(distribution=distribution,
    #                            use_case='innate_immune',
    #                            simple_distribution_implicits=implicits,
    #                            node_ids=node_ids)

    #
    # These distribution setters only accept complex distributions
    #

    def set_mortality_distribution(self,
                                   distribution_male: MortalityDistribution,
                                   distribution_female: MortalityDistribution,
                                   node_ids: list[int] = None) -> None:
        """
        Sets the gendered mortality distributions on the demographics object. Automatically handles any necessary
        config updates.

        Args:
            distribution_male: The male MortalityDistribution to set. Must be a MortalityDistribution object for a
                complex distribution.
            distribution_female: The female MortalityDistribution to set. Must be a MortalityDistribution object for a
                complex distribution.
            node_ids: The node id(s) to apply changes to. None or 0 means the default node.

        Returns:
            Nothing
        """

        # Note that we only need to set the implicit function once, even though we set two distributions.
        from emod_api.demographics.implicit_functions import _set_enable_natural_mortality
        from emod_api.demographics.implicit_functions import _set_mortality_age_gender_year

        implicits = [_set_enable_natural_mortality, _set_mortality_age_gender_year]
        self._set_distribution(distribution=distribution_male,
                               use_case='mortality_male',
                               complex_distribution_implicits=implicits,
                               node_ids=node_ids)
        self._set_distribution(distribution=distribution_female,
                               use_case='mortality_female',
                               node_ids=node_ids)

    def _set_distribution(self,
                          distribution: Union[
                              BaseDistribution,
                              AgeDistribution,
                              SusceptibilityDistribution,
                              FertilityDistribution,
                              MortalityDistribution],
                          use_case: str,
                          simple_distribution_implicits: list[Callable] = None,
                          complex_distribution_implicits: list[Callable] = None,
                          node_ids: list[int] = None) -> None:
        """
        A common core function for setting simple and complex distributions for all uses in EMOD demographics. This
        should not be called directly by users.

        Args:
            distribution: The distribution object to set. If it is a BaseDistribution object, a simple distribution
                will be set on the demographics object. If it is of any other allowed type, a complex distribution is
                set.
            use_case: A string used to identify which function to call on specified nodes to properly configure the
                specified distribution.
            simple_distribution_implicits: for simple distributions, a list of functions to call at config build-time to
                ensure the specified distribution is utilized properly.
            complex_distribution_implicits: for complex distributions, a list of functions to call at config build-time
                to ensure the specified distribution is utilized properly.
            node_ids: The node id(s) to apply changes to. None or 0 means the default node.

        Returns:
            Nothing
        """
        if isinstance(distribution, BaseDistribution):
            distribution_values = distribution.get_demographic_distribution_parameters()
            function_name = f"_set_{use_case}_simple_distribution"
            implicit_calls = simple_distribution_implicits
        else:
            function_name = f"_set_{use_case}_complex_distribution"
            distribution_values = {'distribution': distribution}
            implicit_calls = complex_distribution_implicits

        nodes = self.get_nodes_by_id(node_ids=node_ids)
        for _, node in nodes.items():
            getattr(node, function_name)(**distribution_values)

        # ensure the config is properly set up to know about this distribution
        if implicit_calls is not None:
            self.implicits.extend(implicit_calls)

    def add_individual_property(self,
                                property: str,
                                values: Union[list[str], list[float]] = None,
                                initial_distribution: list[float] = None,
                                node_ids: list[int] = None,
                                overwrite_existing: bool = False) -> None:
        """
        Adds a new individual property or replace values on an already-existing property in a demographics object.

        Individual properties act as 'labels' on model agents that can be used for identifying and targeting
        subpopulations in campaign elements and reports. For example, model agents may be given a property
        ('Accessibility') that labels them as either having access to health care (value: 'Yes') or not (value: 'No').

        Another example: a property ('Risk') could label model agents as belonging to a spectrum of value categories
        (values: 'HIGH', 'MEDIUM', 'LOW') that govern disease-related behavior.

        Note: EMOD requires individual property key and values (property and values arguments) to be the same across all
            nodes. The initial distributions of individual properties (initial_distribution) can vary across nodes.

        Documentation of individual properties and HINT:
            For malaria, see :doc:`emod-malaria:emod/model-properties`
                    and for HIV, see :doc:`emod-hiv:emod/model-properties`.

        Args:
            property: a new individual property key to add. If property already exists an exception is raised
                unless overwrite_existing is True. 'property' must be the same across all nodes, note above.
            values: A list of valid values for the property key. For example,  ['Yes', 'No'] for an 'Accessibility'
                property key. 'values' must be the same across all nodes, note above.
            initial_distribution: The fractional, between 0 and 1, initial distribution of each valid values entry.
                Order must match values argument. The values must add up to 1.
            node_ids: The node ids to apply changes to. None or 0 means the 'Defaults' node, which will apply to all
                the nodes unless a node has its own individual properties re-definition.
            overwrite_existing: When True, overwrites existing individual properties with the same key. If False,
                raises an exception if the property already exists in the node(s).

        Returns:
            None
        """
        nodes = self.get_nodes_by_id(node_ids=node_ids).values()
        individual_property = IndividualProperty(property=property,
                                                 values=values,
                                                 initial_distribution=initial_distribution)
        for node in nodes:
            if not overwrite_existing and node.has_individual_property(property_key=property):
                raise ValueError(f"Property key '{property}' already present in IndividualProperties list")

            node.individual_properties.add(individual_property=individual_property, overwrite=overwrite_existing)

node_count property

Return the number of (geographic) nodes.

node_ids property

Return the list of (geographic) node ids.

__init__(nodes, idref=None, default_node=None)

Passed-in default nodes are optional. If one is not passed in, one will be created.

Source code in emod_api/demographics/demographics_base.py
def __init__(self, nodes: list[Node], idref: str = None, default_node: Node = None):
    """
    Passed-in default nodes are optional. If one is not passed in, one will be created.
    """
    super().__init__(idref=idref)
    self.nodes = nodes
    self.implicits = list()
    self.migration_files = list()

    # verify that the provided non-default nodes have ids > 0
    for node in self.nodes:
        if node.id <= 0:
            raise InvalidNodeIdException(f"Non-default nodes must have integer ids > 0 . Found id: {node.id}")

    # Build the default node if not provided and then perform some setup/verification
    default_node = self._generate_default_node() if default_node is None else default_node
    self.default_node = default_node
    self.default_node.name = self.DEFAULT_NODE_NAME
    if self.default_node.id != 0:
        raise InvalidNodeIdException(f"Default nodes must have an id of 0. It is {self.default_node.id} .")
    self.metadata = self.generate_headers()
    # TODO: remove the following setting of birth_rate on the default node once this EMOD binary issue is fixed
    #  https://github.com/InstituteforDiseaseModeling/DtkTrunk/issues/4009
    if self.default_node.birth_rate is None:
        self.default_node.birth_rate = 0

    # enforce unique node ids and names
    self.verify_demographics_integrity()

add_individual_property(property, values=None, initial_distribution=None, node_ids=None, overwrite_existing=False)

Adds a new individual property or replace values on an already-existing property in a demographics object.

Individual properties act as 'labels' on model agents that can be used for identifying and targeting subpopulations in campaign elements and reports. For example, model agents may be given a property ('Accessibility') that labels them as either having access to health care (value: 'Yes') or not (value: 'No').

Another example: a property ('Risk') could label model agents as belonging to a spectrum of value categories (values: 'HIGH', 'MEDIUM', 'LOW') that govern disease-related behavior.

EMOD requires individual property key and values (property and values arguments) to be the same across all

nodes. The initial distributions of individual properties (initial_distribution) can vary across nodes.

Documentation of individual properties and HINT

For malaria, see :doc:emod-malaria:emod/model-properties and for HIV, see :doc:emod-hiv:emod/model-properties.

Parameters:

Name Type Description Default
property str

a new individual property key to add. If property already exists an exception is raised unless overwrite_existing is True. 'property' must be the same across all nodes, note above.

required
values Union[list[str], list[float]]

A list of valid values for the property key. For example, ['Yes', 'No'] for an 'Accessibility' property key. 'values' must be the same across all nodes, note above.

None
initial_distribution list[float]

The fractional, between 0 and 1, initial distribution of each valid values entry. Order must match values argument. The values must add up to 1.

None
node_ids list[int]

The node ids to apply changes to. None or 0 means the 'Defaults' node, which will apply to all the nodes unless a node has its own individual properties re-definition.

None
overwrite_existing bool

When True, overwrites existing individual properties with the same key. If False, raises an exception if the property already exists in the node(s).

False

Returns:

Type Description
None

None

Source code in emod_api/demographics/demographics_base.py
def add_individual_property(self,
                            property: str,
                            values: Union[list[str], list[float]] = None,
                            initial_distribution: list[float] = None,
                            node_ids: list[int] = None,
                            overwrite_existing: bool = False) -> None:
    """
    Adds a new individual property or replace values on an already-existing property in a demographics object.

    Individual properties act as 'labels' on model agents that can be used for identifying and targeting
    subpopulations in campaign elements and reports. For example, model agents may be given a property
    ('Accessibility') that labels them as either having access to health care (value: 'Yes') or not (value: 'No').

    Another example: a property ('Risk') could label model agents as belonging to a spectrum of value categories
    (values: 'HIGH', 'MEDIUM', 'LOW') that govern disease-related behavior.

    Note: EMOD requires individual property key and values (property and values arguments) to be the same across all
        nodes. The initial distributions of individual properties (initial_distribution) can vary across nodes.

    Documentation of individual properties and HINT:
        For malaria, see :doc:`emod-malaria:emod/model-properties`
                and for HIV, see :doc:`emod-hiv:emod/model-properties`.

    Args:
        property: a new individual property key to add. If property already exists an exception is raised
            unless overwrite_existing is True. 'property' must be the same across all nodes, note above.
        values: A list of valid values for the property key. For example,  ['Yes', 'No'] for an 'Accessibility'
            property key. 'values' must be the same across all nodes, note above.
        initial_distribution: The fractional, between 0 and 1, initial distribution of each valid values entry.
            Order must match values argument. The values must add up to 1.
        node_ids: The node ids to apply changes to. None or 0 means the 'Defaults' node, which will apply to all
            the nodes unless a node has its own individual properties re-definition.
        overwrite_existing: When True, overwrites existing individual properties with the same key. If False,
            raises an exception if the property already exists in the node(s).

    Returns:
        None
    """
    nodes = self.get_nodes_by_id(node_ids=node_ids).values()
    individual_property = IndividualProperty(property=property,
                                             values=values,
                                             initial_distribution=initial_distribution)
    for node in nodes:
        if not overwrite_existing and node.has_individual_property(property_key=property):
            raise ValueError(f"Property key '{property}' already present in IndividualProperties list")

        node.individual_properties.add(individual_property=individual_property, overwrite=overwrite_existing)

apply_overlay(overlay_nodes)

Overlays a set of nodes onto the demographics object. Only overlay nodes with ids matching current demographic node_ids will be overlayed (extending/overriding exisiting node data).

Parameters:

Name Type Description Default
overlay_nodes list[Node]

a list of Node objects that will overlay/override data in the demographics object.

required

Returns:

Type Description
None

Nothing

Source code in emod_api/demographics/demographics_base.py
def apply_overlay(self, overlay_nodes: list[Node]) -> None:
    """
    Overlays a set of nodes onto the demographics object. Only overlay nodes with ids matching current demographic
    node_ids will be overlayed (extending/overriding exisiting node data).

    Args:
        overlay_nodes (list[Node]): a list of Node objects that will overlay/override data in the demographics
            object.

    Returns:
        Nothing
    """
    existing_nodes_by_id = self._all_nodes_by_id
    for overlay_node in overlay_nodes:
        if overlay_node.id in existing_nodes_by_id:
            self.get_node_by_id(node_id=overlay_node.id).update(overlay_node)

get_node(nodeid)

Return the node with node.id equal to nodeid.

Parameters:

Name Type Description Default
nodeid int

an id to use in retrieving the requested Node object. None or 0 for 'the default node'.

required

Returns:

Type Description
Node

a Node object

Source code in emod_api/demographics/demographics_base.py
def get_node(self, nodeid: int) -> Node:
    """
    Return the node with node.id equal to nodeid.

    Args:
        nodeid: an id to use in retrieving the requested Node object. None or 0 for 'the default node'.

    Returns:
        a Node object
    """
    message = "get_node() is a deprecated function of Node objects, use get_node_by_id() instead. " \
              "(For example, demographics.get_node_by_id(node_id=4))"
    warnings.warn(message=message, category=DeprecationWarning, stacklevel=2)
    return self.get_node_by_id(node_id=nodeid)

get_node_by_id(node_id)

Returns the Node object requested by its node id.

Parameters:

Name Type Description Default
node_id int

a node_id to use in retrieving the requested Node object. None or 0 for 'the default node'.

required

Returns:

Type Description
Node

a Node object

Source code in emod_api/demographics/demographics_base.py
def get_node_by_id(self, node_id: int) -> Node:
    """
    Returns the Node object requested by its node id.

    Args:
        node_id: a node_id to use in retrieving the requested Node object. None or 0 for 'the default node'.

    Returns:
        a Node object
    """
    return list(self.get_nodes_by_id(node_ids=[node_id]).values())[0]

get_node_by_name(node_name)

Returns the Node object requested by its node name.

Parameters:

Name Type Description Default
node_name str

a node_name to use in retrieving the requested Node object. None for 'the default node'.

required

Returns:

Type Description
Node

a Node object

Source code in emod_api/demographics/demographics_base.py
def get_node_by_name(self, node_name: str) -> Node:
    """
    Returns the Node object requested by its node name.

    Args:
        node_name: a node_name to use in retrieving the requested Node object. None for 'the default node'.

    Returns:
        a Node object
    """
    return list(self.get_nodes_by_name(node_names=[node_name]).values())[0]

get_nodes_by_id(node_ids)

Returns the Node objects requested by their node id.

Parameters:

Name Type Description Default
node_ids list[int]

a list of node ids to use in retrieving Node objects. None or 0 for 'the default node'.

required

Returns:

Type Description
dict[int, Node]

a dict with id: node entries

Source code in emod_api/demographics/demographics_base.py
def get_nodes_by_id(self, node_ids: list[int]) -> dict[int, Node]:
    """
    Returns the Node objects requested by their node id.

    Args:
        node_ids: a list of node ids to use in retrieving Node objects. None or 0 for 'the default node'.

    Returns:
        a dict with id: node entries
    """
    # replace a None id (default node) request with 0
    if node_ids is None:
        node_ids = [0]
    if None in node_ids:
        node_ids.remove(None)
        node_ids.append(0)

    missing_node_ids = [node_id for node_id in node_ids if node_id not in self._all_node_ids]
    if len(missing_node_ids) > 0:
        msg = ', '.join([str(node_id) for node_id in missing_node_ids])
        raise self.UnknownNodeException(f"The following node id(s) were requested but do not exist in this demographics "
                                        f"object:\n{msg}")
    requested_nodes = {node_id: node for node_id, node in self._all_nodes_by_id.items() if node_id in node_ids}
    return requested_nodes

get_nodes_by_name(node_names)

Returns the Node objects requested by their node name.

Parameters:

Name Type Description Default
node_names list[str]

a list of node names to use in retrieving Node objects. None for 'the default node'.

required

Returns:

Type Description
dict[str, Node]

a dict with name: node entries

Source code in emod_api/demographics/demographics_base.py
def get_nodes_by_name(self, node_names: list[str]) -> dict[str, Node]:
    """
    Returns the Node objects requested by their node name.

    Args:
        node_names: a list of node names to use in retrieving Node objects. None for 'the default node'.

    Returns:
        a dict with name: node entries
    """
    # replace a None name (default node) request with the default node's name
    if node_names is None:
        node_names = [self.default_node.name]
    if None in node_names:
        node_names.remove(None)
        node_names.append(self.default_node.name)

    missing_node_names = [node_name for node_name in node_names if node_name not in self._all_node_names]
    if len(missing_node_names) > 0:
        msg = ', '.join([str(node_name) for node_name in missing_node_names])
        raise self.UnknownNodeException(f"The following node name(s) were requested but do not exist in this demographics "
                                        f"object:\n{msg}")
    requested_nodes = {node_name: node for node_name, node in self._all_nodes_by_name.items()
                       if node_name in node_names}
    return requested_nodes

set_age_distribution(distribution, node_ids=None)

Set the distribution from which the initial ages of the population will be drawn. At initialization, each person will be randomly assigned an age from the given distribution. Automatically handles any necessary config updates.

Parameters:

Name Type Description Default
distribution Union[BaseDistribution, AgeDistribution]

The distribution to set. Can either be a BaseDistribution object for a simple distribution or AgeDistribution object for complex.

required
node_ids list[int]

The node id(s) to apply changes to. None or 0 means the default node.

None

Returns:

Type Description
None

Nothing

Source code in emod_api/demographics/demographics_base.py
def set_age_distribution(self,
                         distribution: Union[BaseDistribution, AgeDistribution],
                         node_ids: list[int] = None) -> None:
    """
    Set the distribution from which the initial ages of the population will be drawn. At initialization, each person
    will be randomly assigned an age from the given distribution. Automatically handles any necessary config
    updates.

    Args:
        distribution: The distribution to set. Can either be a BaseDistribution object for a simple distribution
            or AgeDistribution object for complex.
        node_ids: The node id(s) to apply changes to. None or 0 means the default node.

    Returns:
        Nothing
    """
    from emod_api.demographics.implicit_functions import _set_age_simple, _set_age_complex

    self._set_distribution(distribution=distribution,
                           use_case='age',
                           simple_distribution_implicits=[_set_age_simple],
                           complex_distribution_implicits=[_set_age_complex],
                           node_ids=node_ids)

set_birth_rate(rate, node_ids=None)

Sets a specified population-dependent birth rate value on the target node(s). Automatically handles any necessary config updates.

Parameters:

Name Type Description Default
rate float

(float) The birth rate to set in units of births/year/1000-women

required
node_ids list[int]

(list[int]) The node id(s) to apply changes to. None or 0 means the default node.

None

Returns:

Source code in emod_api/demographics/demographics_base.py
def set_birth_rate(self, rate: float, node_ids: list[int] = None):
    """
    Sets a specified population-dependent birth rate value on the target node(s). Automatically handles any
    necessary config updates.

    Args:
        rate: (float) The birth rate to set in units of births/year/1000-women
        node_ids: (list[int]) The node id(s) to apply changes to. None or 0 means the default node.

    Returns:

    """
    from emod_api.demographics.implicit_functions import _set_population_dependent_birth_rate

    rate = rate / 365 / 1000  # converting to births/day/woman, which is what EMOD internally uses.
    nodes = self.get_nodes_by_id(node_ids=node_ids)
    for _, node in nodes.items():
        node.birth_rate = rate
    self.implicits.append(_set_population_dependent_birth_rate)

set_demographics_filenames(filenames)

Set paths to demographic file.

Parameters:

Name Type Description Default
filenames list[str]

Paths to demographic files.

required
Source code in emod_api/demographics/demographics_base.py
def set_demographics_filenames(self, filenames: list[str]):
    """
    Set paths to demographic file.

    Args:
        filenames: Paths to demographic files.
    """
    from emod_api.demographics.implicit_functions import _set_demographic_filenames

    self.implicits.append(partial(_set_demographic_filenames, filenames=filenames))

set_migration_heterogeneity_distribution(distribution, node_ids=None)

Sets a migration heterogeneity distribution on the demographics object. Automatically handles any necessary config updates.

Parameters:

Name Type Description Default
distribution BaseDistribution

The distribution to set. Must be a BaseDistribution object for a simple distribution.

required
node_ids list[int]

The node id(s) to apply changes to. None or 0 means the default node.

None

Returns:

Type Description
None

Nothing

Source code in emod_api/demographics/demographics_base.py
def set_migration_heterogeneity_distribution(self,
                                             distribution: BaseDistribution,
                                             node_ids: list[int] = None) -> None:
    """
    Sets a migration heterogeneity distribution on the demographics object. Automatically handles any necessary
    config updates.

    Args:
        distribution: The distribution to set. Must be a BaseDistribution object for a simple distribution.
        node_ids: The node id(s) to apply changes to. None or 0 means the default node.

    Returns:
        Nothing
    """

    from emod_api.demographics.implicit_functions import _set_migration_model_fixed_rate
    from emod_api.demographics.implicit_functions import _set_enable_migration_model_heterogeneity

    implicits = [_set_migration_model_fixed_rate, _set_enable_migration_model_heterogeneity]
    self._set_distribution(distribution=distribution,
                           use_case='migration_heterogeneity',
                           simple_distribution_implicits=implicits,
                           node_ids=node_ids)

set_mortality_distribution(distribution_male, distribution_female, node_ids=None)

Sets the gendered mortality distributions on the demographics object. Automatically handles any necessary config updates.

Parameters:

Name Type Description Default
distribution_male MortalityDistribution

The male MortalityDistribution to set. Must be a MortalityDistribution object for a complex distribution.

required
distribution_female MortalityDistribution

The female MortalityDistribution to set. Must be a MortalityDistribution object for a complex distribution.

required
node_ids list[int]

The node id(s) to apply changes to. None or 0 means the default node.

None

Returns:

Type Description
None

Nothing

Source code in emod_api/demographics/demographics_base.py
def set_mortality_distribution(self,
                               distribution_male: MortalityDistribution,
                               distribution_female: MortalityDistribution,
                               node_ids: list[int] = None) -> None:
    """
    Sets the gendered mortality distributions on the demographics object. Automatically handles any necessary
    config updates.

    Args:
        distribution_male: The male MortalityDistribution to set. Must be a MortalityDistribution object for a
            complex distribution.
        distribution_female: The female MortalityDistribution to set. Must be a MortalityDistribution object for a
            complex distribution.
        node_ids: The node id(s) to apply changes to. None or 0 means the default node.

    Returns:
        Nothing
    """

    # Note that we only need to set the implicit function once, even though we set two distributions.
    from emod_api.demographics.implicit_functions import _set_enable_natural_mortality
    from emod_api.demographics.implicit_functions import _set_mortality_age_gender_year

    implicits = [_set_enable_natural_mortality, _set_mortality_age_gender_year]
    self._set_distribution(distribution=distribution_male,
                           use_case='mortality_male',
                           complex_distribution_implicits=implicits,
                           node_ids=node_ids)
    self._set_distribution(distribution=distribution_female,
                           use_case='mortality_female',
                           node_ids=node_ids)

set_prevalence_distribution(distribution, node_ids=None)

Sets a prevalence distribution on the demographics object. Automatically handles any necessary config updates. Initial prevalence distributions are not compatible with HIV EMOD simulations.

Parameters:

Name Type Description Default
distribution BaseDistribution

The distribution to set. Must be a BaseDistribution object for a simple distribution.

required
node_ids list[int]

The node id(s) to apply changes to. None or 0 means the default node.

None

Returns:

Type Description
None

Nothing

Source code in emod_api/demographics/demographics_base.py
def set_prevalence_distribution(self,
                                distribution: BaseDistribution,
                                node_ids: list[int] = None) -> None:
    """
    Sets a prevalence distribution on the demographics object. Automatically handles any necessary config updates.
    Initial prevalence distributions are not compatible with HIV EMOD simulations.

    Args:
        distribution: The distribution to set. Must be a BaseDistribution object for a simple distribution.
        node_ids: The node id(s) to apply changes to. None or 0 means the default node.

    Returns:
        Nothing
    """
    from emod_api.demographics.implicit_functions import _set_init_prev

    self._set_distribution(distribution=distribution,
                           use_case='prevalence',
                           simple_distribution_implicits=[_set_init_prev],
                           node_ids=node_ids)

set_susceptibility_distribution(distribution, node_ids=None)

Set a distribution that will impact the probability that a person will acquire an infection based on immunity. The SusceptibilityDistribution is used to define an age-based distribution from which a probability is selected to determine if a person is susceptible or not. The older ages of the distribution are only used during initialization. Automatically handles any necessary config updates. Susceptibility distributions are NOT compatible or supported for Malaria or HIV simulations.

Parameters:

Name Type Description Default
distribution Union[BaseDistribution, SusceptibilityDistribution]

The distribution to set. Can either be a BaseDistribution object for a simple distribution or SusceptibilityDistribution object for complex.

required
node_ids list[int]

The node id(s) to apply changes to. None or 0 means the default node.

None

Returns:

Type Description
None

Nothing

Source code in emod_api/demographics/demographics_base.py
def set_susceptibility_distribution(self,
                                    distribution: Union[BaseDistribution, SusceptibilityDistribution],
                                    node_ids: list[int] = None) -> None:
    """
    Set a distribution that will impact the probability that a person will acquire an infection based on immunity.
    The SusceptibilityDistribution is used to define an age-based distribution from which a probability is selected
    to determine if a person is susceptible or not. The older ages of the distribution are only used during
    initialization. Automatically handles any necessary config updates. Susceptibility distributions are NOT
    compatible or supported for Malaria or HIV simulations.


    Args:
        distribution: The distribution to set. Can either be a BaseDistribution object for a simple distribution
            or SusceptibilityDistribution object for complex.
        node_ids: The node id(s) to apply changes to. None or 0 means the default node.

    Returns:
        Nothing
    """
    from emod_api.demographics.implicit_functions import _set_suscept_simple, _set_suscept_complex

    self._set_distribution(distribution=distribution,
                           use_case='susceptibility',
                           simple_distribution_implicits=[_set_suscept_simple],
                           complex_distribution_implicits=[_set_suscept_complex],
                           node_ids=node_ids)

verify_demographics_integrity()

One stop shopping for making sure a demographics object doesn't have known invalid settings.

Source code in emod_api/demographics/demographics_base.py
def verify_demographics_integrity(self):
    """
    One stop shopping for making sure a demographics object doesn't have known invalid settings.
    """
    self._verify_node_id_uniqueness()
    self._verify_node_name_uniqueness()