Skip to content

Disease config

Disease Configuration

This module handles the configuration of diseases for the epidemiology model.

Classes:

Name Description
DiseaseConfig

Manages disease-specific configurations.

RatesManager

Handles infection outcome rates.

InteractionManager

Manages interaction-related configurations.

SymptomManager

Manages symptom-related configurations.

VaccinationManager

Manages vaccination-related configurations.

PolicyManager

Handles policy-related configurations.

DiseaseConfig

Manages the configuration of a specific disease.

This class loads and parses disease-specific YAML configurations, and initialises managers for rates, interactions, symptoms, vaccinations, and policies.

Source code in june/epidemiology/infection/disease_config.py
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
class DiseaseConfig: # pylint: disable=too-few-public-methods
    """Manages the configuration of a specific disease.

    This class loads and parses disease-specific YAML configurations,
    and initialises managers for rates, interactions, symptoms,
    vaccinations, and policies.

    """
    def __init__(self, disease_name: str, config_path: str):
        """ 
        Args:
            config_path (str):
                Path to the disease configuration file to get the disease configuration file. 

        """
        self.disease_name = disease_name.lower()

        # Load the main disease YAML
        with open(config_path, "r", encoding="utf-8") as f:
            self.disease_yaml = yaml.safe_load(f)

        self.rates_manager = RatesManager(self.disease_yaml, self.disease_name)
        self.interaction_manager = InteractionManager(self.disease_name)
        self.symptom_manager = SymptomManager(self.disease_yaml)
        self.vaccination_manager = VaccinationManager(self.disease_name)
        self.policy_manager = PolicyManager(self.disease_name)

__init__(disease_name, config_path)

Parameters:

Name Type Description Default
config_path str

Path to the disease configuration file to get the disease configuration file.

required
Source code in june/epidemiology/infection/disease_config.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def __init__(self, disease_name: str, config_path: str):
    """ 
    Args:
        config_path (str):
            Path to the disease configuration file to get the disease configuration file. 

    """
    self.disease_name = disease_name.lower()

    # Load the main disease YAML
    with open(config_path, "r", encoding="utf-8") as f:
        self.disease_yaml = yaml.safe_load(f)

    self.rates_manager = RatesManager(self.disease_yaml, self.disease_name)
    self.interaction_manager = InteractionManager(self.disease_name)
    self.symptom_manager = SymptomManager(self.disease_yaml)
    self.vaccination_manager = VaccinationManager(self.disease_name)
    self.policy_manager = PolicyManager(self.disease_name)

InteractionManager

Manages interaction-related configurations for a specific disease.

This class loads interaction settings from a YAML file and initialises attributes related to disease susceptibility, interaction coefficients, contact matrices, and interactive groups.

Source code in june/epidemiology/infection/disease_config.py
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
class InteractionManager:
    """Manages interaction-related configurations for a specific disease.

    This class loads interaction settings from a YAML file and initialises
    attributes related to disease susceptibility, interaction coefficients,
    contact matrices, and interactive groups.

    """

    def __init__(self, disease_name: str):

        self.disease_name = disease_name.lower()
        interaction_path = (
            BASE_PATH /
            "configs/defaults/interaction" /
            f"interaction_{self.disease_name}.yaml"
        )

        # Load the interaction YAML file
        self._interaction_yaml = load_yaml(interaction_path)
        # Initialise private attributes
        self._susceptibilities = self._interaction_yaml.get("susceptibilities", {})
        self._alpha_physical = self._interaction_yaml.get("alpha_physical", None)
        self._betas = self._interaction_yaml.get("betas", {})
        self._contact_matrices = self._interaction_yaml.get("contact_matrices", {})

    @property
    def susceptibilities(self) -> dict:
        """Retrieve susceptibility values for different groups.

        """
        return self._susceptibilities

    @property
    def alpha_physical(self) -> Optional[float]:
        """Retrieve the physical interaction coefficient (alpha).

        """
        return self._alpha_physical

    @property
    def betas(self) -> dict:
        """Retrieve beta coefficients for interaction types.

        """
        return self._betas

    @property
    def contact_matrices(self) -> dict:
        """Retrieve the contact matrices for population groups.

        """
        return self._contact_matrices

