Skip to content

laser.measles.demographics

laser.measles.demographics

laser.measles.demographics.GADMShapefile

Bases: AdminShapefile

Shapefile reader for GADM (Global Administrative Areas) boundary data.

Automatically determines the admin level from the GADM filename and downloads shapefiles from the GADM servers when needed. Use download to fetch a country's boundaries, or construct directly from a local file.

Example:

1
2
3
4
```python
gadm = GADMShapefile.download("NGA", admin_level=2, directory="./data")
df = gadm.get_dataframe()
```

laser.measles.demographics.GADMShapefile.check_dotname_fields()

Check dotname_fields from shapefile name if not explicitly provided.

laser.measles.demographics.GADMShapefile.download(country_code, admin_level, directory=None, timeout=60) classmethod

Download the GADM shapefile for a given country code and return a GADMShapefile instance.

Parameters:

Name Type Description Default
country_code str

The country code to download the shapefile for.

required
admin_level int

The admin level to download the shapefile for.

required
directory str | Path | None

The directory to download the shapefile to. If None, uses current directory.

None
timeout int

The timeout for the request.

60

Returns:

Type Description
GADMShapefile

A GADMShapefile instance for the downloaded shapefile.

laser.measles.demographics.RasterPatchGenerator(config, verbose=True)

Generate a scenario DataFrame by clipping raster data to shapefile boundaries.

This is the primary tool for the prepare scenario stage. Given population and vaccination-coverage rasters plus an admin-boundary shapefile, it produces a Polars DataFrame with one row per patch containing id, pop, lat, lon, mcv1, and optionally mcv2 columns — ready to pass to any model constructor.

Results are cached on disk; subsequent calls with the same configuration skip the raster-clipping step.

Parameters:

Name Type Description Default
config RasterPatchParams

A RasterPatchParams specifying inputs.

required
verbose bool

Print progress messages.

True

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
```python
from laser.measles.demographics.raster_patch import (
    RasterPatchGenerator, RasterPatchParams,
)

config = RasterPatchParams(
    id="nga_admin2",
    region="NGA",
    shapefile="gadm41_NGA_2.shp",
    population_raster="nga_ppp_2020.tif",
    mcv1_raster="nga_mcv1_2020.tif",
)
generator = RasterPatchGenerator(config)
scenario_df = generator.generate_demographics()
```

laser.measles.demographics.RasterPatchGenerator.clear_cache()

Remove all cached entries for this configuration's ID.

laser.measles.demographics.RasterPatchGenerator.generate_birth_rates()

Generate birth-rate data (not yet implemented).

laser.measles.demographics.RasterPatchGenerator.generate_demographics()

Run the full demographic extraction pipeline.

Clips population (and optionally MCV1) rasters to the shapefile boundaries and stores results in self.population and self.mcv1.

laser.measles.demographics.RasterPatchGenerator.generate_mcv1()

MCV1 coverage, population weighted

laser.measles.demographics.RasterPatchGenerator.generate_mortality_rates()

Generate mortality-rate data (not yet implemented).

laser.measles.demographics.RasterPatchGenerator.generate_population()

Population, counts

laser.measles.demographics.RasterPatchGenerator.get_cache_key(key)

Build a namespaced cache key for this configuration.

Parameters:

Name Type Description Default
key

One of "shapefile", "population", or "mcv1".

required

Returns:

Type Description
str

Cache key string in the form "{config.id}:{key}".

laser.measles.demographics.RasterPatchParams

Bases: BaseModel

Configuration for raster-based demographic data extraction.

Specifies the geographic region, shapefile boundaries, and raster data sources used by RasterPatchGenerator to build a scenario DataFrame during the prepare scenario stage.

Parameters:

Name Type Description Default
id

Unique identifier for this scenario configuration.

required
region

ISO-3166 alpha-3 country code (e.g. "NGA").

required
shapefile

Path to the admin-boundary shapefile (.shp).

required
population_raster

Path to a population-count raster (GeoTIFF).

required
mcv1_raster

Path to a MCV1 coverage raster (GeoTIFF).

required
mcv2_raster

Path to a MCV2 coverage raster (GeoTIFF).

required

Example:

1
2
3
4
5
```python
from laser.measles.demographics.raster_patch import RasterPatchParams

params = RasterPatchParams(admin_level=2)
```

laser.measles.demographics.RasterPatchParams.shapefile_exists(v, info)

Verify the shapefile path exists on disk.

laser.measles.demographics.WPP(country_code)

World Population Prospects (WPP) population data access and processing.

This class provides access to United Nations World Population Prospects data for population trajectories, demographic estimates, and population pyramids. It uses the pyvd library to retrieve and process population data for specific countries, including mortality rates, birth rates, and age-structured population data.

The class supports interpolation of population pyramids for any year within the available data range, making it useful for demographic modeling and population projection analysis.

Attributes:

Name Type Description
country_code str

The ISO country code for the selected country.

year_vec ndarray

Vector of years available in the WPP dataset.

pop_mat ndarray

Population matrix with shape (age_bins, years).

vd_tup tuple

Demographic vital data tuple containing: - mort_year: Mortality year reference - mort_mat: Mortality matrix - birth_rate: Birth rate data - br_mult_x: Birth rate multiplier x values - br_mult_y: Birth rate multiplier y values

age_vec ndarray

Age vector in days, representing age bins.

pyramid_spline

Interpolating spline for population pyramid data.

Example

wpp = WPP("USA") pyramid_2020 = wpp.get_population_pyramid(2020) print(f"Population pyramid shape: {pyramid_2020.shape}")

Initialize WPP data access for a specific country.

Parameters:

Name Type Description Default
country_code str

ISO country code (e.g., "USA", "GBR", "CHN"). The code will be converted to uppercase automatically.

required

Raises:

Type Description
ValueError

If the country code is invalid or data is unavailable.

Note

Population data is adjusted by adding 0.1 to avoid zero values that could cause issues in demographic calculations.

laser.measles.demographics.WPP.get_population_pyramid(year)

Get the population pyramid for a given year.

Retrieves the age-structured population data for the specified year using spline interpolation. The population pyramid represents the distribution of population across different age groups.

Parameters:

Name Type Description Default
year int

The target year for population pyramid data. Must be within the available data range.

required

Returns:

Type Description
ndarray

np.ndarray: Population pyramid array with shape (age_bins,), representing population counts for each age group.

Raises:

Type Description
AssertionError

If the requested year is outside the available data range (before first year or after last year).

Example

wpp = WPP("USA") pyramid_2020 = wpp.get_population_pyramid(2020) print(f"Age groups: {len(pyramid_2020)}") print(f"Total population: {pyramid_2020.sum():.0f}")

laser.measles.demographics.get_shapefile_dataframe(shapefile_path)

Get a DataFrame containing the shapefile data with DOTNAME and shape columns.

Parameters:

Name Type Description Default
shapefile_path str | Path

The path to the shapefile.

required

Returns:

Type Description
DataFrame

A DataFrame with DOTNAME and shape columns.

laser.measles.demographics.plot_shapefile_dataframe(df, ax=None, plot_kwargs=None)

Render shapefile polygons onto a matplotlib axes.

Parameters:

Name Type Description Default
df DataFrame

DataFrame returned by get_shapefile_dataframe containing a shape column.

required
ax Axes | None

Matplotlib axes. A new figure is created if None.

None
plot_kwargs dict | None

Additional keyword arguments forwarded to matplotlib.patches.Polygon.

None

Returns:

Type Description
Figure

The matplotlib Figure containing the rendered map.