Skip to content

Household saver

load_households_from_hdf5(file_path, chunk_size=50000, domain_super_areas=None, config_filename=None)

Loads households from an hdf5 file located at file_path. Note that this object will not be ready to use, as the links to object instances of other classes need to be restored first. This function should be rarely be called oustide world.py

Parameters:

Name Type Description Default
file_path str
required
chunk_size

(Default value = 50000)

50000
domain_super_areas

(Default value = None)

None
config_filename

(Default value = None)

None
Source code in june/hdf5_savers/household_saver.py
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
def load_households_from_hdf5(
    file_path: str, chunk_size=50000, domain_super_areas=None, config_filename=None
):
    """Loads households from an hdf5 file located at ``file_path``.
    Note that this object will not be ready to use, as the links to
    object instances of other classes need to be restored first.
    This function should be rarely be called oustide world.py

    Args:
        file_path (str): 
        chunk_size: (Default value = 50000)
        domain_super_areas: (Default value = None)
        config_filename: (Default value = None)

    """

    Household_Class = Household
    disease_config = GlobalContext.get_disease_config()
    Household_Class.subgroup_params = SubgroupParams.from_disease_config(disease_config)

    logger.info("loading households...")
    households_list = []
    with h5py.File(file_path, "r", libver="latest", swmr=True) as f:
        households = f["households"]
        n_households = households.attrs["n_households"]
        n_chunks = int(np.ceil(n_households / chunk_size))

        logger.info(f"Loading {n_households:,} households in {n_chunks} chunks of {chunk_size:,}")

        # Check if registered members data exists
        has_subgroup_data = "registered_members_subgroups" in households
        subgroup_counts = {}
        subgroup_members = {}
        subgroup_cumulative_counts = {}

        if has_subgroup_data:
            # Get all subgroups
            subgroups = read_dataset(households["registered_members_subgroups"], 0, households["registered_members_subgroups"].shape[0])

            # For each subgroup, prepare the count and flattened arrays
            for subgroup_id in subgroups:
                sg_key = f"registered_members_count_sg{subgroup_id}"
                ids_key = f"registered_members_ids_sg{subgroup_id}"

                if sg_key in households and ids_key in households:
                    # Read counts for this subgroup - handle case where dataset is smaller than total households
                    sg_dataset_size = households[sg_key].shape[0]
                    if sg_dataset_size < n_households:
                        # Some households (like flexible) don't have this subgroup data
                        partial_counts = read_dataset(households[sg_key], 0, sg_dataset_size)
                        # Pad with zeros for remaining households
                        counts = np.zeros(n_households, dtype=np.int64)
                        counts[:sg_dataset_size] = partial_counts
                    else:
                        counts = read_dataset(households[sg_key], 0, n_households)
                    subgroup_counts[subgroup_id] = counts

                    # Calculate cumulative counts for this subgroup
                    cumulative = np.concatenate(([0], np.cumsum(counts)))
                    subgroup_cumulative_counts[subgroup_id] = cumulative

                    # Read flattened member IDs for this subgroup
                    if households[ids_key].shape[0] > 0:
                        member_ids = read_dataset(households[ids_key], 0, households[ids_key].shape[0])
                        subgroup_members[subgroup_id] = member_ids
                    else:
                        subgroup_members[subgroup_id] = np.array([])
        for chunk in range(n_chunks):
            idx1 = chunk * chunk_size
            idx2 = min((chunk + 1) * chunk_size, n_households)
            logger.info(f"Loading chunk {chunk + 1}/{n_chunks} ({idx1:,} - {idx2:,})")
            length = idx2 - idx1
            ids = read_dataset(households["id"], idx1, idx2)
            types = read_dataset(households["type"], idx1, idx2)
            composition_types = read_dataset(households["composition_type"], idx1, idx2)
            max_sizes = read_dataset(households["max_size"], idx1, idx2)
            super_areas = read_dataset(households["super_area"], idx1, idx2)
            for k in range(length):
                if domain_super_areas is not None:
                    super_area = super_areas[k]
                    if super_area == nan_integer:
                        raise ValueError(
                            "if ``domain_super_areas`` is True, I expect not Nones super areas."
                        )
                    if super_area not in domain_super_areas:
                        continue

                # Get registered_members_ids for this household if available
                registered_members_dict = {}

                if has_subgroup_data and subgroups.size > 0:
                    household_index = idx1 + k

                    # Get members for each subgroup
                    for subgroup_id in subgroups:
                        if subgroup_id in subgroup_counts and subgroup_id in subgroup_members:
                            n_members = subgroup_counts[subgroup_id][household_index]

                            if n_members > 0 and len(subgroup_members[subgroup_id]) > 0:
                                start_idx = subgroup_cumulative_counts[subgroup_id][household_index]
                                end_idx = subgroup_cumulative_counts[subgroup_id][household_index + 1]

                                if start_idx < len(subgroup_members[subgroup_id]):
                                    registered_members_dict[int(subgroup_id)] = subgroup_members[subgroup_id][start_idx:end_idx].tolist()

                household = Household_Class(
                    area=None,
                    type=types[k].decode(),
                    max_size=max_sizes[k],
                    composition_type=composition_types[k].decode(),
                    registered_members_ids=registered_members_dict,
                )
                households_list.append(household)
                household.id = ids[k]
    return Households(households_list)

