Skip to content

country_model

Country

Bases: ABC

Country is an "abstract" base class for HIV models of different countries or regions. It is intended that a person wanting to develop a new model of a country will either subclass Country (or another Country model) and change the things that are different. One could use this to ensure that things that are supposed to be the same across all of the country models are the same.

WARNING: Country models are used as the class and not an instance object. That is, one does not create an object like: * my_country = MyCountry() Instead, they call the classmethods directly from the class like: * demographics = MyCountry.build_demographics() If someone attempts to create an instance, we want it to throw an exception so people don't use it in a way that is not intended.

WARNING_2: As of Python 3.13, you are not supposed to combine different properties with the classmethod property. It should be used by itself. This is way we are using class variables instead of properties. When we do class inheritance, each subclass gets its own instance of the class variables. For example, if Zambia and Kenya are both subclasss of Country, they will have their own instance of country_name even though it is declared in Country. This allows us to set country_name for Zambia without it impacting Kenya.

NOTE: We are using classes instead of modules because we can still get inheritance like you'd expect. For example, with classes if BaseCountry has three methods: func_A(), func_B(), and func_C(). Assume func_C() calls both func_A() and func_B(). Let's alo assume that we create Zambia as a subclass of BaseCountry and have it override func_B(). With classes, when func_C()) is called for Zambia, it will use the overridden func_B(). If we tried to do the same thing with modules, func_C() would use the func_B() defined in BaseCountry.

We use Country as a class and this idea of "parameterized calls" so that the country can play well with emod_workflow. The "parameterized calls" need the functions to be static and these calls allow us to give a unique name to each parameter. Unique parameter names allow the user to specifically refer to a parameter even when there are numerous instances of the object that has the parameter.

Source code in emodpy_hiv/country_model.py
 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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