alpha_physical property

Retrieve the physical interaction coefficient (alpha).

betas property

Retrieve beta coefficients for interaction types.

contact_matrices property

Retrieve the contact matrices for population groups.

susceptibilities property

Retrieve susceptibility values for different groups.

PolicyManager

Manages policy configurations for a specific disease.

Source code in june/epidemiology/infection/disease_config.py
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
class PolicyManager:
    """Manages policy configurations for a specific disease."""

    def __init__(self, disease_name: str):
        policy_path = paths.configs_path / f"defaults/policy/policy_{disease_name}.yaml"
        with open(policy_path, "r", encoding="utf-8") as f:
            self.policy_yaml = yaml.safe_load(f) or {}

    def get_policy_data(self, policy_name: str) -> dict:
        """Retrieve the configuration for a specific policy.

        Args:
            policy_name (str): Name of the policy.

        Returns:
            (dict): Configuration dictionary for the policy.

        """
        return self.policy_yaml.get(policy_name, {})

    def get_all_policies(self) -> dict:
        """Retrieve all categorised policies.


        Returns:
            (dict): A dictionary of all policies organised by categories.

        """
        return self.policy_yaml

get_all_policies()

Retrieve all categorised policies.

Returns:

Type Description
dict

A dictionary of all policies organised by categories.

Source code in june/epidemiology/infection/disease_config.py
437
438
439
440
441
442
443
444
445
def get_all_policies(self) -> dict:
    """Retrieve all categorised policies.


    Returns:
        (dict): A dictionary of all policies organised by categories.

    """
    return self.policy_yaml

get_policy_data(policy_name)

Retrieve the configuration for a specific policy.

Parameters:

Name Type Description Default
policy_name str

Name of the policy.

required

Returns:

Type Description
dict

Configuration dictionary for the policy.

Source code in june/epidemiology/infection/disease_config.py
425
426
427
428
429
430
431
432
433
434
435
def get_policy_data(self, policy_name: str) -> dict:
    """Retrieve the configuration for a specific policy.

    Args:
        policy_name (str): Name of the policy.

    Returns:
        (dict): Configuration dictionary for the policy.

    """
    return self.policy_yaml.get(policy_name, {})

RatesManager

Manages infection outcome rates for a specific disease.

This class handles the loading and processing of infection outcome rates for a disease based on its configuration. It initialises rate structures, maps rates to symptom tags, and provides access to infection outcome rates.

Source code in june/epidemiology/infection/disease_config.py
 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