restore_households_properties_from_hdf5(world, file_path, chunk_size=50000, domain_super_areas=None, super_areas_to_domain_dict=None)

Loads households from an hdf5 file located at file_path. Note that this object will not be ready to use, as the links to object instances of other classes need to be restored first. This function should be rarely be called oustide world.py

Parameters:

Name Type Description Default
world World
required
file_path str
required
chunk_size

(Default value = 50000)

50000
domain_super_areas

(Default value = None)

None
super_areas_to_domain_dict dict

(Default value = None)

None
Source code in june/hdf5_savers/household_saver.py
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
def restore_households_properties_from_hdf5(
    world: World,
    file_path: str,
    chunk_size=50000,
    domain_super_areas=None,
    super_areas_to_domain_dict: dict = None,
):
    """Loads households from an hdf5 file located at ``file_path``.
    Note that this object will not be ready to use, as the links to
    object instances of other classes need to be restored first.
    This function should be rarely be called oustide world.py

    Args:
        world (World): 
        file_path (str): 
        chunk_size: (Default value = 50000)
        domain_super_areas: (Default value = None)
        super_areas_to_domain_dict (dict, optional): (Default value = None)

    """
    logger.info("restoring households...")
    with h5py.File(file_path, "r", libver="latest", swmr=True) as f:
        households = f["households"]
        n_households = households.attrs["n_households"]
        n_chunks = int(np.ceil(n_households / chunk_size))

        logger.info(f"Restoring {n_households:,} households in {n_chunks} chunks of {chunk_size:,}")

        # Check if registered members data exists
        has_subgroup_data = "registered_members_subgroups" in households
        subgroup_counts = {}
        subgroup_members = {}
        subgroup_cumulative_counts = {}

        if has_subgroup_data:
            # Get all subgroups
            subgroups = read_dataset(households["registered_members_subgroups"], 0, households["registered_members_subgroups"].shape[0])

            # For each subgroup, prepare the count and flattened arrays
            for subgroup_id in subgroups:
                sg_key = f"registered_members_count_sg{subgroup_id}"
                ids_key = f"registered_members_ids_sg{subgroup_id}"

                if sg_key in households and ids_key in households:
                    # Read counts for this subgroup - handle case where dataset is smaller than total households
                    sg_dataset_size = households[sg_key].shape[0]
                    if sg_dataset_size < n_households:
                        # Some households (like flexible) don't have this subgroup data
                        partial_counts = read_dataset(households[sg_key], 0, sg_dataset_size)
                        # Pad with zeros for remaining households
                        counts = np.zeros(n_households, dtype=np.int64)
                        counts[:sg_dataset_size] = partial_counts
                    else:
                        counts = read_dataset(households[sg_key], 0, n_households)
                    subgroup_counts[subgroup_id] = counts

                    # Calculate cumulative counts for this subgroup
                    cumulative = np.concatenate(([0], np.cumsum(counts)))
                    subgroup_cumulative_counts[subgroup_id] = cumulative

                    # Read flattened member IDs for this subgroup
                    if households[ids_key].shape[0] > 0:
                        member_ids = read_dataset(households[ids_key], 0, households[ids_key].shape[0])
                        subgroup_members[subgroup_id] = member_ids
                    else:
                        subgroup_members[subgroup_id] = np.array([])
        for chunk in range(n_chunks):
            idx1 = chunk * chunk_size
            idx2 = min((chunk + 1) * chunk_size, n_households)
            logger.info(f"Restoring chunk {chunk + 1}/{n_chunks} ({idx1:,} - {idx2:,})")
            length = idx2 - idx1
            ids = read_dataset(households["id"], idx1, idx2)
            super_areas = read_dataset(households["super_area"], idx1, idx2)
            areas = read_dataset(households["area"], idx1, idx2)
            residences_to_visit_ids = read_dataset(
                households["residences_to_visit_ids"], idx1, idx2
            )
            residences_to_visit_specs = read_dataset(
                households["residences_to_visit_specs"], idx1, idx2
            )
            residences_to_visit_super_areas = read_dataset(
                households["residences_to_visit_super_areas"], idx1, idx2
            )
            for k in range(length):
                if domain_super_areas is not None:
                    """
                    Note: if the relatives live outside the super area this will fail.
                    """
                    super_area = super_areas[k]
                    if super_area == nan_integer:
                        raise ValueError(
                            "if ``domain_super_areas`` is True, I expect not Nones super areas."
                        )
                    if super_area not in domain_super_areas:
                        continue
                household = world.households.get_from_id(ids[k])
                area = world.areas.get_from_id(areas[k])
                household.area = area
                area.households.append(household)
                household.residents = tuple(household.people)

                # Restore registered_members_ids if available
                if has_subgroup_data and subgroups.size > 0:
                    household_index = idx1 + k
                    registered_members_dict = {}

                    # Process each subgroup
                    for subgroup_id in subgroups:
                        if subgroup_id in subgroup_counts and subgroup_id in subgroup_members:
                            n_members = subgroup_counts[subgroup_id][household_index]

                            if n_members > 0 and len(subgroup_members[subgroup_id]) > 0:
                                start_idx = subgroup_cumulative_counts[subgroup_id][household_index]
                                end_idx = subgroup_cumulative_counts[subgroup_id][household_index + 1]

                                if start_idx < len(subgroup_members[subgroup_id]):
                                    registered_members_dict[int(subgroup_id)] = subgroup_members[subgroup_id][start_idx:end_idx].tolist()

                    # Always use dictionary format
                    household.registered_members_ids = registered_members_dict
                # visits
                visit_ids = residences_to_visit_ids[k]
                if visit_ids[0] == nan_integer:
                    continue
                visit_specs = residences_to_visit_specs[k]
                visit_super_areas = residences_to_visit_super_areas[k]
                for visit_id, visit_spec, visit_super_area in zip(
                    visit_ids, visit_specs, visit_super_areas
                ):
                    if (
                        domain_super_areas is not None
                        and visit_super_area not in domain_super_areas
                    ):
                        residence = ExternalGroup(
                            id=visit_id,
                            domain_id=super_areas_to_domain_dict[visit_super_area],
                            spec=visit_spec.decode(),
                            region_name=None,
                        )
                    else:
                        visit_spec = visit_spec.decode()
                        if visit_spec == "household":
                            residence = world.households.get_from_id(visit_id)
                        elif visit_spec == "care_home":
                            residence = world.care_homes.get_from_id(visit_id)
                    household.residences_to_visit[visit_spec] = (
                        *household.residences_to_visit[visit_spec],
                        residence,
                    )