class Country(ABC):
    """
    Country is an "abstract" base class for HIV models of different countries or regions.
    It is intended that a person wanting to develop a new model of a country will either
    subclass Country (or another Country model) and change the things that are different.
    One could use this to ensure that things that are supposed to be the same across all
    of the country models are the same.

    WARNING: Country models are used as the class and not an instance object.  That is,
    one does not create an object like:
    * my_country = MyCountry()
    Instead, they call the classmethods directly from the class like:
    * demographics = MyCountry.build_demographics()
    If someone attempts to create an instance, we want it to throw an exception so people
    don't use it in a way that is not intended.

    WARNING_2: As of Python 3.13, you are not supposed to combine different properties
    with the classmethod property. It should be used by itself.  This is way we are using
    class variables instead of properties.  When we do class inheritance, each subclass
    gets its own instance of the class variables.  For example, if Zambia and Kenya are
    both subclasss of Country, they will have their own instance of country_name even
    though it is declared in Country.  This allows us to set country_name for Zambia
    without it impacting Kenya.

    NOTE: We are using classes instead of modules because we can still get inheritance
    like you'd expect.  For example, with classes if BaseCountry has three methods:
    func_A(), func_B(), and func_C().  Assume func_C() calls both func_A() and func_B().
    Let's alo assume that we create Zambia as a subclass of BaseCountry and have it
    override func_B().  With classes, when func_C()) is called for Zambia, it will use
    the overridden func_B().  If we tried to do the same thing with modules, func_C()
    would use the func_B() defined in BaseCountry.

    We use Country as a class and this idea of "parameterized calls" so that the country
    can play well with emod_workflow.  The "parameterized calls" need the functions to be
    static and these calls allow us to give a unique name to each parameter.   Unique
    parameter names allow the user to specifically refer to a parameter even when there
    are numerous instances of the object that has the parameter.

    """

    # ------------------------------------------------------------------------------------
    # --- NOTE: I tried using the "Attributes:" stuff that Google says to use, but I kept
    # --- getting this #duplicate object description ... use :noindex: for one of them"
    # --- error message from ReadTheDocs.
    # ------------------------------------------------------------------------------------

    # String: The name of the country model
    country_name = None

    # Float: The calendar year to start the simulation.  This is frequently
    # set to 1960.5 so that there is time to burn-in the population and relationships.
    base_year = 1960.5

    def __init__(self):
        msg =  "You cannot create an instance of a Country.\n" # noqa: E222
        msg += "You must use the class as the object."
        raise NotImplementedError(msg)

    @staticmethod
    def generate_label(relationship_type: str = None,
                       risk_group: str = None,
                       node_ids: Union[List[int], None] = None,
                       node_name: str = None) -> str:
        if node_name is not None:
            label_items = [str(item) for item in [relationship_type, risk_group, node_name] if item is not None]
        else:
            node_ids = [] if node_ids is None else sorted(node_ids)
            label_items = [str(item) for item in [relationship_type, risk_group, *node_ids, node_name] if item is not None]
        label = '-'.join(label_items)
        return label

    @classmethod
    def get_config_parameterized_calls(cls, config: ReadOnlyDict) -> List[ParameterizedCall]:
        """
        Return a list of ParameterizedCall objects that will complete the configuration of an
        EMOD config object.

        Args
            config: The object to be updated when using instance methods with ParameterizedCall.

        Returns:
            List of ParameterizedCall objects
        """
        parameterized_calls = []

        def set_run_number(config, Run_Number: int = None):
            if Run_Number is not None:
                config.parameters.Run_Number = Run_Number

        pc = ParameterizedCall(func=set_run_number, hyperparameters={'Run_Number': None})
        parameterized_calls.append(pc)
        return parameterized_calls

    @classmethod
    def get_demographics_parameterized_calls(cls, demographics: HIVDemographics) -> List[ParameterizedCall]:
        """
        Return a list of ParameterizedCall objects that will complete the configuration of an
        EMOD demographics object.

        Args
            demographics: If not None, this will be the object that is updated

        Returns:
            List of ParameterizedCall objects
        """
        return []

    @classmethod
    def get_campaign_parameterized_calls(cls, campaign: emod_api.campaign) -> List[ParameterizedCall]:
        """
        Return a list of ParameterizedCall objects that will complete the configuration of an
        EMOD campaign object.

        Args
            campaign: If not None, this will be the object that is updated

        Returns:
            List of ParameterizedCall objects
        """
        return []

    @classmethod
    def initialize_config(cls, schema_path: Union[str, Path]) -> ReadOnlyDict:
        """
        Override this in the subclass to set the default values for the config object as needed.
        """
        config = EMODTask.build_default_config(schema_path=schema_path)
        return config

    @classmethod
    def initialize_demographics(cls) -> HIVDemographics:
        """
        Create the initial demographics object that will be modified by the ParameterizedCall
        objects from **get_demographics_parameterized_calls()**
        """
        demographics = HIVDemographics.from_template_node(pop=10000,
                                                          default_society_template="PFA-Southern-Africa")

        # TODO:  How to load default node attributes?

        return demographics

    @classmethod
    def initialize_campaign(cls, schema_path: Union[str, Path]) -> emod_api.campaign:
        """
        Create the initial campaign object that will be modified by the ParameterizedCall
        objects from **get_campaign_parameterized_calls()**
        """
        campaign = EMODTask.build_default_campaign(schema_path=schema_path)
        campaign.base_year = cls.base_year
        return campaign

    #
    # Convenience functions for non-EMOD-workflow users below
    #

    @classmethod
    def build_reports(cls, reporters: Reporters) -> Reporters:
        """
        Function that creates reports to be used in the experiment. The function must have Reporters
        object as the parameter and return that object. It is assumed that all the reporters come from the
        reporters that are part of EMOD main code. EMOD also supports reporters as custom plug-in dlls,
        however, not through the current emodpy system.

        Args:
            reporters: The Reporters object to add reports to

        Returns:
            Reporters object
        """
        return reporters

    @classmethod
    def _execute_parameterized_calls_on(cls, obj, parameterized_calls: List[ParameterizedCall]):
        for parameterized_call in parameterized_calls:
            # Now modify the provided object (obj). obj is passed as context to each successive ParameterizedCall.
            prepared_call = parameterized_call.prepare_call()
            prepared_call(obj)

    @classmethod
    def build_config(cls, config: ReadOnlyDict) -> ReadOnlyDict:
        """
        A function that creates a config object that can be used with
        EMODTask.from_defaults().

        Args:
            config(ReadOnlyDict): the config object that will be modified. It has the following structure:
                config.parameters.<parameter_name> , with <parameter_name> being an attribute.
        Returns:
            a config object
        """
        config = cls.initialize_config(schema_path=config["schema_path"])
        cls._execute_parameterized_calls_on(obj=config, parameterized_calls=cls.get_config_parameterized_calls(config=config))
        return config

    @classmethod
    def build_demographics(cls) -> HIVDemographics:
        """
        A function that configures the demographics for EMOD and can be used with
        EMODTask.from_defaults().

        Returns:
            a demographics object
        """
        demographics = cls.initialize_demographics()
        cls._execute_parameterized_calls_on(obj=demographics,
                                            parameterized_calls=cls.get_demographics_parameterized_calls(demographics=demographics))
        return demographics

    @classmethod
    def build_campaign(cls, campaign: emod_api.campaign) -> emod_api.campaign:
        """
        A method to pass into EMODTask to build campaign events for Emod.

        Args:
            campaign(emod_api.campaign): The emod_api campaign object to be modified.
        Returns:
            a campaign object
        """
        campaign = cls.initialize_campaign(schema_path=campaign.schema_path)
        calls = cls.get_campaign_parameterized_calls(campaign=campaign)
        cls._execute_parameterized_calls_on(obj=campaign, parameterized_calls=calls)
        return campaign

    #
    # common functions used for building campaign ParameterizedCalls below
    #

    @staticmethod
    def load_nchooser_distribution_data(file_path: str) -> dict:
        """
        Load target distribution data into a dataframe format that works for Nchooser and group by node_id.
        Args:
            file_path: path to the csv file that contains the data

        Returns:
            dict: a dictionary that has node_id as the key and a dataframe as the value. The dataframe contains the
            distribution data for Nchooser.

        """
        data = pd.read_csv(file_path)
        data_dict = defaultdict(pd.DataFrame)
        for node_id in pd.unique(data['node_set']):
            node_data = data[data['node_set'] == node_id]
            node_dict = {'year': [], 'min_age': [], 'max_age': [], 'n_circumcisions': []}
            for year in pd.unique(node_data['year']):
                year_data = node_data[node_data['year'] == year]
                for _, row in year_data.iterrows():
                    node_dict['year'].append(year)
                    node_dict['min_age'].append(float(row['age_bin'].split(':')[0].replace('[', '')))
                    node_dict['max_age'].append(float(row['age_bin'].split(':')[1].replace(')', '')) - 0.00001)
                    node_dict['n_circumcisions'].append(int(row['n_circumcisions']))
            data_dict[int(node_id)] = pd.DataFrame(node_dict)
        return data_dict

    @classmethod
    def add_historical_vmmc_nchooser(cls,
                                     campaign: emod_api.campaign,
                                     historical_vmmc_data_filepath: str,
                                     historical_vmmc_reduced_acquire: float = 0.6):
        # Load historical vmmc data into data frame
        historical_vmmc_data = cls.load_nchooser_distribution_data(historical_vmmc_data_filepath)
        for node_id in historical_vmmc_data:
            coc.add_historical_vmmc_nchooser(campaign=campaign,
                                             historical_vmmc_distributions_by_time=historical_vmmc_data[node_id],
                                             historical_vmmc_reduced_acquire=historical_vmmc_reduced_acquire,
                                             historical_vmmc_property_restrictions=None,
                                             historical_vmmc_node_ids=[node_id],
                                             has_intervention_name_exclusion=coc.ANY_MC,
                                             event_name=f"NChooser to produce specified number of program VMMCs in node"
                                                        f" {node_id}, {cls.country_name}")

    @classmethod
    def add_traditional_male_circumcision(cls,
                                          campaign: emod_api.campaign,
                                          traditional_male_circumcision_coverage: float = 0.5,  # TODO: what is a meaningful default?
                                          traditional_male_circumcision_reduced_acquire: float = 0.6,
                                          node_ids: Union[List[int], None] = None):
        randomchoice_start_year = 1975
        traditional_male_circumcision_start_year = 1961
        coc.add_traditional_male_circumcision(campaign=campaign,
                                              traditional_male_circumcision_start_year=traditional_male_circumcision_start_year,
                                              randomchoice_start_year=randomchoice_start_year,
                                              traditional_male_circumcision_coverage=traditional_male_circumcision_coverage,
                                              traditional_male_circumcision_reduced_acquire=traditional_male_circumcision_reduced_acquire,
                                              traditional_male_circumcision_node_ids=node_ids)

    @classmethod
    def add_vmmc_reference_tracking(cls,
                                    campaign: emod_api.campaign,
                                    tracking_vmmc_reduced_acquire: float = 0.6):
        vmmc_time_value_map = {
            "Times": [2015.9999, 2016, 2021],
            "Values": [0, 0.54, 0.9]  # Zambia values
        }
        coc.add_vmmc_reference_tracking(campaign=campaign,
                                        vmmc_time_value_map=vmmc_time_value_map,
                                        vmmc_reduced_acquire=tracking_vmmc_reduced_acquire,
                                        vmmc_target_min_age=15,
                                        vmmc_target_max_age=15.09,
                                        vmmc_start_year=2015,
                                        vmmc_node_ids=None,  # all nodes
                                        update_period=30.4166666666667)

    @classmethod
    def seed_infections(cls,
                        campaign: emod_api.campaign,
                        node_ids: Union[List[int], None] = None,
                        seeding_start_year: float = 1982,
                        seeding_coverage: float = 0.2,
                        seeding_target_min_age: float = 0,
                        seeding_target_max_age: float = 200,
                        seeding_target_gender: TargetGender = TargetGender.ALL):
        # add outbreak individual interventions with coverage 0.1 to all nodes with Risk:HIGH
        coc.seed_infections(campaign=campaign,
                            seeding_node_ids=node_ids,
                            seeding_start_year=seeding_start_year,
                            seeding_coverage=seeding_coverage,
                            seeding_target_min_age=seeding_target_min_age,
                            seeding_target_max_age=seeding_target_max_age,
                            seeding_target_gender=seeding_target_gender,
                            seeding_target_property_restrictions=["Risk:HIGH"])

    @classmethod
    def add_csw(cls,
                campaign: emod_api.campaign,
                csw_male_uptake_coverage: float = 0.1,
                csw_female_uptake_coverage: float = 0.1,  # TODO: meaningful default values?
                node_ids: Union[List[int], None] = None):
        coc.add_csw(campaign=campaign,
                    node_ids=node_ids,
                    male_uptake_coverage=csw_male_uptake_coverage,
                    female_uptake_coverage=csw_female_uptake_coverage)

    @classmethod
    def add_post_debut_coinfection(cls,
                                   campaign: emod_api.campaign,
                                   coinfection_coverage_HIGH: float = 0.3,
                                   coinfection_coverage_MEDIUM: float = 0.3,
                                   coinfection_coverage_LOW: float = 0.1,
                                   node_ids: Union[List[int], None] = None):
        coinfection_risk_to_coverage = {
            'HIGH': coinfection_coverage_HIGH,
            'MEDIUM': coinfection_coverage_MEDIUM,
            'LOW': coinfection_coverage_LOW
        }
        for risk, coverage in coinfection_risk_to_coverage.items():
            coc.add_post_debut_coinfection(campaign=campaign,
                                           coinfection_coverage=coverage,
                                           coinfection_gender=TargetGender.ALL,
                                           coinfection_IP=f'Risk:{risk}',
                                           coinfection_node_ids=node_ids)

    @classmethod
    def add_pmtct(cls, campaign: emod_api.campaign, node_ids: Union[List[int], None] = None):
        cls.add_state_TestingOnANC(campaign, node_ids=node_ids)
        # Testing of children at 6 weeks of age
        cls.add_state_TestingOnChild6w(campaign, node_ids=node_ids)

    @classmethod
    def add_health_care_testing(cls,
                                campaign: emod_api.campaign,
                                hct_delay_to_next_test: List[float],
                                hct_delay_to_next_test_node_ids: List[List[int]],
                                hct_delay_to_next_test_node_names: List[str],
                                hct_start_year: float = 1990,
                                node_ids: Union[List[int], None] = None):

        cls.add_state_HCTUptakeAtDebut(campaign=campaign, start_year=hct_start_year, node_ids=node_ids)

        cls.add_state_HCTUptakePostDebut(campaign=campaign, start_year=hct_start_year, node_ids=node_ids)

        cls.add_state_HCTTestingLoop(campaign=campaign,
                                     hct_delay_to_next_test=hct_delay_to_next_test,
                                     hct_delay_to_next_test_node_ids=hct_delay_to_next_test_node_ids,
                                     hct_delay_to_next_test_node_names=hct_delay_to_next_test_node_names,
                                     start_year=hct_start_year,
                                     node_ids=node_ids)

    @classmethod
    def add_ART_cascade(cls,
                        campaign: emod_api.campaign,
                        art_cascade_start_year: float = 1990,
                        cd4_retention_rate: float = 1,
                        linking_to_pre_art_sigmoid_min: float = 0.7572242198,
                        linking_to_pre_art_sigmoid_max: float = 0.9591484679,
                        linking_to_pre_art_sigmoid_midyear: float = 2006.8336631523,
                        linking_to_pre_art_sigmoid_rate: float = 1.0,
                        pre_staging_retention: float = 0.85,
                        pre_art_retention: float = 0.75,
                        linking_to_art_sigmoid_min: float = 0.0,
                        linking_to_art_sigmoid_max: float = 0.8507390283,
                        linking_to_art_sigmoid_midyear: float = 1997.4462231708,
                        linking_to_art_sigmoid_rate: float = 1.0,
                        art_reenrollment_willingness: float = 0.9,
                        immediate_art_rate: float = 0.1,
                        node_ids: Union[List[int], None] = None):

        cls.add_state_TestingOnSymptomatic(campaign=campaign, start_year=art_cascade_start_year, node_ids=node_ids)

        #
        # ---- BEGIN ART STAGING SECTION ----
        #
        cls.add_state_ARTStagingDiagnosticTest(campaign=campaign, start_year=art_cascade_start_year, node_ids=node_ids)

        cls.add_state_ARTStaging(campaign=campaign, start_year=art_cascade_start_year,
                                 cd4_retention_rate=cd4_retention_rate,
                                 pre_staging_retention=pre_staging_retention,
                                 node_ids=node_ids)
        #
        # ---- BEGIN PRE-ART ----
        #
        # chance of linking to pre-ART
        cls.add_state_LinkingToPreART(campaign=campaign,
                                      start_year=art_cascade_start_year,
                                      sigmoid_min=linking_to_pre_art_sigmoid_min,
                                      sigmoid_max=linking_to_pre_art_sigmoid_max,
                                      sigmoid_midyear=linking_to_pre_art_sigmoid_midyear,
                                      sigmoid_rate=linking_to_pre_art_sigmoid_rate,
                                      node_ids=node_ids)

        # ensuring each agent continues this cascade once per timestep
        cls.add_state_OnPreART(campaign=campaign, start_year=art_cascade_start_year, pre_art_retention=pre_art_retention,
                               node_ids=node_ids)
        #
        # ---- BEGIN ART LINKING ----
        #
        cls.add_state_LinkingToART(campaign=campaign,
                                   start_year=art_cascade_start_year,
                                   sigmoid_min=linking_to_art_sigmoid_min,
                                   sigmoid_max=linking_to_art_sigmoid_max,
                                   sigmoid_midyear=linking_to_art_sigmoid_midyear,
                                   sigmoid_rate=linking_to_art_sigmoid_rate,
                                   node_ids=node_ids)

        # decide to initiate ART now or later
        cls.add_state_OnART(campaign=campaign, start_year=art_cascade_start_year,
                            art_reenrollment_willingness=art_reenrollment_willingness,
                            immediate_art_rate=immediate_art_rate,
                            node_ids=node_ids)
        #
        cls.add_state_LostForever(campaign=campaign, start_year=art_cascade_start_year, node_ids=node_ids)

    @classmethod
    def add_state_TestingOnANC(cls, campaign: emod_api.campaign, node_ids: Union[List[int], None] = None):
        start_year = 1990
        coverage = 1.0
        sigmoid_min = 0
        sigmoid_max = 0.975
        sigmoid_midyear = 2005.87
        sigmoid_rate = 0.7136
        link_to_ART_rate = 0.8
        treatment_a_efficacy = 0.9
        treatment_b_efficacy = 0.96667
        sdNVP_efficacy = 0.66
        disqualifying_properties = [coc.CascadeState.LOST_FOREVER,
                                    coc.CascadeState.ON_ART,
                                    coc.CascadeState.LINKING_TO_ART,
                                    coc.CascadeState.ON_PRE_ART,
                                    coc.CascadeState.LINKING_TO_PRE_ART,
                                    coc.CascadeState.ART_STAGING,
                                    coc.CascadeState.TESTING_ON_SYMPTOMATIC]
        property_restrictions = 'Accessibility:Yes'

        coc.add_state_TestingOnANC(campaign=campaign,
                                   disqualifying_properties=disqualifying_properties,
                                   coverage=coverage,
                                   link_to_ART_rate=link_to_ART_rate,
                                   node_ids=node_ids,
                                   sigmoid_min=sigmoid_min,
                                   sigmoid_max=sigmoid_max,
                                   sigmoid_midyear=sigmoid_midyear,
                                   sigmoid_rate=sigmoid_rate,
                                   treatment_a_efficacy=treatment_a_efficacy,
                                   treatment_b_efficacy=treatment_b_efficacy,
                                   sdNVP_efficacy=sdNVP_efficacy,
                                   start_year=start_year,
                                   property_restrictions=property_restrictions)

    @classmethod
    def add_state_TestingOnChild6w(cls, campaign: emod_api.campaign, node_ids: Union[List[int], None] = None):
        child_testing_start_year = 2004
        child_testing_time_value_map = {"Times": [2004, 2005, 2006, 2008, 2009],  # TODO: move to Zambia?
                                        "Values": [0, 0.03, 0.1, 0.2, 0.3365]}
        disqualifying_properties = [coc.CascadeState.LOST_FOREVER,
                                    coc.CascadeState.ON_ART,
                                    coc.CascadeState.LINKING_TO_ART,
                                    coc.CascadeState.ON_PRE_ART,
                                    coc.CascadeState.LINKING_TO_PRE_ART,
                                    coc.CascadeState.ART_STAGING,
                                    coc.CascadeState.TESTING_ON_SYMPTOMATIC]
        property_restrictions = 'Accessibility:Yes'
        coc.add_state_TestingOnChild6w(campaign=campaign,
                                       disqualifying_properties=disqualifying_properties,
                                       time_value_map=child_testing_time_value_map,
                                       node_ids=node_ids,
                                       property_restrictions=property_restrictions,
                                       start_year=child_testing_start_year)

    @classmethod
    def add_state_HCTUptakeAtDebut(cls,
                                   campaign: emod_api.campaign,
                                   start_year: float,
                                   node_ids: Union[List[int], None] = None):
        disqualifying_properties = [coc.CascadeState.LOST_FOREVER,
                                    coc.CascadeState.ON_ART,
                                    coc.CascadeState.LINKING_TO_ART,
                                    coc.CascadeState.ON_PRE_ART,
                                    coc.CascadeState.LINKING_TO_PRE_ART,
                                    coc.CascadeState.ART_STAGING]
        coc.add_state_HCTUptakeAtDebut(campaign=campaign,
                                       disqualifying_properties=disqualifying_properties,
                                       node_ids=node_ids,
                                       start_year=start_year)

    @classmethod
    def add_state_HCTUptakePostDebut(cls,
                                     campaign: emod_api.campaign,
                                     start_year: float,
                                     node_ids: Union[List[int], None] = None):
        disqualifying_properties = [coc.CascadeState.LOST_FOREVER,
                                    coc.CascadeState.ON_ART,
                                    coc.CascadeState.LINKING_TO_ART,
                                    coc.CascadeState.ON_PRE_ART,
                                    coc.CascadeState.LINKING_TO_PRE_ART,
                                    coc.CascadeState.ART_STAGING]
        coc.add_state_HCTUptakePostDebut(campaign=campaign,
                                         disqualifying_properties=disqualifying_properties,
                                         node_ids=node_ids,
                                         hct_reentry_rate=1,
                                         start_year=start_year,
                                         tvmap_test_for_enter_HCT_testing_loop=coc.all_negative_time_value_map)

    @classmethod
    def add_state_HCTTestingLoop(cls, campaign: emod_api.campaign,
                                 start_year: float,
                                 hct_delay_to_next_test: List[float],
                                 hct_delay_to_next_test_node_ids: List[List[int]],
                                 hct_delay_to_next_test_node_names: List[str],
                                 node_ids: Union[List[int], None] = None):
        disqualifying_properties = [coc.CascadeState.LOST_FOREVER,
                                    coc.CascadeState.ON_ART,
                                    coc.CascadeState.LINKING_TO_ART,
                                    coc.CascadeState.ON_PRE_ART,
                                    coc.CascadeState.LINKING_TO_PRE_ART,
                                    coc.CascadeState.ART_STAGING]
        coc.add_state_HCTTestingLoop(campaign=campaign,
                                     disqualifying_properties=disqualifying_properties,
                                     start_year=start_year,
                                     hct_retention_rate=0.95,
                                     tvmap_consider_immediate_ART=coc.all_negative_time_value_map,
                                     hct_delay_to_next_test=hct_delay_to_next_test,
                                     hct_delay_to_next_test_node_ids=hct_delay_to_next_test_node_ids,
                                     hct_delay_to_next_test_node_names=hct_delay_to_next_test_node_names,
                                     node_ids=node_ids)

    @classmethod
    def add_state_TestingOnSymptomatic(cls,
                                       campaign: emod_api.campaign,
                                       start_year: float,
                                       node_ids: Union[List[int], None] = None):
        disqualifying_properties = [coc.CascadeState.LOST_FOREVER,
                                    coc.CascadeState.ON_ART,
                                    coc.CascadeState.LINKING_TO_ART,
                                    coc.CascadeState.ON_PRE_ART,
                                    coc.CascadeState.LINKING_TO_PRE_ART,
                                    coc.CascadeState.ART_STAGING]
        coc.add_state_TestingOnSymptomatic(campaign=campaign,
                                           disqualifying_properties=disqualifying_properties,
                                           start_year=start_year,
                                           node_ids=node_ids,
                                           tvmap_increased_symptomatic_presentation=coc.all_negative_time_value_map)

    @classmethod
    def add_state_ARTStagingDiagnosticTest(cls,
                                           campaign: emod_api.campaign,
                                           start_year: float,
                                           node_ids: Union[List[int], None] = None):
        disqualifying_properties = [coc.CascadeState.LOST_FOREVER,
                                    coc.CascadeState.ON_ART,
                                    coc.CascadeState.LINKING_TO_ART,
                                    coc.CascadeState.ON_PRE_ART,
                                    coc.CascadeState.LINKING_TO_PRE_ART]
        coc.add_state_ARTStagingDiagnosticTest(campaign=campaign,
                                               disqualifying_properties=disqualifying_properties,
                                               start_year=start_year,
                                               node_ids=node_ids)

    @classmethod
    def add_state_ARTStaging(cls,
                             campaign: emod_api.campaign,
                             start_year: float,
                             cd4_retention_rate: float = 1,
                             pre_staging_retention: float = 0.85,
                             node_ids: Union[List[int], None] = None):
        disqualifying_properties = [coc.CascadeState.LOST_FOREVER,
                                    coc.CascadeState.ON_ART,
                                    coc.CascadeState.LINKING_TO_ART,
                                    coc.CascadeState.ON_PRE_ART,
                                    coc.CascadeState.LINKING_TO_PRE_ART]
        coc.add_state_ARTStaging(campaign=campaign,
                                 disqualifying_properties=disqualifying_properties,
                                 start_year=start_year,
                                 node_ids=node_ids,
                                 pre_staging_retention=pre_staging_retention,
                                 cd4_retention_rate=cd4_retention_rate)

    @classmethod
    def add_state_LinkingToPreART(cls,
                                  campaign: emod_api.campaign,
                                  start_year: float,
                                  sigmoid_min: float = 0.7572242198,
                                  sigmoid_max: float = 0.9591484679,
                                  sigmoid_midyear: float = 2006.8336631523,
                                  sigmoid_rate: float = 1.0,
                                  node_ids: Union[List[int], None] = None):
        disqualifying_properties_pre_art_linking = [coc.CascadeState.LOST_FOREVER,
                                                    coc.CascadeState.ON_ART,
                                                    coc.CascadeState.LINKING_TO_ART,
                                                    coc.CascadeState.ON_PRE_ART]
        coc.add_state_LinkingToPreART(campaign=campaign,
                                      disqualifying_properties=disqualifying_properties_pre_art_linking,
                                      start_year=start_year,
                                      sigmoid_min=sigmoid_min,
                                      sigmoid_max=sigmoid_max,
                                      sigmoid_midyear=sigmoid_midyear,
                                      sigmoid_rate=sigmoid_rate,
                                      node_ids=node_ids)

    @classmethod
    def add_state_OnPreART(cls,
                           campaign: emod_api.campaign,
                           start_year: float,
                           pre_art_retention: float = 0.75,
                           node_ids: Union[List[int], None] = None):
        disqualifying_properties_pre_art = [coc.CascadeState.LOST_FOREVER,
                                            coc.CascadeState.ON_ART,
                                            coc.CascadeState.LINKING_TO_ART]
        coc.add_state_OnPreART(campaign=campaign,
                               node_ids=node_ids,
                               pre_art_retention=pre_art_retention,
                               disqualifying_properties=disqualifying_properties_pre_art,
                               start_year=start_year)

    @classmethod
    def add_state_LinkingToART(cls,
                               campaign: emod_api.campaign,
                               start_year: float,
                               sigmoid_min: float = 0.0,
                               sigmoid_max: float = 0.8507390283,
                               sigmoid_midyear: float = 1997.4462231708,
                               sigmoid_rate: float = 1.0,
                               node_ids: Union[List[int], None] = None):
        disqualifying_properties = [coc.CascadeState.LOST_FOREVER, coc.CascadeState.ON_ART]
        coc.add_state_LinkingToART(campaign=campaign,
                                   node_ids=node_ids,
                                   disqualifying_properties=disqualifying_properties,
                                   start_year=start_year,
                                   sigmoid_min=sigmoid_min,
                                   sigmoid_max=sigmoid_max,
                                   sigmoid_midyear=sigmoid_midyear,
                                   sigmoid_rate=sigmoid_rate)

    @classmethod
    def add_state_OnART(cls,
                        campaign: emod_api.campaign,
                        start_year: float,
                        art_reenrollment_willingness: float = 0.9,
                        immediate_art_rate: float = 0.1,
                        node_ids: Union[List[int], None] = None):
        tvmap_immediate_ART_restart = coc.all_negative_time_value_map
        tvmap_reconsider_lost_forever = coc.all_negative_time_value_map
        disqualifying_properties = [coc.CascadeState.LOST_FOREVER]
        coc.add_state_OnART(campaign=campaign,
                            art_reenrollment_willingness=art_reenrollment_willingness,
                            immediate_art_rate=immediate_art_rate,
                            node_ids=node_ids,
                            disqualifying_properties=disqualifying_properties,
                            start_year=start_year,
                            tvmap_immediate_ART_restart=tvmap_immediate_ART_restart,
                            tvmap_reconsider_lost_forever=tvmap_reconsider_lost_forever)

    @classmethod
    def add_state_LostForever(cls,
                              campaign: emod_api.campaign,
                              start_year: float,
                              node_ids: Union[List[int], None] = None):
        coc.add_state_LostForever(campaign=campaign,
                                  node_ids=node_ids,
                                  start_year=start_year)

