Skip to content

Boarding school

BoardingSchool

Bases: Group

Source code in june/groups/boarding_school.py
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
class BoardingSchool(Group):
    """ """
    class SubgroupType(IntEnum):
        """ """
        residents = 0
        visitors = 1
    """
    Represents a boarding school with its residents.

    Parameters
    ----------
    area : Area
        The area the student dorm belongs to.
    age_proportions : dict
        The age distribution proportions for the student dorm.
    gender : str
        The gender type of the boarding school ('boys', 'girls', 'mixed').
        Defaults to 'mixed' if not specified.
    """

    __slots__ = ("spec", "area", "quarantine_starting_date", "registered_members_ids", "age_proportions", "target_allocations", "gender")

    def __init__(
        self,
        area: Area = None,
        registered_members_ids: dict = None,
        age_proportions: dict = None,
        target_allocations: dict = None,
        gender: str = "mixed",
    ):
        super().__init__()
        self.spec = "boarding_school"
        self.area = area
        self.quarantine_starting_date = None
        self.registered_members_ids = registered_members_ids if registered_members_ids is not None else {}
        self.age_proportions = age_proportions if age_proportions is not None else {
            'prop_0_15': 0.85,
            'prop_16_24': 0.15,
            'prop_25_34': 0.0,
            'prop_35_49': 0.0,
            'prop_50_64': 0.0,
            'prop_65_99': 0.0
        }
        self.target_allocations = target_allocations if target_allocations is not None else {
            'n_total': 0,
            'n_0_15': 0,
            'n_16_24': 0,
            'n_25_34': 0,
            'n_35_49': 0,
            'n_50_64': 0,
            'n_65_99': 0
        }
        self.gender = gender.lower() if gender else "mixed"

    def add(self, person, subgroup_type, activity: str = "residence"):
        """

        Args:
            person: 
            subgroup_type: 
            activity (str, optional): (Default value = "residence")

        """
        if activity == "leisure":
            super().add(
                person, subgroup_type=self.SubgroupType.visitors, activity="leisure"
            )
        else:
            super().add(person, subgroup_type=subgroup_type, activity=activity)

    def add_to_registered_members(self, person_id, subgroup_type=0):
        """Add a person to the registered members list for a specific subgroup.

        Args:
            person_id (int): The ID of the person to add
            subgroup_type (int, optional, optional): The subgroup to add the person to (default: 0)

        """
        # Create the subgroup if it doesn't exist
        if subgroup_type not in self.registered_members_ids:
            self.registered_members_ids[subgroup_type] = []

        # Add the person if not already in the list
        if person_id not in self.registered_members_ids[subgroup_type]:
            self.registered_members_ids[subgroup_type].append(person_id)


    @property
    def residents(self):
        """ """
        return self.subgroups[self.SubgroupType.residents]

    @property
    def visitors(self):
        """ """
        return self.subgroups[self.SubgroupType.visitors]

    def quarantine(self, time, quarantine_days, household_compliance):
        """

        Args:
            time: 
            quarantine_days: 
            household_compliance: 

        """
        return True

    @property
    def coordinates(self):
        """ """
        return self.area.coordinates

    @property
    def super_area(self):
        """ """
        if self.area is None:
            return None
        else:
            return self.area.super_area

    @property
    def households_to_visit(self):
        """ """
        return None

    @property
    def student_dorms_to_visit(self):
        """ """
        return None

    def get_leisure_subgroup(self, person, subgroup_type, to_send_abroad):
        """

        Args:
            person: 
            subgroup_type: 
            to_send_abroad: 

        """
        return self[self.SubgroupType.visitors]

    @property
    def type(self):
        """ """
        return "student_dorm"

coordinates property

households_to_visit property

residents property

student_dorms_to_visit property

super_area property

type property

visitors property

SubgroupType

Bases: IntEnum

Source code in june/groups/boarding_school.py
23
24
25
26
class SubgroupType(IntEnum):
    """ """
    residents = 0
    visitors = 1

add(person, subgroup_type, activity='residence')

Parameters:

Name Type Description Default
person
required
subgroup_type
required
activity str

(Default value = "residence")

'residence'
Source code in june/groups/boarding_school.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def add(self, person, subgroup_type, activity: str = "residence"):
    """

    Args:
        person: 
        subgroup_type: 
        activity (str, optional): (Default value = "residence")

    """
    if activity == "leisure":
        super().add(
            person, subgroup_type=self.SubgroupType.visitors, activity="leisure"
        )
    else:
        super().add(person, subgroup_type=subgroup_type, activity=activity)

add_to_registered_members(person_id, subgroup_type=0)

Add a person to the registered members list for a specific subgroup.

Parameters:

Name Type Description Default
person_id int

The ID of the person to add

required
subgroup_type (int, optional)

The subgroup to add the person to (default: 0)