class RatesManager:
    """Manages infection outcome rates for a specific disease.

    This class handles the loading and processing of infection outcome rates
    for a disease based on its configuration. It initialises rate structures,
    maps rates to symptom tags, and provides access to infection outcome rates.

    """
    def __init__(self, disease_yaml: dict, disease_name: str):
        self.rates_file: Path = (
            paths.data_path /
            f"input/health_index/infection_outcome_rates_{disease_name.lower()}.csv"
        )
        self.rate_to_tag_mapping: Dict[str, str] = (
            get_nested_key(disease_yaml, ["disease", "rate_to_tag_mapping"], {})
        )
        self.symptom_tags: Dict[str, int] = {
            tag["name"]: tag["value"]
            for tag in get_nested_key(disease_yaml, ["disease", "symptom_tags"], [])
        }
        self.unrated_tags: List[str] = get_nested_key(disease_yaml, ["disease", "unrated_tags"], [])
        self.infection_outcome_rates: List[dict] = (
            get_nested_key(disease_yaml, ["disease", "infection_outcome_rates"], [])
        )

        self._rates_structure: Dict[str, Union[None, Dict[str, float]]] = None  # Initialise to None



    @property
    def rates_structure(self) -> Dict[str, Dict[str, Dict[str, Union[None, Dict[str, float]]]]]:
        """Retrieve or initialise the rates structure.

        The rates structure is a nested dictionary mapping rate parameters,
        population sectors, and genders to their precomputed values.


        Returns:
            dict[str, dict[str, dict[str, Union[None, dict[str, float]]]]]:
                A nested dictionary where keys are parameters, population sectors (e.g., 'gp', 'ch'), and genders ('male', 'female').

        """
        if self._rates_structure is None:
            self._rates_structure = {
                outcome["parameter"]: {
                    "gp": {"male": None, "female": None},
                    "ch": {"male": None, "female": None}
                }
                for outcome in self.infection_outcome_rates
            }
        return self._rates_structure

    def get_precomputed_rates(
        self, rates_df: pd.DataFrame, population: str, sex: str, parameter: str
    ) -> Dict[str, float]:
        """Retrieve or compute precomputed rates for a given parameter, population, and gender.

        Args:
            rates_df (pd.DataFrame): A DataFrame containing rate values indexed by age bins.
            population (str): The population type (e.g., 'ch', 'gp').
            sex (str): The sex of the individual ('male' or 'female').
            parameter (str): The rate parameter to retrieve or compute (e.g., 'hospital', 'ifr').

        Returns:
            dict[str, float]: A dictionary mapping age bins to precomputed rate values.

        Raises:
            ValueError:
                If the specified column (constructed from population, parameter,
                and sex) is not found in the DataFrame.

        """
        # Check if rates are already computed for this parameter, population, and gender
        if self.rates_structure[parameter][population][sex] is not None:
            return self.rates_structure[parameter][population][sex]

        column_name = f"{population}_{parameter}_{sex}"

        if column_name not in rates_df.columns:
            raise ValueError(f"Column '{column_name}' not found in the DataFrame.")

        # Store the precomputed rates in the nested structure
        self.rates_structure[parameter][population][sex] = rates_df[column_name].to_dict()


        rate = {
            age_bin: float(value)
            for age_bin, value in self.rates_structure[parameter][population][sex].items()
        }
        return rate

    def map_rate_to_tag(self, rate_name: str) -> str:
        """Map a rate name to its corresponding symptom tag using the rate-to-tag mapping.

        Args:
            rate_name (str): The name of the rate in the CSV or configuration.

        Returns:
            (str): The corresponding symptom tag name.

        Raises:
            KeyError: If the rate name is not found in the mapping.

        """
        if rate_name not in self.rate_to_tag_mapping:
            raise KeyError(
                f"Rate '{rate_name}' is not mapped to a symptom tag."
            )
        return self.rate_to_tag_mapping[rate_name]

    def get_tag_for_rate(self, rate_name: str) -> int:
        """Get the tag value corresponding to a rate name using the mapping.

        Args:
            rate_name (str): The name of the rate in the CSV or configuration.

        Returns:
            (int): The tag value corresponding to the rate name.

        Raises:
            KeyError: If the rate name or tag is not found in the configuration.

        """
        tag_name = self.map_rate_to_tag(rate_name)
        return self.symptom_tags[tag_name]

    def get_rates_file(self) -> str:
        """Retrieve the path to the infection outcome rates file.


        Returns:
            (str): Path to the rates file.

        """
        return self.rates_file

rates_structure property

Retrieve or initialise the rates structure.

The rates structure is a nested dictionary mapping rate parameters, population sectors, and genders to their precomputed values.

Returns:

Type Description
Dict[str, Dict[str, Dict[str, Union[None, Dict[str, float]]]]]

dict[str, dict[str, dict[str, Union[None, dict[str, float]]]]]: A nested dictionary where keys are parameters, population sectors (e.g., 'gp', 'ch'), and genders ('male', 'female').

get_precomputed_rates(rates_df, population, sex, parameter)

Retrieve or compute precomputed rates for a given parameter, population, and gender.

Parameters:

Name Type Description Default
rates_df DataFrame

A DataFrame containing rate values indexed by age bins.

required
population str

The population type (e.g., 'ch', 'gp').

required
sex str

The sex of the individual ('male' or 'female').

required
parameter str

The rate parameter to retrieve or compute (e.g., 'hospital', 'ifr').

required

Returns:

Type Description
Dict[str, float]

dict[str, float]: A dictionary mapping age bins to precomputed rate values.

Raises:

Type Description
ValueError

If the specified column (constructed from population, parameter, and sex) is not found in the DataFrame.

