Skip to content

age_distribution

AgeDistribution

Bases: Updateable

Source code in emod_api/demographics/age_distribution.py
  9
 10
 11
 12
 13
 14
 15
 16
 17
 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
class AgeDistribution(Updateable):
    def __init__(self,
                 ages_years: List[float],
                 cumulative_population_fraction: List[float]):
        """
        A cumulative population age distribution in fraction units 0 to 1. This is used as part of initializing the
        population in an EMOD simulation.

        The AgeDistribution provides a probability each agent at the beginning of a simulation will be
        initialized with a given age. A uniform random number is drawn for each agent and checked against the
        provided cumulative population fractions directly, with the corresponding age entry selected for the agent. If
        the drawn number lies between two values, the selected agent age is linearly interpolated from the two closest
        corresponding ages. If the drawn number lies beyond the provided cumulative population fraction range, the
        closest corresponding age will be selected.

        Args:
            ages_years: (List[float]) A list of ages (in years) that population fraction data will be provided for.
                Must be a list of monotonically increasing floats within range 0 <= age <= 200 .
            cumulative_population_fraction: (List[float]) A list of cumulative population fractions corresponding to
                the provided ages_years list. Must be a list of monotonically increasing floats within range
                0 <= fraction <= 1 .

        Example:
            ages_years: [5, 10, 20, 50, 100]
            cumulative_population_fraction: [0.1, 0.2, 0.5, 0.8, 1.0]

            Uniform random number draw: 0.8
                Selected age: 50 years
            Uniform random number draw: 0.35
                Selected age: 10 + (0.35 - 0.2) * ((20-10) / (0.5-0.2)) = 15 years
            Uniform random number draw: 0.05 (beyond provided fraction range)
                Selected age: 1 year (nearest corresponding age)
        """
        super().__init__()
        self.ages_years = ages_years
        self.cumulative_population_fraction = cumulative_population_fraction
        # This will convert the object to an age distribution dictionary and then validate it reporting object-relevant
        # messages
        self._validate(distribution_dict=self.to_dict(validate=False), source_is_dict=False)

    @classmethod
    def _rate_scale_factor(cls):
        return 365.0  # convert ages in years to days

    def to_dict(self, validate: bool = True) -> Dict:
        distribution_dict = {
            'ResultValues': self.ages_years,
            'DistributionValues': self.cumulative_population_fraction,
            'ResultScaleFactor': self._rate_scale_factor()
        }
        if validate:
            self._validate(distribution_dict=distribution_dict, source_is_dict=False)
        return distribution_dict

    @classmethod
    def from_dict(cls, distribution_dict: Dict):
        cls._validate(distribution_dict=distribution_dict, source_is_dict=True)
        return cls(ages_years=distribution_dict['ResultValues'],
                   cumulative_population_fraction=distribution_dict['DistributionValues'])

    _validation_messages = {
        'fixed_value_check': {
            True: "key: %s value: %s does not match expected value: %s",
            False: None  # These are all properties of the obj and cannot be made invalid
        },
        'data_dimensionality_check_ages': {
            True: 'ResultValues must be a 1-d array of floats',
            False: 'ages_years must be a 1-d array of floats'
        },
        'data_dimensionality_check_distributions': {
            True: 'DistributionValues must be a 1-d array of floats',
            False: 'cumulative_population_fraction must be a 1-d array of floats'
        },
        'age_and_distribution_length_check': {
            True: 'ResultValues and DistributionValues must be the same length but are not',
            False: 'ages_years and cumulative_population_fraction must be the same length but are not'
        },
        'age_range_check': {
            True: "ResultValues age values must be: 0 <= age <= 200 in years. Out-of-range index:values : %s",
            False: "All ages_years values must be: 0 <= age <= 200 in years. Out-of-range index:values : %s"
        },
        'distribution_range_check': {
            True: "DistributionValues cumulative fractions must be: 0 <= fraction <= 1. "
                  "Out-of-range index:values : %s",
            False: "All cumulative_population_fraction values must be: 0 <= fraction <= 1. "
                   "Out-of-range index:values : %s"
        },
        'age_monotonicity_check': {
            True: "ResultValues ages in years must monotonically increase but do not, index: %d value: %s",
            False: "ages_years values must monotonically increase but do not, index: %d value: %s"
        },
        'distribution_monotonicity_check': {
            True: "DistributionValues cumulative fractions must monotonically increase but do not, index: %d value: %s",
            False: "cumulative_population_fraction values must monotonically increase but do not, index: %d value: %s"
        },
    }

    @classmethod
    def _validate(cls, distribution_dict: Dict, source_is_dict: bool):
        """
        Validate an AgeDistribution in dict form

        Args:
            distribution_dict: (dict) the age distribution dict to validate
            source_is_dict: (bool) If true, report dict-relevant error messages. If false, report obj-relevant messages.

        Returns:
            Nothing
        """
        if source_is_dict is True:
            expected_values = {
                'ResultScaleFactor': cls._rate_scale_factor()
            }
            for key, expected_value in expected_values.items():
                value = distribution_dict[key]
                if value != expected_value:
                    message = cls._validation_messages['fixed_value_check'][source_is_dict] % (key, value, expected_value)
                    raise demog_ex.InvalidFixedValueException(message)

        # ensure the ages and distribution values are both 1-d iterables of the same length
        ages = distribution_dict['ResultValues']
        distribution_values = distribution_dict['DistributionValues']

        is_1d = check_dimensionality(data=ages, dimensionality=1)
        if not is_1d:
            message = cls._validation_messages['data_dimensionality_check_ages'][source_is_dict]
            raise demog_ex.InvalidDataDimensionality(message)
        is_1d = check_dimensionality(data=distribution_values, dimensionality=1)
        if not is_1d:
            message = cls._validation_messages['data_dimensionality_check_distributions'][source_is_dict]
            raise demog_ex.InvalidDataDimensionality(message)

        if len(ages) != len(distribution_values):
            message = cls._validation_messages['age_and_distribution_length_check'][source_is_dict]
            raise demog_ex.InvalidDataDimensionLength(message)

        # ensure the age and distribution value lists are ascending and in reasonable ranges
        out_of_range = [f"{index}:{age}" for index, age in enumerate(ages) if (age < 0) or (age > 200)]
        if len(out_of_range) > 0:
            oor_str = ', '.join(out_of_range)
            message = cls._validation_messages['age_range_check'][source_is_dict] % oor_str
            raise demog_ex.AgeOutOfRangeException(message)
        out_of_range = [f"{index}:{value}" for index, value in enumerate(distribution_values)
                        if (value < 0) or (value > 1)]
        if len(out_of_range) > 0:
            oor_str = ', '.join(out_of_range)
            message = cls._validation_messages['distribution_range_check'][source_is_dict] % oor_str
            raise demog_ex.DistributionOutOfRangeException(message)

        for i in range(1, len(ages)):
            if ages[i] - ages[i - 1] <= 0:
                message = cls._validation_messages['age_monotonicity_check'][source_is_dict] % (i, ages[i])
                raise demog_ex.NonMonotonicAgeException(message)
        for i in range(1, len(distribution_values)):
            if distribution_values[i] - distribution_values[i - 1] <= 0:
                message = cls._validation_messages['distribution_monotonicity_check'][source_is_dict] % (i, distribution_values[i])
                raise demog_ex.NonMonotonicDistributionException(message)