build_campaign(campaign) classmethod

A method to pass into EMODTask to build campaign events for Emod.

Parameters:

Name Type Description Default
campaign campaign

The emod_api campaign object to be modified.

required

Returns: a campaign object

Source code in emodpy_hiv/country_model.py
@classmethod
def build_campaign(cls, campaign: emod_api.campaign) -> emod_api.campaign:
    """
    A method to pass into EMODTask to build campaign events for Emod.

    Args:
        campaign(emod_api.campaign): The emod_api campaign object to be modified.
    Returns:
        a campaign object
    """
    campaign = cls.initialize_campaign(schema_path=campaign.schema_path)
    calls = cls.get_campaign_parameterized_calls(campaign=campaign)
    cls._execute_parameterized_calls_on(obj=campaign, parameterized_calls=calls)
    return campaign

build_config(config) classmethod

A function that creates a config object that can be used with EMODTask.from_defaults().

Parameters:

Name Type Description Default
config ReadOnlyDict

the config object that will be modified. It has the following structure: config.parameters. , with being an attribute.

required

Returns: a config object

Source code in emodpy_hiv/country_model.py
@classmethod
def build_config(cls, config: ReadOnlyDict) -> ReadOnlyDict:
    """
    A function that creates a config object that can be used with
    EMODTask.from_defaults().

    Args:
        config(ReadOnlyDict): the config object that will be modified. It has the following structure:
            config.parameters.<parameter_name> , with <parameter_name> being an attribute.
    Returns:
        a config object
    """
    config = cls.initialize_config(schema_path=config["schema_path"])
    cls._execute_parameterized_calls_on(obj=config, parameterized_calls=cls.get_config_parameterized_calls(config=config))
    return config