0
Source code in june/groups/boarding_school.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def add_to_registered_members(self, person_id, subgroup_type=0):
    """Add a person to the registered members list for a specific subgroup.

    Args:
        person_id (int): The ID of the person to add
        subgroup_type (int, optional, optional): The subgroup to add the person to (default: 0)

    """
    # Create the subgroup if it doesn't exist
    if subgroup_type not in self.registered_members_ids:
        self.registered_members_ids[subgroup_type] = []

    # Add the person if not already in the list
    if person_id not in self.registered_members_ids[subgroup_type]:
        self.registered_members_ids[subgroup_type].append(person_id)

get_leisure_subgroup(person, subgroup_type, to_send_abroad)

Parameters:

Name Type Description Default
person
required
subgroup_type
required
to_send_abroad
required
Source code in june/groups/boarding_school.py
152
153
154
155
156
157
158
159
160
161
def get_leisure_subgroup(self, person, subgroup_type, to_send_abroad):
    """

    Args:
        person: 
        subgroup_type: 
        to_send_abroad: 

    """
    return self[self.SubgroupType.visitors]

quarantine(time, quarantine_days, household_compliance)

Parameters:

Name Type Description Default
time
required
quarantine_days
required
household_compliance
required
Source code in june/groups/boarding_school.py
118
119
120
121
122
123
124
125
126
127
def quarantine(self, time, quarantine_days, household_compliance):
    """

    Args:
        time: 
        quarantine_days: 
        household_compliance: 

    """
    return True

BoardingSchoolError

Bases: BaseException

Source code in june/groups/boarding_school.py
16
17
18
class BoardingSchoolError(BaseException):
    """ """
    pass

BoardingSchools

Bases: Supergroup

Source code in june/groups/boarding_school.py
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
class BoardingSchools(Supergroup):
    """ """
    venue_class = BoardingSchool

    def __init__(self, student_dorms: List[venue_class]):
        super().__init__(members=student_dorms)

    @classmethod
    def for_geography(
        cls,
        geography: Geography,
        data_file: str = default_data_filename,
    ) -> "BoardingSchools":
        """Initialises student dorms from geography.

        Args:
            geography (Geography): The geography object with areas for initialising student dorms.
            data_file (str, optional): Path to the student dorm data file. (Default value = default_data_filename)

        Returns:
            StudentDorms: An instance containing all created student dorms.

        """
        areas = geography.areas
        if not areas:
            raise BoardingSchoolError("Empty geography!")
        return cls.for_areas(areas, data_file)

    @classmethod
    def for_areas(
        cls,
        areas: List[Area],
        data_file: str = default_data_filename,
    ) -> "BoardingSchools":
        """

        Args:
            areas (List[Area]): list of areas for which to create populations
            data_file (str, optional): The path to the data file (CSV with columns: area, super_area, Type, age group proportions) (Default value = default_data_filename)

        """
        # Read the CSV file with age proportions
        boarding_school_df = pd.read_csv(data_file)

        if areas:
            area_names = [area.name for area in areas]
            # Filter student dorms that are in the areas of interest
            boarding_school_df = boarding_school_df[boarding_school_df['area'].isin(area_names)]

        boarding_schools = []
        logger.info(
            f"There are {len(boarding_school_df)} boarding schools in this geography."
        )

        # Create a mapping of area names to area objects for quick lookup
        area_dict = {area.name: area for area in areas}

        # Create individual student dorms for each row in the CSV
        for _, row in boarding_school_df.iterrows():
            area_name = row['area']

            if area_name in area_dict:
                area = area_dict[area_name]

                # Extract age proportions from the CSV
                age_proportions = {
                    'prop_0_15': float(row['prop_0_15']),
                    'prop_16_24': float(row['prop_16_24']),
                    'prop_25_34': float(row['prop_25_34']),
                    'prop_35_49': float(row['prop_35_49']),
                    'prop_50_64': float(row['prop_50_64']),
                    'prop_65_99': float(row['prop_65_99'])
                }

                # Extract target allocations from the CSV
                target_allocations = {
                    'n_total': int(float(row['n_total'])),
                    'n_0_15': int(float(row['n_0_15'])),
                    'n_16_24': int(float(row['n_16_24'])),
                    'n_25_34': int(float(row['n_25_34'])),
                    'n_35_49': int(float(row['n_35_49'])),
                    'n_50_64': int(float(row['n_50_64'])),
                    'n_65_99': int(float(row['n_65_99']))
                }

                # Extract gender information, default to "mixed" if not present
                gender = row.get('Gender', 'mixed')
                if pd.isna(gender) or gender == '':
                    gender = 'mixed'

                boarding_school = cls.venue_class(
                    area=area,
                    age_proportions=age_proportions,
                    target_allocations=target_allocations,
                    gender=gender
                )
                boarding_schools.append(boarding_school)

        # Visualization - Sample 5 boarding schools for inspection
        sample_boarding_schools = [
            {
                "| B.S. ID": student_dorm.id,
                "| Area": student_dorm.area.name if student_dorm.area else "Unknown",
                "| Gender": student_dorm.gender,
                "| Target Total": student_dorm.target_allocations['n_total'],
                "| Target 16-24": student_dorm.target_allocations['n_16_24'],
                "| Prop 16-24": f"{student_dorm.age_proportions['prop_16_24']:.2f}",
                "| Coordinates": student_dorm.coordinates if student_dorm.area else "Unknown",
            }
            for student_dorm in random.sample(boarding_schools, min(5, len(boarding_schools)))
        ]

        df_boarding_schools = pd.DataFrame(sample_boarding_schools)
        print("\n===== Sample of Created Boarding Schools =====")
        print(df_boarding_schools)
        return cls(boarding_schools)