save_households_to_hdf5(households, file_path, chunk_size=500000)

Saves the households object to hdf5 format file file_path. Currently for each person, the following values are stored: - id, n_beds, n_icu_beds, super_area, coordinates

Parameters:

Name Type Description Default
households Households
required
file_path str

path of the saved hdf5 file

required
chunk_size int

number of people to save at a time. Note that they have to be copied to be saved,

500000

so keep the number below 1e6. (Default value = 500000)

Source code in june/hdf5_savers/household_saver.py
 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
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
def save_households_to_hdf5(
    households: Households, file_path: str, chunk_size: int = 500000
):
    """Saves the households object to hdf5 format file ``file_path``. Currently for each person,
    the following values are stored:
    - id, n_beds, n_icu_beds, super_area, coordinates

    Args:
        households (Households): 
        file_path (str): path of the saved hdf5 file
        chunk_size (int, optional): number of people to save at a time. Note that they have to be copied to be saved,
    so keep the number below 1e6. (Default value = 500000)

    """
    n_households = len(households)
    n_chunks = int(np.ceil(n_households / chunk_size))

    logger.info(f"Saving {n_households:,} households in {n_chunks} chunks of {chunk_size:,}")

    with h5py.File(file_path, "a") as f:
        households_dset = f.create_group("households")
        for chunk in range(n_chunks):
            logger.info(f"Processing chunk {chunk + 1}/{n_chunks} ({chunk * chunk_size:,} - {min((chunk + 1) * chunk_size, n_households):,})")
            idx1 = chunk * chunk_size
            idx2 = min((chunk + 1) * chunk_size, n_households)
            ids = []
            areas = []
            super_areas = []
            types = []
            composition_types = []
            max_sizes = []
            registered_members_ids = []  # Add for storing registered_members_ids
            for household in households[idx1:idx2]:
                ids.append(household.id)
                if household.area is None:
                    areas.append(nan_integer)
                    super_areas.append(nan_integer)
                else:
                    areas.append(household.area.id)
                    super_areas.append(household.super_area.id)
                if household.type is None:
                    types.append(" ".encode("ascii", "ignore"))
                else:
                    types.append(household.type.encode("ascii", "ignore"))
                if household.composition_type is None:
                    composition_types.append(" ".encode("ascii", "ignore"))
                else:
                    composition_types.append(
                        household.composition_type.encode("ascii", "ignore")
                    )
                max_sizes.append(household.max_size)

                # Process registered_members_ids
                household_registered_members = {}
                if hasattr(household, 'registered_members_ids') and household.registered_members_ids is not None:
                    for subgroup_id, members in household.registered_members_ids.items():
                        household_registered_members[subgroup_id] = np.array(members, dtype=np.int64)
                registered_members_ids.append(household_registered_members)

            ids = np.array(ids, dtype=np.int64)
            areas = np.array(areas, dtype=np.int64)
            super_areas = np.array(super_areas, dtype=np.int64)
            types = np.array(types, dtype="S20")
            composition_types = np.array(composition_types, dtype="S20")
            max_sizes = np.array(max_sizes, dtype=np.float64)

            # Create datasets to store registered_members_ids
            # First, determine what subgroups exist across all households
            all_subgroups = set()
            for household_subgroups in registered_members_ids:
                all_subgroups.update(household_subgroups.keys())
            all_subgroups = sorted(list(all_subgroups))  # Ensure consistent ordering

            # Store subgroup IDs as integers
            subgroup_ids = np.array(all_subgroups, dtype=np.int64) if all_subgroups else np.array([], dtype=np.int64)

            # Create counts and flattened arrays for each subgroup
            subgroup_counts = {}
            flattened_subgroup_members = {}

            for subgroup_id in all_subgroups:
                # Count of members in this subgroup for each household
                counts = np.array([len(household_dict.get(subgroup_id, [])) for household_dict in registered_members_ids], dtype=np.int64)
                subgroup_counts[subgroup_id] = counts

                # Flatten all member IDs for this subgroup
                member_arrays = [household_dict.get(subgroup_id, np.array([], dtype=np.int64)) for household_dict in registered_members_ids]
                flattened = np.concatenate(member_arrays) if any(len(arr) > 0 for arr in member_arrays) else np.array([], dtype=np.int64)
                flattened_subgroup_members[subgroup_id] = flattened
            if chunk == 0:
                # PERFORMANCE OPTIMIZATION: Add compression to reduce I/O time
                compression_opts = dict(compression='lzf', shuffle=True, fletcher32=True)

                households_dset.attrs["n_households"] = n_households
                households_dset.create_dataset("id", data=ids, maxshape=(None,), **compression_opts)
                households_dset.create_dataset("area", data=areas, maxshape=(None,), **compression_opts)
                households_dset.create_dataset(
                    "super_area", data=super_areas, maxshape=(None,), **compression_opts
                )
                households_dset.create_dataset("type", data=types, maxshape=(None,), **compression_opts)
                households_dset.create_dataset(
                    "composition_type", data=composition_types, maxshape=(None,), **compression_opts
                )
                households_dset.create_dataset(
                    "max_size", data=max_sizes, maxshape=(None,), **compression_opts
                )

                # Store registered_members_ids subgroups information
                if all_subgroups:  # Only create these datasets if we have subgroups
                    households_dset.create_dataset("registered_members_subgroups", data=subgroup_ids, maxshape=(None,))

                    # Create datasets for each subgroup
                    for subgroup_id in all_subgroups:
                        # Store counts for this subgroup
                        households_dset.create_dataset(
                            f"registered_members_count_sg{subgroup_id}", 
                            data=subgroup_counts[subgroup_id], 
                            maxshape=(None,)
                        )

                        # Store flattened members for this subgroup
                        flattened_members = flattened_subgroup_members[subgroup_id]
                        households_dset.create_dataset(
                            f"registered_members_ids_sg{subgroup_id}", 
                            data=flattened_members, 
                            maxshape=(None,)
                        )

            else:
                newshape = (households_dset["id"].shape[0] + ids.shape[0],)
                households_dset["id"].resize(newshape)
                households_dset["id"][idx1:idx2] = ids
                households_dset["area"].resize(newshape)
                households_dset["area"][idx1:idx2] = areas
                households_dset["super_area"].resize(newshape)
                households_dset["super_area"][idx1:idx2] = super_areas
                households_dset["type"].resize(newshape)
                households_dset["type"][idx1:idx2] = types
                households_dset["composition_type"].resize(newshape)
                households_dset["composition_type"][idx1:idx2] = composition_types
                households_dset["max_size"].resize(newshape)
                households_dset["max_size"][idx1:idx2] = max_sizes

                # Update registered members for subgroups
                if all_subgroups:  # Only update these datasets if we have subgroups
                    for subgroup_id in all_subgroups:
                        # Update counts for this subgroup
                        count_dataset = households_dset[f"registered_members_count_sg{subgroup_id}"]
                        count_dataset.resize(newshape)
                        count_dataset[idx1:idx2] = subgroup_counts[subgroup_id]

                        # Update flattened IDs for this subgroup (variable length)
                        ids_dataset = households_dset[f"registered_members_ids_sg{subgroup_id}"]
                        flattened_members = flattened_subgroup_members[subgroup_id]

                        if flattened_members.shape[0] > 0:
                            current_length = ids_dataset.shape[0]
                            new_length = current_length + flattened_members.shape[0]
                            ids_dataset.resize((new_length,))
                            ids_dataset[current_length:new_length] = flattened_members

        residences_to_visit_specs = []
        residences_to_visit_ids = []
        residences_to_visit_super_areas = []
        for household in households:
            if not household.residences_to_visit:
                residences_to_visit_specs.append(np.array(["none"], dtype="S20"))
                residences_to_visit_ids.append(np.array([nan_integer], dtype=np.int64))
                residences_to_visit_super_areas.append(
                    np.array([nan_integer], dtype=np.int64)
                )
            else:
                to_visit_ids = []
                to_visit_specs = []
                to_visit_super_areas = []
                for residence_type in household.residences_to_visit:
                    for residence_to_visit in household.residences_to_visit[
                        residence_type
                    ]:
                        to_visit_specs.append(residence_type)
                        to_visit_ids.append(residence_to_visit.id)
                        to_visit_super_areas.append(residence_to_visit.super_area.id)
                residences_to_visit_specs.append(np.array(to_visit_specs, dtype="S20"))
                residences_to_visit_ids.append(np.array(to_visit_ids, dtype=np.int64))
                residences_to_visit_super_areas.append(
                    np.array(to_visit_super_areas, dtype=np.int64)
                )

        if len(np.unique(list(chain(*residences_to_visit_ids)))) > 1:
            residences_to_visit_ids = np.array(
                residences_to_visit_ids, dtype=int_vlen_type
            )
            residences_to_visit_specs = np.array(
                residences_to_visit_specs, dtype=str_vlen_type
            )
            residences_to_visit_super_areas = np.array(
                residences_to_visit_super_areas, dtype=int_vlen_type
            )
        else:
            residences_to_visit_ids = np.array(residences_to_visit_ids, dtype=np.int64)
            residences_to_visit_specs = np.array(residences_to_visit_specs, dtype="S20")
            residences_to_visit_super_areas = np.array(
                residences_to_visit_super_areas, dtype=np.int64
            )
        households_dset.create_dataset(
            "residences_to_visit_ids", data=residences_to_visit_ids
        )
        households_dset.create_dataset(
            "residences_to_visit_specs", data=residences_to_visit_specs
        )
        households_dset.create_dataset(
            "residences_to_visit_super_areas", data=residences_to_visit_super_areas
        )