Source code in june/epidemiology/infection/disease_config.py
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
def get_precomputed_rates(
    self, rates_df: pd.DataFrame, population: str, sex: str, parameter: str
) -> Dict[str, float]:
    """Retrieve or compute precomputed rates for a given parameter, population, and gender.

    Args:
        rates_df (pd.DataFrame): A DataFrame containing rate values indexed by age bins.
        population (str): The population type (e.g., 'ch', 'gp').
        sex (str): The sex of the individual ('male' or 'female').
        parameter (str): The rate parameter to retrieve or compute (e.g., 'hospital', 'ifr').

    Returns:
        dict[str, float]: A dictionary mapping age bins to precomputed rate values.

    Raises:
        ValueError:
            If the specified column (constructed from population, parameter,
            and sex) is not found in the DataFrame.

    """
    # Check if rates are already computed for this parameter, population, and gender
    if self.rates_structure[parameter][population][sex] is not None:
        return self.rates_structure[parameter][population][sex]

    column_name = f"{population}_{parameter}_{sex}"

    if column_name not in rates_df.columns:
        raise ValueError(f"Column '{column_name}' not found in the DataFrame.")

    # Store the precomputed rates in the nested structure
    self.rates_structure[parameter][population][sex] = rates_df[column_name].to_dict()


    rate = {
        age_bin: float(value)
        for age_bin, value in self.rates_structure[parameter][population][sex].items()
    }
    return rate

get_rates_file()

Retrieve the path to the infection outcome rates file.

Returns:

Type Description
str

Path to the rates file.

Source code in june/epidemiology/infection/disease_config.py
210
211
212
213
214
215
216
217
218
def get_rates_file(self) -> str:
    """Retrieve the path to the infection outcome rates file.


    Returns:
        (str): Path to the rates file.

    """
    return self.rates_file

get_tag_for_rate(rate_name)

Get the tag value corresponding to a rate name using the mapping.

Parameters:

Name Type Description Default
rate_name str

The name of the rate in the CSV or configuration.

required

Returns:

Type Description
int

The tag value corresponding to the rate name.

Raises:

Type Description
KeyError

If the rate name or tag is not found in the configuration.

Source code in june/epidemiology/infection/disease_config.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def get_tag_for_rate(self, rate_name: str) -> int:
    """Get the tag value corresponding to a rate name using the mapping.

    Args:
        rate_name (str): The name of the rate in the CSV or configuration.

    Returns:
        (int): The tag value corresponding to the rate name.

    Raises:
        KeyError: If the rate name or tag is not found in the configuration.

    """
    tag_name = self.map_rate_to_tag(rate_name)
    return self.symptom_tags[tag_name]

map_rate_to_tag(rate_name)

Map a rate name to its corresponding symptom tag using the rate-to-tag mapping.

Parameters:

Name Type Description Default
rate_name str

The name of the rate in the CSV or configuration.

required

Returns:

Type Description
str

The corresponding symptom tag name.

Raises:

Type Description
KeyError

If the rate name is not found in the mapping.

Source code in june/epidemiology/infection/disease_config.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
def map_rate_to_tag(self, rate_name: str) -> str:
    """Map a rate name to its corresponding symptom tag using the rate-to-tag mapping.

    Args:
        rate_name (str): The name of the rate in the CSV or configuration.

    Returns:
        (str): The corresponding symptom tag name.

    Raises:
        KeyError: If the rate name is not found in the mapping.

    """
    if rate_name not in self.rate_to_tag_mapping:
        raise KeyError(
            f"Rate '{rate_name}' is not mapped to a symptom tag."
        )
    return self.rate_to_tag_mapping[rate_name]

SymptomManager

Manages symptom-related configurations for a specific disease.

This class initialises and processes symptom-related attributes for a disease based on its YAML configuration. It provides functionality to retrieve symptom tag indices, categories, and default stages.