for_areas(areas, data_file=default_data_filename) classmethod

Parameters:

Name Type Description Default
areas List[Area]

list of areas for which to create populations

required
data_file str

The path to the data file (CSV with columns: area, super_area, Type, age group proportions) (Default value = default_data_filename)

default_data_filename
Source code in june/groups/boarding_school.py
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
@classmethod
def for_areas(
    cls,
    areas: List[Area],
    data_file: str = default_data_filename,
) -> "BoardingSchools":
    """

    Args:
        areas (List[Area]): list of areas for which to create populations
        data_file (str, optional): The path to the data file (CSV with columns: area, super_area, Type, age group proportions) (Default value = default_data_filename)

    """
    # Read the CSV file with age proportions
    boarding_school_df = pd.read_csv(data_file)

    if areas:
        area_names = [area.name for area in areas]
        # Filter student dorms that are in the areas of interest
        boarding_school_df = boarding_school_df[boarding_school_df['area'].isin(area_names)]

    boarding_schools = []
    logger.info(
        f"There are {len(boarding_school_df)} boarding schools in this geography."
    )

    # Create a mapping of area names to area objects for quick lookup
    area_dict = {area.name: area for area in areas}

    # Create individual student dorms for each row in the CSV
    for _, row in boarding_school_df.iterrows():
        area_name = row['area']

        if area_name in area_dict:
            area = area_dict[area_name]

            # Extract age proportions from the CSV
            age_proportions = {
                'prop_0_15': float(row['prop_0_15']),
                'prop_16_24': float(row['prop_16_24']),
                'prop_25_34': float(row['prop_25_34']),
                'prop_35_49': float(row['prop_35_49']),
                'prop_50_64': float(row['prop_50_64']),
                'prop_65_99': float(row['prop_65_99'])
            }

            # Extract target allocations from the CSV
            target_allocations = {
                'n_total': int(float(row['n_total'])),
                'n_0_15': int(float(row['n_0_15'])),
                'n_16_24': int(float(row['n_16_24'])),
                'n_25_34': int(float(row['n_25_34'])),
                'n_35_49': int(float(row['n_35_49'])),
                'n_50_64': int(float(row['n_50_64'])),
                'n_65_99': int(float(row['n_65_99']))
            }

            # Extract gender information, default to "mixed" if not present
            gender = row.get('Gender', 'mixed')
            if pd.isna(gender) or gender == '':
                gender = 'mixed'

            boarding_school = cls.venue_class(
                area=area,
                age_proportions=age_proportions,
                target_allocations=target_allocations,
                gender=gender
            )
            boarding_schools.append(boarding_school)

    # Visualization - Sample 5 boarding schools for inspection
    sample_boarding_schools = [
        {
            "| B.S. ID": student_dorm.id,
            "| Area": student_dorm.area.name if student_dorm.area else "Unknown",
            "| Gender": student_dorm.gender,
            "| Target Total": student_dorm.target_allocations['n_total'],
            "| Target 16-24": student_dorm.target_allocations['n_16_24'],
            "| Prop 16-24": f"{student_dorm.age_proportions['prop_16_24']:.2f}",
            "| Coordinates": student_dorm.coordinates if student_dorm.area else "Unknown",
        }
        for student_dorm in random.sample(boarding_schools, min(5, len(boarding_schools)))
    ]

    df_boarding_schools = pd.DataFrame(sample_boarding_schools)
    print("\n===== Sample of Created Boarding Schools =====")
    print(df_boarding_schools)
    return cls(boarding_schools)

for_geography(geography, data_file=default_data_filename) classmethod

Initialises student dorms from geography.

Parameters:

Name Type Description Default
geography Geography

The geography object with areas for initialising student dorms.

required
data_file str

Path to the student dorm data file. (Default value = default_data_filename)

default_data_filename

Returns:

Name Type Description
StudentDorms BoardingSchools

An instance containing all created student dorms.

Source code in june/groups/boarding_school.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
@classmethod
def for_geography(
    cls,
    geography: Geography,
    data_file: str = default_data_filename,
) -> "BoardingSchools":
    """Initialises student dorms from geography.

    Args:
        geography (Geography): The geography object with areas for initialising student dorms.
        data_file (str, optional): Path to the student dorm data file. (Default value = default_data_filename)

    Returns:
        StudentDorms: An instance containing all created student dorms.

    """
    areas = geography.areas
    if not areas:
        raise BoardingSchoolError("Empty geography!")
    return cls.for_areas(areas, data_file)