Skip to content

Student dorm

StudentDorm

Bases: Group

Source code in june/groups/student_dorm.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
class StudentDorm(Group):
    """ """
    class SubgroupType(IntEnum):
        """ """
        residents = 0
        visitors = 1
    """
    Represents a student dormitory with its residents and visitors.

    Parameters
    ----------
    area : Area
        The area the student dorm belongs to.
    age_proportions : dict
        The age distribution proportions for the student dorm.
    """

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

    def __init__(
        self,
        area: Area = None,
        registered_members_ids: dict = None,
        age_proportions: dict = None,
        target_allocations: dict = None,
    ):
        super().__init__()
        self.spec = "student_dorm"
        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_16_24': 0.85,    # Default to mostly young adults
            'prop_25_34': 0.15,    # Some graduate students
            '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_16_24': 0,
            'n_25_34': 0,
            'n_35_49': 0,
            'n_50_64': 0,
            'n_65_99': 0
        }

    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/student_dorm.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/student_dorm.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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/student_dorm.py
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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/student_dorm.py
145
146
147
148
149
150
151
152
153
154
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/student_dorm.py
111
112
113
114
115
116
117
118
119
120
def quarantine(self, time, quarantine_days, household_compliance):
    """

    Args:
        time: 
        quarantine_days: 
        household_compliance: 

    """
    return True

StudentDormError

Bases: BaseException

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

StudentDorms

Bases: Supergroup

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

    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,
    ) -> "StudentDorms":
        """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 StudentDormError("Empty geography!")
        return cls.for_areas(areas, data_file)

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

        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
        student_dorm_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
            student_dorm_df = student_dorm_df[student_dorm_df['area'].isin(area_names)]

        student_dorms = []
        logger.info(
            f"There are {len(student_dorm_df)} student dorms 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 student_dorm_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_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_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']))
                }

                student_dorm = cls.venue_class(
                    area=area,
                    age_proportions=age_proportions,
                    target_allocations=target_allocations
                )
                student_dorms.append(student_dorm)
                area.student_dorms.append(student_dorm)

        # Visualization - Sample 5 student dorms for inspection
        sample_student_dorms = [
            {
                "| Dorm ID": student_dorm.id,
                "| Area": student_dorm.area.name if student_dorm.area else "Unknown",
                "| Target Total": student_dorm.target_allocations['n_total'],
                "| Target 16-24": student_dorm.target_allocations['n_16_24'],
                "| Target 25-34": student_dorm.target_allocations['n_25_34'],
                "| Prop 16-24": f"{student_dorm.age_proportions['prop_16_24']:.2f}",
                "| Prop 25-34": f"{student_dorm.age_proportions['prop_25_34']:.2f}",
                "| Coordinates": student_dorm.coordinates if student_dorm.area else "Unknown",
            }
            for student_dorm in random.sample(student_dorms, min(5, len(student_dorms)))
        ]

        df_student_dorms = pd.DataFrame(sample_student_dorms)
        print("\n===== Sample of Created Student Dorms =====")
        print(df_student_dorms)
        return cls(student_dorms)

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/student_dorm.py
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
@classmethod
def for_areas(
    cls,
    areas: List[Area],
    data_file: str = default_data_filename,
) -> "StudentDorms":
    """

    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
    student_dorm_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
        student_dorm_df = student_dorm_df[student_dorm_df['area'].isin(area_names)]

    student_dorms = []
    logger.info(
        f"There are {len(student_dorm_df)} student dorms 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 student_dorm_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_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_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']))
            }

            student_dorm = cls.venue_class(
                area=area,
                age_proportions=age_proportions,
                target_allocations=target_allocations
            )
            student_dorms.append(student_dorm)
            area.student_dorms.append(student_dorm)

    # Visualization - Sample 5 student dorms for inspection
    sample_student_dorms = [
        {
            "| Dorm ID": student_dorm.id,
            "| Area": student_dorm.area.name if student_dorm.area else "Unknown",
            "| Target Total": student_dorm.target_allocations['n_total'],
            "| Target 16-24": student_dorm.target_allocations['n_16_24'],
            "| Target 25-34": student_dorm.target_allocations['n_25_34'],
            "| Prop 16-24": f"{student_dorm.age_proportions['prop_16_24']:.2f}",
            "| Prop 25-34": f"{student_dorm.age_proportions['prop_25_34']:.2f}",
            "| Coordinates": student_dorm.coordinates if student_dorm.area else "Unknown",
        }
        for student_dorm in random.sample(student_dorms, min(5, len(student_dorms)))
    ]

    df_student_dorms = pd.DataFrame(sample_student_dorms)
    print("\n===== Sample of Created Student Dorms =====")
    print(df_student_dorms)
    return cls(student_dorms)

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 StudentDorms

An instance containing all created student dorms.

Source code in june/groups/student_dorm.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
@classmethod
def for_geography(
    cls,
    geography: Geography,
    data_file: str = default_data_filename,
) -> "StudentDorms":
    """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 StudentDormError("Empty geography!")
    return cls.for_areas(areas, data_file)