build_demographics() classmethod

A function that configures the demographics for EMOD and can be used with EMODTask.from_defaults().

Returns:

Type Description
HIVDemographics

a demographics object

Source code in emodpy_hiv/country_model.py
@classmethod
def build_demographics(cls) -> HIVDemographics:
    """
    A function that configures the demographics for EMOD and can be used with
    EMODTask.from_defaults().

    Returns:
        a demographics object
    """
    demographics = cls.initialize_demographics()
    cls._execute_parameterized_calls_on(obj=demographics,
                                        parameterized_calls=cls.get_demographics_parameterized_calls(demographics=demographics))
    return demographics

build_reports(reporters) classmethod

Function that creates reports to be used in the experiment. The function must have Reporters object as the parameter and return that object. It is assumed that all the reporters come from the reporters that are part of EMOD main code. EMOD also supports reporters as custom plug-in dlls, however, not through the current emodpy system.

Parameters:

Name Type Description Default
reporters Reporters

The Reporters object to add reports to

required

Returns:

Type Description
Reporters

Reporters object

Source code in emodpy_hiv/country_model.py
@classmethod
def build_reports(cls, reporters: Reporters) -> Reporters:
    """
    Function that creates reports to be used in the experiment. The function must have Reporters
    object as the parameter and return that object. It is assumed that all the reporters come from the
    reporters that are part of EMOD main code. EMOD also supports reporters as custom plug-in dlls,
    however, not through the current emodpy system.

    Args:
        reporters: The Reporters object to add reports to

    Returns:
        Reporters object
    """
    return reporters