Source code in june/epidemiology/infection/disease_config.py
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
class SymptomManager:
    """Manages symptom-related configurations for a specific disease.

    This class initialises and processes symptom-related attributes for a disease
    based on its YAML configuration. It provides functionality to retrieve
    symptom tag indices, categories, and default stages.

    """
    def __init__(self, disease_yaml: dict):
        # Initialise attributes from the disease YAML
        if "disease" not in disease_yaml:
            raise ValueError("The provided YAML does not contain a 'disease' key.")

        self.disease_yaml: dict = disease_yaml
        self.symptom_tags: Dict[str, int] = {
            tag["name"]: tag["value"]
            for tag in get_nested_key(disease_yaml, ["disease", "symptom_tags"], [])
        }
        settings = get_nested_key(disease_yaml, ["disease", "settings"], {})
        self.default_lowest_stage: str = settings.get("default_lowest_stage", "unknown")
        self._max_mild_symptom: Optional[str] = settings.get("max_mild_symptom_tag")
        self.severe_symptom = self._resolve_tags("severe_symptoms_stay_at_home_stage")
        self.stay_at_home = self._resolve_tags("stay_at_home_stage")


    @property
    def default_lowest_stage_index(self) -> int:
        """Retrieve the index of the default lowest stage.


        Returns:
            (int): The index of the default lowest stage.

        Raises:
            ValueError: If the default lowest stage is not found in the symptom tags.


        """
        if self.default_lowest_stage not in self.symptom_tags:
            raise ValueError(
                f"Default stage '{self.default_lowest_stage}' not in symptom tags."
            )
        return self.symptom_tags[self.default_lowest_stage]

    @property
    def max_mild_symptom_tag(self) -> Optional[int]:
        """Retrieve the index of the maximum mild symptom tag.


        Returns:
            Optional[int]: The value corresponding to `max_mild_symptom_tag`.

        Raises:
            ValueError: If `max_mild_symptom_tag` is not defined or is not valid.


        """
        if self._max_mild_symptom is None:
            raise ValueError("'max_mild_symptom_tag' is not defined in the configuration.")
        if self._max_mild_symptom not in self.symptom_tags:
            raise ValueError(
                f"'max_mild_symptom_tag' ({self._max_mild_symptom}) is not a valid symptom tag."
            )
        return self.symptom_tags[self._max_mild_symptom]

    def _resolve_tags(self, category: str) -> List[int]:
        """Resolve tags dynamically for a given category from the configuration.

        Args:
            category (str): The category in the YAML file to retrieve the symptom tags for.

        Returns:
            (list[int]): A list of tag values corresponding to the given category.

        """
        stage_definitions = get_nested_key(self.disease_yaml, ["disease", "settings", category], [])
        return [
            self.symptom_tags.get(stage.get("name"), -1)
            for stage in stage_definitions
            if "name" in stage and stage["name"] in self.symptom_tags
        ]

    def get_tag_value(self, tag_name: str) -> int:
        """Get the value of a symptom tag by its name.

        Args:
            tag_name (str): The name of the symptom tag.

        Returns:
            (int): The value of the symptom tag.

        Raises:
            KeyError: If the tag name is not found in the configuration.


        """
        if tag_name not in self.symptom_tags:
            raise KeyError(f"Symptom tag '{tag_name}' not found.")
        return self.symptom_tags[tag_name]

default_lowest_stage_index property

Retrieve the index of the default lowest stage.

Returns:

Type Description
int

The index of the default lowest stage.

Raises:

Type Description
ValueError

If the default lowest stage is not found in the symptom tags.

max_mild_symptom_tag property

Retrieve the index of the maximum mild symptom tag.

Returns:

Type Description
Optional[int]

Optional[int]: The value corresponding to max_mild_symptom_tag.

Raises:

Type Description
ValueError

If max_mild_symptom_tag is not defined or is not valid.

get_tag_value(tag_name)

Get the value of a symptom tag by its name.

Parameters:

Name Type Description Default
tag_name str

The name of the symptom tag.

required

Returns:

Type Description
int

The value of the symptom tag.

Raises:

Type Description
KeyError

If the tag name is not found in the configuration.

Source code in june/epidemiology/infection/disease_config.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
def get_tag_value(self, tag_name: str) -> int:
    """Get the value of a symptom tag by its name.

    Args:
        tag_name (str): The name of the symptom tag.

    Returns:
        (int): The value of the symptom tag.

    Raises:
        KeyError: If the tag name is not found in the configuration.


    """
    if tag_name not in self.symptom_tags:
        raise KeyError(f"Symptom tag '{tag_name}' not found.")
    return self.symptom_tags[tag_name]

