-
Notifications
You must be signed in to change notification settings - Fork 73
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: use future population projections (#210)
- Loading branch information
Showing
10 changed files
with
289 additions
and
62 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
import pandas as pd | ||
import os | ||
|
||
""" | ||
This stage loads and cleans projection data about the French population. | ||
""" | ||
|
||
def configure(context): | ||
context.config("data_path") | ||
context.config("projection_path", "projection_2021") | ||
context.config("projection_scenario", "00_central") | ||
context.config("projection_year", None) | ||
|
||
def execute(context): | ||
source_path = "{}/{}/{}.xlsx".format( | ||
context.config("data_path"), | ||
context.config("projection_path"), | ||
context.config("projection_scenario")) | ||
|
||
projection_year = int(context.config("projection_year")) | ||
|
||
df_all = pd.read_excel( | ||
source_path, sheet_name = "population", skiprows = 1).iloc[:107] | ||
|
||
df_male = pd.read_excel( | ||
source_path, sheet_name = "populationH", skiprows = 1).iloc[:107] | ||
|
||
df_female = pd.read_excel( | ||
source_path, sheet_name = "populationF", skiprows = 1).iloc[:107] | ||
|
||
df_male["sex"] = "male" | ||
df_female["sex"] = "female" | ||
|
||
assert df_all["Âge au 1er janvier"].iloc[-1] == "Total" | ||
assert df_male["Âge au 1er janvier"].iloc[-1] == "Total des hommes" | ||
assert df_female["Âge au 1er janvier"].iloc[-1] == "Total des femmes" | ||
|
||
df_sex = pd.concat([ | ||
df_male.iloc[-1:], | ||
df_female.iloc[-1:] | ||
]).drop(columns = ["Âge au 1er janvier"])[["sex", projection_year]] | ||
df_sex.columns = ["sex", "projection"] | ||
|
||
df_age = df_all[["Âge au 1er janvier", projection_year]].iloc[:-1] | ||
df_age.columns = ["age", "projection"] | ||
|
||
df_male = df_male[["Âge au 1er janvier", "sex", projection_year]].iloc[:-1] | ||
df_female = df_female[["Âge au 1er janvier", "sex", projection_year]].iloc[:-1] | ||
|
||
df_male.columns = ["age", "sex", "projection"] | ||
df_female.columns = ["age","sex", "projection"] | ||
|
||
df_cross = pd.concat([df_male, df_female]) | ||
df_cross["sex"] = df_cross["sex"].astype("category") | ||
|
||
df_total = df_all.iloc[-1:].drop(columns = ["Âge au 1er janvier"])[[projection_year]] | ||
df_total.columns = ["projection"] | ||
|
||
return { | ||
"total": df_total, "sex": df_sex, "age": df_age, "cross": df_cross | ||
} | ||
|
||
def validate(context): | ||
if context.config("projection_year") is not None: | ||
source_path = "{}/{}/{}.xlsx".format( | ||
context.config("data_path"), | ||
context.config("projection_path"), | ||
context.config("projection_scenario")) | ||
|
||
if not os.path.exists(source_path): | ||
raise RuntimeError("Projection data is not available") | ||
|
||
return os.path.getsize(source_path) | ||
|
||
return 0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
import pandas as pd | ||
import numpy as np | ||
|
||
""" | ||
This stage reweights the census data set according to the projection data for a different year. | ||
""" | ||
|
||
def configure(context): | ||
context.stage("data.census.cleaned") | ||
context.stage("data.census.projection") | ||
|
||
def execute(context): | ||
df_census = context.stage("data.census.cleaned") | ||
projection = context.stage("data.census.projection") | ||
|
||
# Prepare indexing | ||
df_households = df_census[["household_id", "household_size", "weight"]].drop_duplicates("household_id") | ||
df_households["household_index"] = np.arange(len(df_households)) | ||
df_census = pd.merge(df_census, df_households[["household_id", "household_index"]]) | ||
|
||
# Obtain weights and sizes as arrays | ||
household_weights = df_households["weight"].values | ||
household_sizes = df_households["household_size"].values | ||
|
||
# Obtain the attribute levels and membership of attributes for all households | ||
attributes = [] | ||
|
||
attribute_membership = [] | ||
attribute_counts = [] | ||
attribute_targets = [] | ||
|
||
# Proccesing age ... | ||
df_marginal = projection["age"] | ||
for index, row in context.progress(df_marginal.iterrows(), label = "Processing attribute: age", total = len(df_marginal)): | ||
f = df_census["age"] == row["age"] | ||
|
||
if row["age"] == 0: | ||
continue # we skip incompatible values for peopel of zero age | ||
|
||
if np.count_nonzero(f) == 0: | ||
print("Did not find age:", row["age"]) | ||
|
||
else: | ||
df_counts = df_census.loc[f, "household_index"].value_counts() | ||
|
||
attribute_targets.append(row["projection"]) | ||
attribute_membership.append(df_counts.index.values) | ||
attribute_counts.append(df_counts.values) | ||
attributes.append("age={}".format(row["age"])) | ||
|
||
# Processing sex ... | ||
df_marginal = projection["sex"] | ||
for index, row in context.progress(df_marginal.iterrows(), label = "Processing attribute: sex", total = len(df_marginal)): | ||
f = df_census["sex"] == row["sex"] | ||
|
||
if np.count_nonzero(f) == 0: | ||
print("Did not find sex:", row["sex"]) | ||
|
||
else: | ||
df_counts = df_census.loc[f, "household_index"].value_counts() | ||
|
||
attribute_targets.append(row["projection"]) | ||
attribute_membership.append(df_counts.index.values) | ||
attribute_counts.append(df_counts.values) | ||
attributes.append("sex={}".format(row["sex"])) | ||
|
||
# Processing age x sex ... | ||
df_marginal = projection["cross"] | ||
for index, row in context.progress(df_marginal.iterrows(), label = "Processing attributes: sex x age", total = len(df_marginal)): | ||
f = (df_census["sex"] == row["sex"]) & (df_census["age"] == row["age"]) | ||
|
||
if row["age"] == 0: | ||
continue | ||
|
||
if np.count_nonzero(f) == 0: | ||
print("Did not find values:", row["sex"], row["age"]) | ||
|
||
else: | ||
df_counts = df_census.loc[f, "household_index"].value_counts() | ||
|
||
attribute_targets.append(row["projection"]) | ||
attribute_membership.append(df_counts.index.values) | ||
attribute_counts.append(df_counts.values) | ||
attributes.append("sex={},age={}".format(row["sex"], row["age"])) | ||
|
||
# Processing total ... | ||
attribute_targets.append(projection["total"]["projection"].values[0]) | ||
attribute_membership.append(np.arange(len(household_sizes))) | ||
attribute_counts.append(household_sizes) | ||
attributes.append("total") | ||
|
||
# Perform IPU to obtain update weights | ||
update = np.ones((len(df_households),)) | ||
|
||
minimum_factors = [] | ||
maximum_factors = [] | ||
|
||
for iteration in context.progress(range(100), label = "Performing IPU"): | ||
factors = [] | ||
for k in np.arange(len(attributes)): | ||
selection = attribute_membership[k] | ||
|
||
target = attribute_targets[k] | ||
current = np.sum(update[selection] * household_weights[selection] * attribute_counts[k]) | ||
|
||
factor = target / current | ||
factors.append(factor) | ||
|
||
update[selection] *= factor | ||
|
||
minimum_factors.append(np.min(factors)) | ||
maximum_factors.append(np.max(factors)) | ||
|
||
if np.max(factors) - np.min(factors) < 1e-3: | ||
break | ||
|
||
criterion = np.max(factors) - np.min(factors) | ||
|
||
# Check that the applied factors in the last iteration are sufficiently small | ||
assert criterion > 0.01 | ||
|
||
# For a sanity check, we check for the obtained distribution in 2019, but this | ||
# may evolve in the future. | ||
assert np.quantile(update, 0.1) > 0.35 | ||
assert np.quantile(update, 0.8) < 2.0 | ||
assert np.quantile(update, 0.9) < 2.5 | ||
|
||
# Update the weights | ||
df_households["weight"] *= update | ||
|
||
return df_households[["household_id", "weight"]] |
Oops, something went wrong.