get_campaign_parameterized_calls(campaign) classmethod

Return a list of ParameterizedCall objects that will complete the configuration of an EMOD campaign object.

Args campaign: If not None, this will be the object that is updated

Returns:

Type Description
List[ParameterizedCall]

List of ParameterizedCall objects

Source code in emodpy_hiv/country_model.py
@classmethod
def get_campaign_parameterized_calls(cls, campaign: emod_api.campaign) -> List[ParameterizedCall]:
    """
    Return a list of ParameterizedCall objects that will complete the configuration of an
    EMOD campaign object.

    Args
        campaign: If not None, this will be the object that is updated

    Returns:
        List of ParameterizedCall objects
    """
    return []

get_config_parameterized_calls(config) classmethod

Return a list of ParameterizedCall objects that will complete the configuration of an EMOD config object.

Args config: The object to be updated when using instance methods with ParameterizedCall.

Returns:

Type Description
List[ParameterizedCall]

List of ParameterizedCall objects

Source code in emodpy_hiv/country_model.py
@classmethod
def get_config_parameterized_calls(cls, config: ReadOnlyDict) -> List[ParameterizedCall]:
    """
    Return a list of ParameterizedCall objects that will complete the configuration of an
    EMOD config object.

    Args
        config: The object to be updated when using instance methods with ParameterizedCall.

    Returns:
        List of ParameterizedCall objects
    """
    parameterized_calls = []

    def set_run_number(config, Run_Number: int = None):
        if Run_Number is not None:
            config.parameters.Run_Number = Run_Number

    pc = ParameterizedCall(func=set_run_number, hyperparameters={'Run_Number': None})
    parameterized_calls.append(pc)
    return parameterized_calls