VaccinationManager

Manages vaccination-related configurations for a specific disease.

This class loads and processes vaccination-related settings from a YAML file. It initialises attributes for available vaccines and vaccination campaigns.

Source code in june/epidemiology/infection/disease_config.py
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
class VaccinationManager:
    """Manages vaccination-related configurations for a specific disease.

    This class loads and processes vaccination-related settings from a YAML file.
    It initialises attributes for available vaccines and vaccination campaigns.

    """
    def __init__(self, disease_name: str):

        vaccination_path = (
            paths.configs_path /
            f"defaults/epidemiology/vaccines/vaccines_{disease_name}.yaml"
        )

        # Load the vaccination YAML
        with open(vaccination_path, "r", encoding="utf-8") as f:
            self.vaccination_yaml = yaml.safe_load(f)

        # Initialise attributes
        self.vaccines = self.vaccination_yaml.get("vaccines", {}) or {}
        self.vaccination_campaigns = self.vaccination_yaml.get("vaccination_campaigns", {}) or {}

    def get_vaccines(self) -> dict:
        """Retrieve all vaccines.


        Returns:
            (dict): A dictionary of vaccines.

        """
        return self.vaccines

    def get_vaccination_campaigns(self) -> dict:
        """Retrieve all vaccination campaigns.


        Returns:
            (dict): A dictionary of vaccination campaigns.

        """
        return self.vaccination_campaigns

get_vaccination_campaigns()

Retrieve all vaccination campaigns.

Returns:

Type Description
dict

A dictionary of vaccination campaigns.

Source code in june/epidemiology/infection/disease_config.py
407
408
409
410
411
412
413
414
415
def get_vaccination_campaigns(self) -> dict:
    """Retrieve all vaccination campaigns.


    Returns:
        (dict): A dictionary of vaccination campaigns.

    """
    return self.vaccination_campaigns

get_vaccines()

Retrieve all vaccines.

Returns:

Type Description
dict

A dictionary of vaccines.

Source code in june/epidemiology/infection/disease_config.py
397
398
399
400
401
402
403
404
405
def get_vaccines(self) -> dict:
    """Retrieve all vaccines.


    Returns:
        (dict): A dictionary of vaccines.

    """
    return self.vaccines

get_nested_key(data, keys, default=None)

Retrieve the value from a nested dictionary using a list of keys.

This function iteratively traverses a dictionary using the provided list of keys to access nested values. If a key is missing at any level, the function returns the specified default value.

Parameters:

Name Type Description Default
data dict

The dictionary to traverse.

required
keys list[str]

A list of keys representing the path to the desired value.

required
default any

The value to return if any key in the path is missing (default is None).

None

Returns:

Type Description
any

The value from the nested dictionary if all keys exist, otherwise the specified default value.

Source code in june/epidemiology/infection/disease_config.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def get_nested_key(data: dict, keys: list[str], default=None):
    """Retrieve the value from a nested dictionary using a list of keys.

    This function iteratively traverses a dictionary using the provided list
    of keys to access nested values. If a key is missing at any level, the
    function returns the specified default value.

    Args:
        data (dict): The dictionary to traverse.
        keys (list[str]): A list of keys representing the path to the desired value.
        default (any, optional): The value to return if any key in the path is missing (default is None).

    Returns:
        (any):
            The value from the nested dictionary if all keys exist,
            otherwise the specified default value.

    """
    for key in keys:
        data = data.get(key, {})
    return data or default

load_yaml(file_path)

Utility function to load a YAML file.

Parameters:

Name Type Description Default
file_path Path

The path to the YAML file.

required

Returns:

Type Description
dict

The contents of the YAML file as a dictionary.

Source code in june/epidemiology/infection/disease_config.py
21
22
23
24
25
26
27
28
29
30
31
32
def load_yaml(file_path: Path) -> dict:
    """Utility function to load a YAML file.

    Args:
        file_path (Path): The path to the YAML file.

    Returns:
        (dict): The contents of the YAML file as a dictionary.

    """
    with open(file_path, "r", encoding="utf-8") as f:
        return yaml.safe_load(f) or {}