laser_measles.demographics package#

class WPP(country_code)[source]#

Bases: object

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.

country_code#

The ISO country code for the selected country.

Type:

str

year_vec#

Vector of years available in the WPP dataset.

Type:

np.ndarray

pop_mat#

Population matrix with shape (age_bins, years).

Type:

np.ndarray

vd_tup#

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

Type:

tuple

age_vec#

Age vector in days, representing age bins.

Type:

np.ndarray

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}")
get_population_pyramid(year)[source]#

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:

year (int) – The target year for population pyramid data. Must be within the available data range.

Returns:

Population pyramid array with shape (age_bins,),

representing population counts for each age group.

Return type:

np.ndarray

Raises:

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}")
pydantic model GADMShapefile[source]#

Bases: AdminShapefile

Show JSON schema
{
   "title": "GADMShapefile",
   "type": "object",
   "properties": {
      "shapefile": {
         "format": "path",
         "title": "Shapefile",
         "type": "string"
      },
      "admin_level": {
         "anyOf": [
            {
               "type": "integer"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "title": "Admin Level"
      },
      "dotname_fields": {
         "anyOf": [
            {
               "items": {
                  "type": "string"
               },
               "type": "array"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "title": "Dotname Fields"
      }
   },
   "required": [
      "shapefile"
   ]
}

Fields:

Validators:
classmethod download(country_code, admin_level, directory=None, timeout=60)[source]#

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

Parameters:
  • country_code (str) – The country code to download the shapefile for.

  • admin_level (int) – The admin level to download the shapefile for.

  • directory (str | Path | None) – The directory to download the shapefile to. If None, uses current directory.

  • timeout (int) – The timeout for the request.

Return type:

GADMShapefile

Returns:

A GADMShapefile instance for the downloaded shapefile.

validator check_dotname_fields  »  all fields[source]#

Check dotname_fields from shapefile name if not explicitly provided.

Return type:

GADMShapefile

class RasterPatchGenerator(config, verbose=True)[source]#

Bases: object

clear_cache()[source]#
Return type:

None

generate_birth_rates()[source]#
Return type:

DataFrame

generate_demographics()[source]#
Return type:

None

generate_mcv1()[source]#

MCV1 coverage, population weighted

Return type:

DataFrame

generate_mortality_rates()[source]#
Return type:

DataFrame

generate_population()[source]#

Population, counts

Return type:

DataFrame

get_cache_key(key)[source]#
Return type:

str

pydantic model RasterPatchParams[source]#

Bases: BaseModel

Show JSON schema
{
   "title": "RasterPatchParams",
   "type": "object",
   "properties": {
      "id": {
         "description": "Unique identifier for the scenario",
         "title": "Id",
         "type": "string"
      },
      "region": {
         "description": "Country identifier (ISO3 code)",
         "title": "Region",
         "type": "string"
      },
      "shapefile": {
         "anyOf": [
            {
               "type": "string"
            },
            {
               "format": "path",
               "type": "string"
            }
         ],
         "description": "Path to the shapefile",
         "title": "Shapefile"
      },
      "population_raster": {
         "anyOf": [
            {
               "type": "string"
            },
            {
               "format": "path",
               "type": "string"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "description": "Path to the population raster",
         "title": "Population Raster"
      },
      "mcv1_raster": {
         "anyOf": [
            {
               "type": "string"
            },
            {
               "format": "path",
               "type": "string"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "description": "Path to the MCV1 raster",
         "title": "Mcv1 Raster"
      },
      "mcv2_raster": {
         "anyOf": [
            {
               "type": "string"
            },
            {
               "format": "path",
               "type": "string"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "description": "Path to the MCV2 raster",
         "title": "Mcv2 Raster"
      }
   },
   "required": [
      "id",
      "region",
      "shapefile"
   ]
}

Fields:
Validators:
field id: str [Required]#

Unique identifier for the scenario

field mcv1_raster: str | Path | None = None#

Path to the MCV1 raster

field mcv2_raster: str | Path | None = None#

Path to the MCV2 raster

field population_raster: str | Path | None = None#

Path to the population raster

field region: str [Required]#

Country identifier (ISO3 code)

field shapefile: str | Path [Required]#

Path to the shapefile

Validated by:
validator shapefile_exists  »  shapefile[source]#
get_shapefile_dataframe(shapefile_path)[source]#

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

Parameters:

shapefile_path (str | Path) – The path to the shapefile.

Return type:

DataFrame

Returns:

A DataFrame with DOTNAME and shape columns.

plot_shapefile_dataframe(df, ax=None, plot_kwargs=None)[source]#
Return type:

Figure

Submodules#

laser_measles.demographics.admin_shapefile module#

Admin level shapefiles

pydantic model AdminShapefile[source]#

Bases: BaseShapefile

Shapefile of administrative units.

Parameters:
  • admin_level (int) – Admin level of the shapefile.

  • dotname_fields (list[str]) – List of fields to use for dotname. e.g., [“ADMIN0”, “ADMIN1”, “ADMIN2”]

Show JSON schema
{
   "title": "AdminShapefile",
   "description": "Shapefile of administrative units.\n\nArgs:\n    admin_level (int): Admin level of the shapefile.\n    dotname_fields (list[str]): List of fields to use for dotname. e.g., [\"ADMIN0\", \"ADMIN1\", \"ADMIN2\"]",
   "type": "object",
   "properties": {
      "shapefile": {
         "format": "path",
         "title": "Shapefile",
         "type": "string"
      },
      "admin_level": {
         "anyOf": [
            {
               "type": "integer"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "title": "Admin Level"
      },
      "dotname_fields": {
         "anyOf": [
            {
               "items": {
                  "type": "string"
               },
               "type": "array"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "title": "Dotname Fields"
      }
   },
   "required": [
      "shapefile"
   ]
}

Fields:
field admin_level: int | None = None#
field dotname_fields: list[str] | None = None#
add_dotname()[source]#

Add a DOTNAME to the shapefil (e.g., ADMIN0:ADMIN1:ADMIN2)

Return type:

None

get_shapefile_parent()[source]#

Get the parent directory of the shapefile.

Return type:

Path

shape_subdivide(patch_size_km)[source]#

Subdivide the shapefile for a given administrative level into patches of approximately equal area.

Parameters:

patch_size_km (int) – Size of the patch in square kilometers.

Return type:

None

laser_measles.demographics.base module#

class DemographicsGeneratorProtocol(*args, **kwargs)[source]#

Bases: Protocol

generate_population()[source]#
Return type:

DataFrame

generate_birth_rates()[source]#
Return type:

DataFrame

generate_mortality_rates()[source]#
Return type:

DataFrame

class ShapefileProtocol(*args, **kwargs)[source]#

Bases: Protocol

add_dotname()[source]#
Return type:

None

get_dataframe()[source]#
Return type:

DataFrame

pydantic model BaseShapefile[source]#

Bases: BaseModel

Show JSON schema
{
   "title": "BaseShapefile",
   "type": "object",
   "properties": {
      "shapefile": {
         "format": "path",
         "title": "Shapefile",
         "type": "string"
      }
   },
   "required": [
      "shapefile"
   ]
}

Fields:
field shapefile: Path [Required]#
classmethod convert_to_path(v)[source]#

Wrap a classmethod, staticmethod, property or unbound function and act as a descriptor that allows us to detect decorated items from the class’ attributes.

This class’ __get__ returns the wrapped item’s __get__ result, which makes it transparent for classmethods and staticmethods.

wrapped#

The decorator that has to be wrapped.

decorator_info#

The decorator info.

shim#

A wrapper function to wrap V1 style function.

add_dotname()[source]#
Return type:

None

get_dataframe()[source]#

Get a Polars DataFrame containing the shapefile data and fields.

Return type:

DataFrame

Returns:

A Polars DataFrame.

laser_measles.demographics.cache module#

load_cache(cache_dir=None)[source]#

Load the cache for the application.

Parameters:

cache_dir (str | None) – The cache directory to use. If None, the default cache directory will be used.

Return type:

Cache

Returns:

The cache object.

get_cache_dir()[source]#

Get the cache directory for the application.

Return type:

str

clear_cache(cache_dir=None)[source]#

Clear diskcache data from the application cache.

Return type:

None

clear_all_cache()[source]#

Clear all cached data from the application cache.

Return type:

None

clear_cache_dir(dir)[source]#

Clear all cached data from a specific directory.

Return type:

None

get_all_cache_keys()[source]#

Get all the cache keys for the application.

Return type:

list[str]

laser_measles.demographics.gadm module#

GADM shapefiles

pydantic model GADMShapefile[source]#

Bases: AdminShapefile

Show JSON schema
{
   "title": "GADMShapefile",
   "type": "object",
   "properties": {
      "shapefile": {
         "format": "path",
         "title": "Shapefile",
         "type": "string"
      },
      "admin_level": {
         "anyOf": [
            {
               "type": "integer"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "title": "Admin Level"
      },
      "dotname_fields": {
         "anyOf": [
            {
               "items": {
                  "type": "string"
               },
               "type": "array"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "title": "Dotname Fields"
      }
   },
   "required": [
      "shapefile"
   ]
}

Fields:

Validators:
classmethod download(country_code, admin_level, directory=None, timeout=60)[source]#

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

Parameters:
  • country_code (str) – The country code to download the shapefile for.

  • admin_level (int) – The admin level to download the shapefile for.

  • directory (str | Path | None) – The directory to download the shapefile to. If None, uses current directory.

  • timeout (int) – The timeout for the request.

Return type:

GADMShapefile

Returns:

A GADMShapefile instance for the downloaded shapefile.

validator check_dotname_fields  »  all fields[source]#

Check dotname_fields from shapefile name if not explicitly provided.

Return type:

GADMShapefile

laser_measles.demographics.raster_patch module#

Raster patch generator for demographic data. You can use this to generate initial conditions (e.g, population, MCV1 coverage) for a laser-measles scenario.

pydantic model RasterPatchParams[source]#

Bases: BaseModel

Show JSON schema
{
   "title": "RasterPatchParams",
   "type": "object",
   "properties": {
      "id": {
         "description": "Unique identifier for the scenario",
         "title": "Id",
         "type": "string"
      },
      "region": {
         "description": "Country identifier (ISO3 code)",
         "title": "Region",
         "type": "string"
      },
      "shapefile": {
         "anyOf": [
            {
               "type": "string"
            },
            {
               "format": "path",
               "type": "string"
            }
         ],
         "description": "Path to the shapefile",
         "title": "Shapefile"
      },
      "population_raster": {
         "anyOf": [
            {
               "type": "string"
            },
            {
               "format": "path",
               "type": "string"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "description": "Path to the population raster",
         "title": "Population Raster"
      },
      "mcv1_raster": {
         "anyOf": [
            {
               "type": "string"
            },
            {
               "format": "path",
               "type": "string"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "description": "Path to the MCV1 raster",
         "title": "Mcv1 Raster"
      },
      "mcv2_raster": {
         "anyOf": [
            {
               "type": "string"
            },
            {
               "format": "path",
               "type": "string"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "description": "Path to the MCV2 raster",
         "title": "Mcv2 Raster"
      }
   },
   "required": [
      "id",
      "region",
      "shapefile"
   ]
}

Fields:
Validators:
field id: str [Required]#

Unique identifier for the scenario

field mcv1_raster: str | Path | None = None#

Path to the MCV1 raster

field mcv2_raster: str | Path | None = None#

Path to the MCV2 raster

field population_raster: str | Path | None = None#

Path to the population raster

field region: str [Required]#

Country identifier (ISO3 code)

field shapefile: str | Path [Required]#

Path to the shapefile

Validated by:
validator shapefile_exists  »  shapefile[source]#
class RasterPatchGenerator(config, verbose=True)[source]#

Bases: object

generate_demographics()[source]#
Return type:

None

get_cache_key(key)[source]#
Return type:

str

generate_population()[source]#

Population, counts

Return type:

DataFrame

generate_mcv1()[source]#

MCV1 coverage, population weighted

Return type:

DataFrame

clear_cache()[source]#
Return type:

None

generate_birth_rates()[source]#
Return type:

DataFrame

generate_mortality_rates()[source]#
Return type:

DataFrame

laser_measles.demographics.shapefiles module#

check_field(path, field_name)[source]#
Return type:

bool

add_dotname(path, dot_name_fields, dotname_symbol=':', append_suffix='dotname', inplace=False, field_name='DOTNAME')[source]#

Add a DOTNAME to the shapefile.

Return type:

None

get_shapefile_dataframe(shapefile_path)[source]#

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

Parameters:

shapefile_path (str | Path) – The path to the shapefile.

Return type:

DataFrame

Returns:

A DataFrame with DOTNAME and shape columns.

plot_shapefile_dataframe(df, ax=None, plot_kwargs=None)[source]#
Return type:

Figure

laser_measles.demographics.wpp module#

class WPP(country_code)[source]#

Bases: object

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.

country_code#

The ISO country code for the selected country.

Type:

str

year_vec#

Vector of years available in the WPP dataset.

Type:

np.ndarray

pop_mat#

Population matrix with shape (age_bins, years).

Type:

np.ndarray

vd_tup#

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

Type:

tuple

age_vec#

Age vector in days, representing age bins.

Type:

np.ndarray

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}")
get_population_pyramid(year)[source]#

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:

year (int) – The target year for population pyramid data. Must be within the available data range.

Returns:

Population pyramid array with shape (age_bins,),

representing population counts for each age group.

Return type:

np.ndarray

Raises:

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}")