get_demographics_parameterized_calls(demographics) classmethod

Return a list of ParameterizedCall objects that will complete the configuration of an EMOD demographics object.

Args demographics: If not None, this will be the object that is updated

Returns:

Type Description
List[ParameterizedCall]

List of ParameterizedCall objects

Source code in emodpy_hiv/country_model.py
@classmethod
def get_demographics_parameterized_calls(cls, demographics: HIVDemographics) -> List[ParameterizedCall]:
    """
    Return a list of ParameterizedCall objects that will complete the configuration of an
    EMOD demographics object.

    Args
        demographics: If not None, this will be the object that is updated

    Returns:
        List of ParameterizedCall objects
    """
    return []

initialize_campaign(schema_path) classmethod

Create the initial campaign object that will be modified by the ParameterizedCall objects from get_campaign_parameterized_calls()

Source code in emodpy_hiv/country_model.py
@classmethod
def initialize_campaign(cls, schema_path: Union[str, Path]) -> emod_api.campaign:
    """
    Create the initial campaign object that will be modified by the ParameterizedCall
    objects from **get_campaign_parameterized_calls()**
    """
    campaign = EMODTask.build_default_campaign(schema_path=schema_path)
    campaign.base_year = cls.base_year
    return campaign

initialize_config(schema_path) classmethod