__init__(ages_years, cumulative_population_fraction)

A cumulative population age distribution in fraction units 0 to 1. This is used as part of initializing the population in an EMOD simulation.

The AgeDistribution provides a probability each agent at the beginning of a simulation will be initialized with a given age. A uniform random number is drawn for each agent and checked against the provided cumulative population fractions directly, with the corresponding age entry selected for the agent. If the drawn number lies between two values, the selected agent age is linearly interpolated from the two closest corresponding ages. If the drawn number lies beyond the provided cumulative population fraction range, the closest corresponding age will be selected.

Parameters:

Name Type Description Default
ages_years List[float]

(List[float]) A list of ages (in years) that population fraction data will be provided for. Must be a list of monotonically increasing floats within range 0 <= age <= 200 .

required
cumulative_population_fraction List[float]

(List[float]) A list of cumulative population fractions corresponding to the provided ages_years list. Must be a list of monotonically increasing floats within range 0 <= fraction <= 1 .

required
Example

ages_years: [5, 10, 20, 50, 100] cumulative_population_fraction: [0.1, 0.2, 0.5, 0.8, 1.0]

Uniform random number draw: 0.8 Selected age: 50 years Uniform random number draw: 0.35 Selected age: 10 + (0.35 - 0.2) * ((20-10) / (0.5-0.2)) = 15 years Uniform random number draw: 0.05 (beyond provided fraction range) Selected age: 1 year (nearest corresponding age)

Source code in emod_api/demographics/age_distribution.py
10
11
12
13
14
15
16
17
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
def __init__(self,
             ages_years: List[float],
             cumulative_population_fraction: List[float]):
    """
    A cumulative population age distribution in fraction units 0 to 1. This is used as part of initializing the
    population in an EMOD simulation.

    The AgeDistribution provides a probability each agent at the beginning of a simulation will be
    initialized with a given age. A uniform random number is drawn for each agent and checked against the
    provided cumulative population fractions directly, with the corresponding age entry selected for the agent. If
    the drawn number lies between two values, the selected agent age is linearly interpolated from the two closest
    corresponding ages. If the drawn number lies beyond the provided cumulative population fraction range, the
    closest corresponding age will be selected.

    Args:
        ages_years: (List[float]) A list of ages (in years) that population fraction data will be provided for.
            Must be a list of monotonically increasing floats within range 0 <= age <= 200 .
        cumulative_population_fraction: (List[float]) A list of cumulative population fractions corresponding to
            the provided ages_years list. Must be a list of monotonically increasing floats within range
            0 <= fraction <= 1 .

    Example:
        ages_years: [5, 10, 20, 50, 100]
        cumulative_population_fraction: [0.1, 0.2, 0.5, 0.8, 1.0]

        Uniform random number draw: 0.8
            Selected age: 50 years
        Uniform random number draw: 0.35
            Selected age: 10 + (0.35 - 0.2) * ((20-10) / (0.5-0.2)) = 15 years
        Uniform random number draw: 0.05 (beyond provided fraction range)
            Selected age: 1 year (nearest corresponding age)
    """
    super().__init__()
    self.ages_years = ages_years
    self.cumulative_population_fraction = cumulative_population_fraction
    # This will convert the object to an age distribution dictionary and then validate it reporting object-relevant
    # messages
    self._validate(distribution_dict=self.to_dict(validate=False), source_is_dict=False)