Override this in the subclass to set the default values for the config object as needed.

Source code in emodpy_hiv/country_model.py
@classmethod
def initialize_config(cls, schema_path: Union[str, Path]) -> ReadOnlyDict:
    """
    Override this in the subclass to set the default values for the config object as needed.
    """
    config = EMODTask.build_default_config(schema_path=schema_path)
    return config

initialize_demographics() classmethod

Create the initial demographics object that will be modified by the ParameterizedCall objects from get_demographics_parameterized_calls()

Source code in emodpy_hiv/country_model.py
@classmethod
def initialize_demographics(cls) -> HIVDemographics:
    """
    Create the initial demographics object that will be modified by the ParameterizedCall
    objects from **get_demographics_parameterized_calls()**
    """
    demographics = HIVDemographics.from_template_node(pop=10000,
                                                      default_society_template="PFA-Southern-Africa")

    # TODO:  How to load default node attributes?

    return demographics

load_nchooser_distribution_data(file_path) staticmethod

Load target distribution data into a dataframe format that works for Nchooser and group by node_id. Args: file_path: path to the csv file that contains the data

Returns:

Name Type Description
dict dict

a dictionary that has node_id as the key and a dataframe as the value. The dataframe contains the

dict

distribution data for Nchooser.

Source code in emodpy_hiv/country_model.py
@staticmethod
def load_nchooser_distribution_data(file_path: str) -> dict:
    """
    Load target distribution data into a dataframe format that works for Nchooser and group by node_id.
    Args:
        file_path: path to the csv file that contains the data

    Returns:
        dict: a dictionary that has node_id as the key and a dataframe as the value. The dataframe contains the
        distribution data for Nchooser.

    """
    data = pd.read_csv(file_path)
    data_dict = defaultdict(pd.DataFrame)
    for node_id in pd.unique(data['node_set']):
        node_data = data[data['node_set'] == node_id]
        node_dict = {'year': [], 'min_age': [], 'max_age': [], 'n_circumcisions': []}
        for year in pd.unique(node_data['year']):
            year_data = node_data[node_data['year'] == year]
            for _, row in year_data.iterrows():
                node_dict['year'].append(year)
                node_dict['min_age'].append(float(row['age_bin'].split(':')[0].replace('[', '')))
                node_dict['max_age'].append(float(row['age_bin'].split(':')[1].replace(')', '')) - 0.00001)
                node_dict['n_circumcisions'].append(int(row['n_circumcisions']))
        data_dict[int(node_id)] = pd.DataFrame(node_dict)
    return data_dict

get_country_class(country_class_name)

Import the countries module and return the class of the country.

Parameters:

Name Type Description Default
country_class_name str

The name of the country to get the class for. The name is expected to be exactly like like it is in its module. Countries with more than one word are expected to have an underscore ('_') between the words.

Examples of naming convention: - Zambia should be located in the module emodpy_hiv.countries.zambia.zambia - South Africa should have a class called South_Africa and be in a module called emodpy_hiv.countries.south_africa.south_africa

required
Source code in emodpy_hiv/country_model.py
def get_country_class(country_class_name: str):
    """
    Import the countries module and return the class of the country.

    Args:
        country_class_name:
            The name of the country to get the class for.  The name is expected to be exactly like
            like it is in its module.  Countries with more than one word are expected to have an
            underscore ('_') between the words.

            Examples of naming convention:
            - Zambia should be located in the module emodpy_hiv.countries.zambia.zambia
            - South Africa should have a class called South_Africa and be in a module called
            emodpy_hiv.countries.south_africa.south_africa
    """
    module_name = f"emodpy_hiv.countries.{country_class_name.lower()}.{country_class_name.lower()}"
    module_name = module_name.replace(" ", "_")
    country_module = importlib.import_module(module_name)
    country_class = getattr(country_module, country_class_name)
    return country_class