Every exercise in 99_capstone.py, with the solution and why it works. Each answer stays closed until you swear you tried it first. Opening one changes nothing in your notebook; your check still has to go green from your own code. Read the whole notebook, with its lessons.
Exercise K1.1. The flat table
The task
Why it matters: every other output reads it. A row too many here is a fishing unit counted twice in the director's table; a code that lost its zero is a province no table can find.
Input → output: a batch's folder (BATCH, or any folder holding sfh2025_r*.duckdb files) → a pandas or polars DataFrame with one row per fishing unit in the batch:
- the households deleted in the capture system (
hh_deleted_onfilled) or voided in editing (row_void = 1inhousehold), the households excluded by the sampling side (sel_excluded = 1inselection) and the unit rows voided (row_void = 1) left out; - a unit entered twice kept once, so the unit's key (
region_code,hh_id,operator_line,unit_no:UNIT_KEY) never repeats; - these columns, others welcome after them:
region_code,province_code,citymun_code,barangay_codeas zero-padded text (2, 3, 2 and 3 characters);hh_id; the key partsoperator_lineandunit_no; the unit's scaleunit_scale; and its household's stratumsel_stratum, enumeration areasel_eaand final weightsel_final_weight.
| region_code | province_code | citymun_code | barangay_code | hh_id | operator_line | unit_no | unit_scale | sel_stratum | sel_ea | sel_final_weight |
|---|---|---|---|---|---|---|---|---|---|---|
02 |
015 |
01 |
012 |
… | 1 | 1 | 2 | F |
… | |
11 |
024 |
… | … | … | … | … | 1 | C |
… | … |
Tools: module 2 (10_flat_table.py): one DuckDB connection that attaches every region's file, as a script in R loops over regional databases; codes kept whole; or course.table(name, folder=folder) for each table, then joins on the household (module 3) and drop_duplicates on the key (module 4).
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| A few rows too many in the small batch | One of the three removal marks is not applied: hh_deleted_on and row_void in household, sel_excluded in selection. |
module 2, section 2 |
| One row too many, and a key that repeats | The unit entered twice is still there twice. | drop_duplicates on the whole key |
Rows multiplied, or MergeError with validate= |
A join on hh_id alone: in the small batch region 11 reuses region 02's ids. |
join on region_code and hh_id |
region_code shows 2, or province_code shows 15 |
The codes were read as numbers. | zero-padded text: str.zfill, or lpad in SQL |
| Region 11 alone passes, the small batch fails | Region 11 of the small batch stores its codes as text, and the code treats them as numbers. | read both kinds of region the same way |
| Every unit of stratum F is missing | A filter or a join on sel_ea dropped the blank areas: stratum F has no area. |
keep sel_ea blank where it is blank |
{'columns missing': [...]} |
A column the brief names is missing or renamed. | the list above |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Read the three tables the flat table needs with the removed households and voided rows left out, keep each unit once, and join each unit to its household's area codes and its design on the region and the household together.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def flat_table(folder: Path) -> pd.DataFrame: """One row per fishing unit of the batch in `folder`, with its area codes as text and its household's design.""" # Exercise K1.1: what goes in, what comes out and how it is checked are in the text above this cell. household = ["region_code", "hh_id"] units = course.table("fishing_unit", folder=folder) units = units.sort_values(["region_code", "row_id"]).drop_duplicates(UNIT_KEY) areas = course.table("household", folder=folder)[household + ["province_code", "citymun_code", "barangay_code"]] design = course.table("selection", folder=folder)[household + ["sel_stratum", "sel_ea", "sel_final_weight"]] flat = units.merge(areas, on=household, how="inner", validate="many_to_one").merge(design, on=household, how="inner", validate="many_to_one") return flat.reset_index(drop=True)Why each part is there
course.table(..., folder=folder)reads every region's file in the folder, addsregion_codewhere a table lacks it, writes the area codes as zero-padded text and leaves out the three kinds of removed household and the rows markedrow_void = 1: the work of module 2, sections 2 and 3, in one call.- Sorting by the row id before
drop_duplicates(UNIT_KEY)keeps the first entry of a unit entered twice. The key includesregion_code, because household ids repeat across regions. - Both joins are on
region_codeandhh_idwithvalidate="many_to_one": a household id alone would give a region 11 unit the weight of a region 02 household, and the validation stops if a household is listed twice. - Nothing is dropped by the joins: every unit's household is in
householdand inselection, because all three were read with the same removals.
Exercise K1.2. The matching report
The task
Why it matters: a catch row whose key matches no unit is catch that no unit reports, and a unit with no catch row reports no catch. Neither is visible in a sum; both change what the batch says.
Input → output: a batch's folder → one row per key with no match on the other side, between the units (fishing_unit) and the catch (catch), both after the removals, with the columns region_code, hh_id, operator_line, unit_no (the catch's key parts under the unit's names) and side, which is unit without catch or catch without unit.
| region_code | hh_id | operator_line | unit_no | side |
|---|---|---|---|---|
02 |
… | 1 | 4 | catch without unit |
02 |
… | 1 | 1 | unit without catch |
A key listed twice is read once. Repairing the keys is not part of this output: module 3 did that, and the batch's editors will.
Tools: module 3 (20_key_matching.py): an anti_join in R runs one way at a time; in pandas one merge(how="outer", indicator=True) gives both sides at once. The catch's key parts carry the table's prefix: catch_operator_line, catch_unit_no (CHILD_PREFIX).
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
KeyError naming operator_line on the catch |
The catch's key parts carry the prefix catch_. |
rename them to the unit's names |
| Every catch row is unmatched | The key parts are text on one side and numbers on the other, or region_code is 2 on one side and 02 on the other. |
the key's types, side by side |
| Too few keys in the small batch | The join ignores region_code, so region 11's keys find matches in region 02. |
the whole key, region first |
| A unit without catch is missing | The catch was read with clean=False, so the voided catch row still counts as catch. |
the removals |
| The right keys, but the check is red | side is not written exactly unit without catch or catch without unit. |
the two labels |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
One outer join of the units' keys with the catch's keys, region included: the rows found on one side only are the report, and the indicator says which side.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def matching_report(folder: Path) -> pd.DataFrame: """Every unit key with no catch row, and every catch key with no unit, in the batch in `folder`.""" # Exercise K1.2: what goes in, what comes out and how it is checked are in the text above this cell. units = course.table("fishing_unit", folder=folder)[UNIT_KEY].drop_duplicates() prefix = CHILD_PREFIX["catch"] catch = course.table("catch", folder=folder) catch = catch.rename(columns={f"{prefix}_operator_line": "operator_line", f"{prefix}_unit_no": "unit_no"})[UNIT_KEY].drop_duplicates() both = units.merge(catch, on=UNIT_KEY, how="outer", indicator=True) unmatched = both[both["_merge"] != "both"].copy() unmatched["side"] = unmatched["_merge"].map({"left_only": "unit without catch", "right_only": "catch without unit"}).astype("string") return unmatched[UNIT_KEY + ["side"]].sort_values(["side", *UNIT_KEY]).reset_index(drop=True)Why each part is there
- Both tables are read with the removals applied, so a voided catch row is not counted as catch: a unit whose only catch row was voided is a unit without catch.
- The catch's key parts are renamed to the unit's names, so the two keys can be compared column by column.
drop_duplicateson the keys first: a unit entered twice, or two catch rows of one unit, are one key, and the report lists keys.merge(how="outer", indicator=True)on the whole key,region_codefirst:left_onlyis a unit with no catch,right_onlycatch with no unit. Withoutregion_code, a region 11 catch row could match a region 02 unit with the same numbers.
Exercise K1.3. The rules report
The task
Why it matters: the rules are what the questionnaire says must be true. A household that fails one goes back to an editor before its numbers are published, so the editors need the list, rule by rule.
Input → output: a batch's folder → one row per rule and household that fails it, with the columns rule (the rule's id, as M1 or U3), region_code and hh_id; add what helps an editor. Module 4's failure report has all three columns. A household that fails a rule on two rows may be listed twice: the check reads each rule and household once. The rules run on the tables after the removals, before the flat table drops a unit entered twice. C2 and C3 are the matching report's.
The rules are those of data/codebook_rules.csv, made exact here, because a check can only compare a rule that says what happens at its edges. "Blank fails" means a blank value is a failure; a child table's key parts are read under the unit's names, as in Exercise K1.2.
| rule | a row fails when |
|---|---|
| M1 | the member's sex mem_sex is not 1 or 2 (blank fails) |
| M2 | the member's age mem_age is blank, or outside 0 to 110 |
| M3 | a member under 10 has any of mem_fished, mem_role_operator, mem_role_crew, mem_role_hired, mem_role_shore answered |
| M4 | a member who runs a unit (mem_role_operator = 1) is under 16 |
| M5 | a member 6 or over has an education mem_education that is not a code in codes/education.csv (blank fails) |
| M6 | a member who fished (mem_fished = 1) has none of the four mem_role_ flags equal to 1 |
| H1 | the household's hh_roster_members differs from its number of member rows |
| U1 | a unit's key (with region_code) is on more than one row |
| U2 | the unit's operator_line is no member's mem_line in the household, or that member's mem_role_operator is not 1, or its mem_units_run differs from the number of the household's units that name the line, counted by distinct unit_no |
| U3 | the unit's unit_scale is not 2 when one of its boats is 5.0 gross tons or more, or not 1 when none is (a unit with no boat: 1) |
| U4 | unit_uses_boat is not 1 or 0 (blank fails) |
| U5 | unit_uses_boat is not 1 for a unit with rows in boat, or not 0 for a unit with none (blank fails) |
| U6 | a unit with unit_hired_crew = 1 has no row in crew with crew_hired = 1 |
| U7 | the unit's unit_boats, a blank read as 0, differs from its number of rows in boat |
| U8 | unit_months_active is blank, or outside 1 to 12 |
| B1 | the boat's hull boat_hull is not 1, 2 or 3, or its engine boat_engine is not 0, 1 or 2 (blank fails) |
| B2 | a boat with no engine (boat_engine = 0) is 5.0 gross tons or more |
| B3 | the stored boat_tonnage is more than 0.01 from the boat's gross tonnage (a blank on either side fails) |
| B4 | a boat with boat_engine = 0 has an engine power boat_engine_hp, or a boat with another engine code has none |
| B5 | a registration number boat_reg_no (not blank) is on more than one boat row of the household |
| C1 | the species catch_species is not a code in codes/species.csv (blank fails) |
| C4 | one species code is on more than one catch row of a unit |
| W1 | the crew member's sex crew_sex is not 1 or 2 (blank fails) |
A boat's gross tonnage, in U3, B2 and B3, is length × beam × depth × 0.212 when it was measured in meters (boat_measured_in = 2), × 0.006 when measured in feet (boat_measured_in = 3), and the papers' boat_tonnage_reported when its size comes from its registration papers (boat_measured_in = 1).
| rule | region_code | hh_id |
|---|---|---|
M1 |
02 |
… |
U3 |
11 |
… |
Tools: module 4 (30_edit_rules.py): rules as data, run to a failure report; in R each rule is a case_when, and here each is a boolean mask over its table.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| A rule missing from households, by rule | Its mask is never True: often a comparison with a blank, which pandas makes False or missing. | how the rule treats a blank, in the table above |
| M4 or M5 fails hundreds of households | A blank made a failure where it only means "not asked": a child under 10 has no mem_role_operator, a child under 6 no mem_education, and a blank compared with 1 is missing, not False. |
read a flag as True only where it is 1; M5's scope, members 6 or over |
| C1 finds fewer households than you expect | A blank species was let through: notna() & ~isin(...) passes it, and the table says a blank fails. |
C1 |
| U3 fails nearly every unit without a boat | The largest boat of no boats is missing, and the comparison made it a failure. | a unit with no boat must be 1 |
| B3 fails every boat measured in feet, or every boat from its papers | The meters factor, 0.212, used for feet, or the papers' figure left out. | the three ways a tonnage is known |
| U1, U2 or H1 too many in the small batch | Keys compared without region_code, so region 11's households meet region 02's. |
the region in every key |
| H1 is wrong for one household | The member rows were counted with clean=False, or households with no member rows were dropped by the join. |
count after the removals; how="left" |
Rule ids like m1 or M01 |
The check compares the ids as written. | the ids of codebook_rules.csv |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Each rule is a mask over the table it is about: True where a row fails. The report is every failing row's household, with its rule, stacked. Where the table says a blank fails, the mask makes it True on purpose; where a blank only means "not asked", the mask makes it False.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def rules_report(folder: Path) -> pd.DataFrame: """Every rule of the codebook but C2 and C3, and every household of the batch in `folder` that fails it.""" # Exercise K1.3: what goes in, what comes out and how it is checked are in the text above this cell. household = ["region_code", "hh_id"]
def child(name: str) -> pd.DataFrame: prefix = CHILD_PREFIX[name] return course.table(name, folder=folder).rename(columns={f"{prefix}_operator_line": "operator_line", f"{prefix}_unit_no": "unit_no"})
def known(mask: pd.Series) -> pd.Series: return mask.astype("boolean").fillna(False).astype(bool)
def yes(column: pd.Series) -> pd.Series: return known(column.eq(1))
members = course.table("member", folder=folder) households = course.table("household", folder=folder) units = course.table("fishing_unit", folder=folder) boats, catch, crew = child("boat"), child("catch"), child("crew") education = set(course.codes("education")["code"]) species = set(course.codes("species")["code"]) failures = []
def fail(rule: str, table: pd.DataFrame, mask: pd.Series) -> None: failures.append(table.loc[mask.astype("boolean").fillna(True).astype(bool), household].assign(rule=rule))
age = members["mem_age"] fail("M1", members, ~members["mem_sex"].isin([1, 2])) fail("M2", members, ~age.between(0, 110)) answered = members[["mem_fished", "mem_role_operator", "mem_role_crew", "mem_role_hired", "mem_role_shore"]].notna().any(axis=1) fail("M3", members, (age < 10) & answered) fail("M4", members, yes(members["mem_role_operator"]) & (age < 16)) fail("M5", members, known(age >= 6) & ~members["mem_education"].isin(education)) roles = members[["mem_role_operator", "mem_role_crew", "mem_role_hired", "mem_role_shore"]].apply(yes).any(axis=1) fail("M6", members, yes(members["mem_fished"]) & ~roles) rows = members.groupby(household).size().rename("rows").reset_index() sizes = households.merge(rows, on=household, how="left").fillna({"rows": 0}) fail("H1", sizes, sizes["hh_roster_members"] != sizes["rows"]) fail("U1", units, units.duplicated(UNIT_KEY, keep=False)) named = units.groupby(household + ["operator_line"])["unit_no"].nunique().rename("named").reset_index() runners = members[household + ["mem_line", "mem_role_operator", "mem_units_run"]].rename(columns={"mem_line": "operator_line"}) operators = units.merge(runners, on=household + ["operator_line"], how="left").merge(named, on=household + ["operator_line"], how="left") fail("U2", operators, ~(yes(operators["mem_role_operator"]) & known(operators["mem_units_run"] == operators["named"]))) volume = boats["boat_length"] * boats["boat_beam"] * boats["boat_depth"] measured = boats["boat_measured_in"] boats["gt"] = (volume * 0.212).where(measured == 2, (volume * 0.006).where(measured == 3, boats["boat_tonnage_reported"])) per_unit = boats.groupby(UNIT_KEY).agg(largest=("gt", "max"), boat_rows=("gt", "size")).reset_index() checked = units.merge(per_unit, on=UNIT_KEY, how="left").fillna({"boat_rows": 0}) fail("U3", checked, checked["unit_scale"] != np.where(checked["largest"] >= 5.0, 2, 1)) fail("U4", units, ~units["unit_uses_boat"].isin([0, 1])) fail("U5", checked, checked["unit_uses_boat"] != np.where(checked["boat_rows"] > 0, 1, 0)) hired = crew.loc[yes(crew["crew_hired"]), UNIT_KEY].drop_duplicates().assign(hired_row=True) hires = units.merge(hired, on=UNIT_KEY, how="left") fail("U6", hires, yes(hires["unit_hired_crew"]) & hires["hired_row"].isna()) fail("U7", checked, checked["unit_boats"].fillna(0) != checked["boat_rows"]) fail("U8", units, ~units["unit_months_active"].between(1, 12)) fail("B1", boats, ~boats["boat_hull"].isin([1, 2, 3]) | ~boats["boat_engine"].isin([0, 1, 2])) fail("B2", boats, known(boats["boat_engine"] == 0) & known(boats["gt"] >= 5.0)) fail("B3", boats, (boats["boat_tonnage"] - boats["gt"]).abs() > 0.01) fail("B4", boats, boats["boat_engine_hp"].isna() != boats["boat_engine"].eq(0)) fail("B5", boats, boats["boat_reg_no"].notna() & boats.duplicated(household + ["boat_reg_no"], keep=False)) fail("C1", catch, ~catch["catch_species"].isin(species)) fail("C4", catch, catch.duplicated(UNIT_KEY + ["catch_species"], keep=False)) fail("W1", crew, ~crew["crew_sex"].isin([1, 2])) report = pd.concat(failures, ignore_index=True)[["rule", *household]].drop_duplicates() return report.sort_values(["rule", *household]).reset_index(drop=True)Why each part is there
fail(rule, table, mask)keeps the households where the mask is True, andfillna(True)makes a comparison with a blank a failure, as "blank fails" asks.isinis never blank:~isin([1, 2])fails a blank sex (M1), hull (B1), species (C1) or crew sex (W1) by itself.- A yes-or-no flag is read with
yes(), and a scope such as "a member 6 or over" withknown(): both are False on a blank. A child under 10 has nomem_role_operator, and withfillna(True)alone M4 would fail every child. - H1, U5 and U7 count rows of another table per household or unit and join the counts with
how="left", so a household with no member rows, or a unit with no boat rows, counts 0. - U2 joins each unit to the member whose
mem_lineis itsoperator_line; a missing member leavesmem_role_operatorblank, whichyes()reads as not 1, a failure. The count is of distinctunit_no, so a unit entered twice is U1's failure and not U2's. - The boat's tonnage comes from its dimensions in the unit it was measured in, or from its papers. U3 compares each unit's largest boat with its scale; a unit with no boat gets a missing maximum,
>= 5is False, so it must be 1. Dimensions written in inches under the code for feet show here: a boat of thousands of tons in a unit that calls itself small-scale. - B3 compares the stored tonnage with the recomputed one within 0.01, because the stored one is rounded to hundredths.
drop_duplicatesleaves each rule and household once, which is what the check reads.
Exercise K1.4. The domain table
The task
Why it matters: this is the director's table: the estimated number of fishing units in each province, small-scale and large-scale, each with the standard error and the CV that say how far to trust it.
Input → output: a batch's folder → one row per province of the batch and scale, with region_code and province_code as zero-padded text, scale (small-scale for a unit with unit_scale = 1, large-scale for unit_scale = 2, as reported), and total, se and cv (the CV in percent: 100 × SE ÷ total). A province with no unit of a scale gets the row anyway, with total 0, SE 0 and a blank CV.
| region_code | province_code | scale | total | se | cv |
|---|---|---|---|---|---|
02 |
015 |
large-scale |
… | … | … |
02 |
015 |
small-scale |
… | … | … |
The design, as module 6 (50_design_estimates.py) set it out: the unit is the household, with weight sel_final_weight; a household's value is its number of units of the scale, from the flat table. The strata are province × sel_stratum. The PSU is the enumeration area sel_ea, numbered within its province; in stratum F, where every registered large unit is taken, each household is its own PSU. The finite population correction uses each stratum's number of PSUs, eas_in_frame in the batch's stratum_counts.csv, as a count. The variance is the stratified between-PSU (Taylor) variance with that correction. No stratum of the batch has a single PSU.
The check compares totals and SEs to four significant figures and CVs to three, so svy and a function your group writes from the formula both pass.
Tools: svy's Design(stratum=, psu=, wgt=, pop_size=) and Sample(...).estimation.total(y=, by=) (module 6, section 2), on a polars table; or the formula as your own function (module 6, section 4). In ReGenesees you write the correction as fpc = ~fpc in e.svydesign, where it may be the stratum's count or its sampled share (its documentation, checked 2026-11-20); svy's pop_size= wants the count.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| Totals right, every SE too large | The finite population correction left out. | pop_size= with eas_in_frame |
| ValueError: Invalid FPC values from svy | The correction given as a sampling fraction, eas_sampled ÷ eas_in_frame, as ReGenesees also accepts; svy wants the count of PSUs. |
eas_in_frame, as it is |
| ValueError: singleton PSU(s) detected from svy, or SEs of 0 in stratum F from your own function | Stratum F's households all have a blank sel_ea, so they form one PSU. |
each household its own PSU in stratum F |
| Every household of stratum F is missing, and the totals are too small | A groupby that drops blank keys: sel_ea is blank in stratum F. |
dropna=False, or leave sel_ea out of the grouping |
| Totals too large | Each unit's row taken as a household, or the unit entered twice counted twice. | one row per household, from the flat table |
| CVs a hundred times too small | svy's CV is a fraction. | 100 × SE ÷ total |
| ValueError: You are trying to merge on string and int64 columns for key 'region_code' | The stratum counts' codes are numbers in the CSV, and the flat table's are text. | str.zfill on the counts' codes |
scale with other labels |
The check compares small-scale and large-scale as written. |
the labels |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Turn the flat table into one row per household with its count of small-scale and of large-scale units, give each household its stratum, PSU and stratum's PSU count, and let svy estimate both totals by province.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def domain_table(folder: Path) -> pd.DataFrame: """The estimated number of fishing units by province and scale in the batch in `folder`, with SE and CV (%).""" # Exercise K1.4: what goes in, what comes out and how it is checked are in the text above this cell. flat = flat_table(folder) counts = pd.read_csv(Path(folder) / "stratum_counts.csv") counts["region_code"] = counts["region_code"].astype("string").str.zfill(2) counts["province_code"] = counts["province_code"].astype("string").str.zfill(3) counts = counts.rename(columns={"eas_in_frame": "psus_in_stratum"}) flat = flat.assign(small=(flat["unit_scale"] == 1).astype(int), large=(flat["unit_scale"] == 2).astype(int)) design = ["region_code", "province_code", "hh_id", "sel_stratum", "sel_ea", "sel_final_weight"] homes = flat.groupby(design, as_index=False, dropna=False)[["small", "large"]].sum() homes = homes.merge(counts[["region_code", "province_code", "sel_stratum", "psus_in_stratum"]], on=["region_code", "province_code", "sel_stratum"], how="left", validate="many_to_one") homes["province"] = homes["region_code"] + "-" + homes["province_code"] homes["stratum_id"] = homes["province"] + "-" + homes["sel_stratum"] area = homes["stratum_id"] + "-" + homes["sel_ea"].astype("Int64").astype("string") homes["psu_id"] = area.where(homes["sel_stratum"] != "F", homes["region_code"] + "-hh-" + homes["hh_id"].astype("string")) columns = ["province", "stratum_id", "psu_id", "sel_final_weight", "psus_in_stratum", "small", "large"] sample = svy.Sample(data=pl.from_pandas(homes[columns].astype({"province": str, "stratum_id": str, "psu_id": str})), design=svy.Design(stratum="stratum_id", psu="psu_id", wgt="sel_final_weight", pop_size="psus_in_stratum")) parts = [] for column, scale in (("large", "large-scale"), ("small", "small-scale")): estimate = sample.estimation.total(y=column, by="province").to_polars().to_pandas() parts.append(pd.DataFrame({"region_code": estimate["province"].str[:2], "province_code": estimate["province"].str[3:], "scale": scale, "total": estimate["est"], "se": estimate["se"], "cv": 100 * estimate["se"] / estimate["est"].where(estimate["est"] != 0)})) return pd.concat(parts, ignore_index=True).sort_values(["region_code", "province_code", "scale"]).reset_index(drop=True)Why each part is there
- The flat table (Exercise K1.1) is the input, so a unit entered twice is counted once and the removed households are out. Summing the two 0/1 columns per household gives each household's values; the design columns are the same on all its rows, so they go into the
groupby, withdropna=Falsebecausesel_eais blank in stratum F. - The stratum counts' codes are numbers in the CSV;
str.zfillmakes them the flat table's text before the join, andvalidate="many_to_one"stops if a stratum is listed twice. - The stratum is region, province and
sel_stratumtogether, and the PSU is written with its stratum in front, so it names one area wherever it is read: area 3001 of province 015 is another area than area 3001 of province 031. In stratum F,sel_eais blank for every household, and svy would refuse a stratum of one PSU, so each household becomes its own PSU from its id, ascourse.design_frame()does for the first batch. pop_size="psus_in_stratum"gives svy the stratum's count of PSUs, from which it forms the correction 1 − n/N. The province is the domain (by=); it is a group of whole strata, so its estimate is the stratified estimate within it.- svy gives the CV as a fraction; the brief asks for percent. A total of 0 has an SE of 0 and no CV, which the division gives as a missing value.
- The same figures come from the formula: for each stratum h, (1 − n_h/N_h) × n_h/(n_h − 1) × the sum over its PSUs of (z − z̄)², z being a PSU's weighted total, summed over the province's strata; the square root is the SE.
Exercise K1.5. The workbook
The task
Why it matters: the director reads Excel, and so do the editors. A table retyped from a notebook is a table with typing errors in it; a workbook written by code is the same every time it runs.
Input → output: a batch's folder and a file path → the workbook written at that path (its folder made if need be), and the path given back. It has four sheets, in this order: Estimates, Rule failures, Orphans, Notes.
Estimatesholds the domain table (output 4),Rule failuresthe rules report (output 3) andOrphansthe matching report (output 2), each with these columns in this order:region_code,province_code,scale,total,se,cv;region_code,hh_id,rule;region_code,hh_id,operator_line,unit_no,side.- A title and a note above a table are welcome. The check finds each table by its header row, the first row whose first cell is
region_code, and reads down to the first row whose first cell is empty. - Codes are text (
02,015), and totals, SEs and CVs are numbers Excel can add up, rounded or not. Notessays which weight the estimates use, naming the variablesel_final_weight, where the data came from and when the workbook was made.
Tools: module 7, section 1 (60_publish_tables.py): pd.ExcelWriter with startrow= and index=False, and openpyxl for titles and number formats; in R, writexl.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
'sheets' in another order, or with Sheet among them |
The sheets are written in another order, or the empty sheet openpyxl starts with is still there. | the four names, in order |
no table found |
The header row's first cell is not region_code: to_excel writes the index as the first column unless told not to. |
index=False |
'codes as text': False |
A code was written as a number (2 for 02), or turned into one on the way. |
the codes' type before writing |
'figures as numbers': False |
Totals or SEs written as formatted text ("5,131"), which Excel cannot add up. |
a number format, not a text |
'notes name sel_final_weight': False |
The notes describe the weight in words only. | name the variable |
| The tables found, the figures wrong | Outputs 2 to 4 are not green yet: the workbook only writes what they give. | Exercises K1.2 to K1.4 |
| PermissionError on the Try it | The file is open in Excel, which locks it. | close it, run again |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Write the three reports the group already has, each below a title and a note on its own sheet, without the index, and a notes sheet that says how the numbers were made; then give back where the file is.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def write_workbook(folder: Path, path: Path) -> Path: """The director's workbook for the batch in `folder`, written at `path`: estimates, rule failures, orphans, notes.""" # Exercise K1.5: what goes in, what comes out and how it is checked are in the text above this cell. path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) sheets = { "Estimates": ("Fishing units by province and scale, with standard errors and CVs (%)", domain_table(folder)), "Rule failures": ("Households that fail a rule of the codebook", rules_report(folder)[["region_code", "hh_id", "rule"]]), "Orphans": ("Units without catch, and catch without a unit", matching_report(folder)), } with pd.ExcelWriter(path, engine="openpyxl") as writer: for name, (title, table) in sheets.items(): table.to_excel(writer, sheet_name=name, startrow=3, index=False) sheet = writer.sheets[name] sheet["A1"] = title sheet["A2"] = f"Survey of Fishing Households 2025, second batch, {Path(folder).name}" if name == "Estimates": for row in sheet.iter_rows(min_row=5, min_col=4, max_col=5): for cell in row: cell.number_format = "#,##0" notes = writer.book.create_sheet("Notes") for line in ["Notes", "Estimates are weighted with the final weight sel_final_weight, under the design: strata province by sel_stratum, PSU the enumeration area (in stratum F the household), fpc from eas_in_frame.", f"Data: {Path(folder).as_posix()}", f"Made on {date.today().isoformat()}"]: notes.append([line]) return pathWhy each part is there
- The workbook calls the group's own outputs 2, 3 and 4: the director's sheet and the domain table can never disagree, because one is written from the other.
startrow=3leaves rows 1 to 3 for a title and a note, andindex=Falsekeeps pandas from writing the index as the first column, which would put a number, notregion_code, in the header row's first cell.- The codes are text in the tables, so
to_excelwrites them as text and02keeps its zero; the totals are floats and stay numbers. The number format#,##0shows whole units without changing the stored value. Notesnames the weight by its variable, the data's folder and the date: what a reader needs to reproduce the table, or to know it is stale.path.parent.mkdir(parents=True, exist_ok=True)makes the folder, so the function runs on a fresh copy of the course folder.
Exercise K1.6. The review table
The task
Why it matters: the supervisors can revisit 100 households. A list in which the planted defects sit at the top sends them where the errors are; a list in household order sends them nowhere in particular.
Input → output: a batch's folder → one row per household of the batch (after the removals), with region_code, hh_id and rank (1 is the first to revisit, then 2, 3 and so on, each rank once); add score and reasons so a supervisor knows why a household is there. What you rank on is your group's design: the rules and the matching report, the outliers, ratios and relations of module 8 (70_anomalies_rules.py), a detector of module 9 (80_anomalies_ml.py), or a mix.
| region_code | hh_id | rank | score | reasons |
|---|---|---|---|---|
11 |
… | 1 | … | a boat's size; a rule |
02 |
… | 2 | … | … |
How it is judged. The check reads the table sorted by rank and counts how many of the batch's planted defects are among its first 100 rows. It passes at 80% or more (the recall at 100). A planted defect is a household that the course changed on purpose. Two kinds do not count: the removed households and voided rows, which your flat table already leaves out, and the households of an area stratum that run a large-scale unit, which are no error but a heavy weight in a small domain. The course does not ship its list. The check holds a digest of each planted household instead: a code of 16 characters made from its region and household id by a one-way function (SHA-256), from which the household cannot be read. The check makes the same code from each household in your table and counts the matches. The cell below the check shows your recall as a number, for the demo.
Tools: module 8, section 5 (a review table from ranked flags) and module 9, section 3 (judging a detector by recall).
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
'rows' differs from the flat table's households |
Only the flagged households are listed, or the removed ones are back. | every household after the removals |
'one row per household': False |
A household listed once per flag. | one row per region_code and hh_id |
'ranks 1 to n': False |
Ranks that start at 0, ties given the same rank, or a rank per flag. | range(1, n + 1) after sorting |
| The recall is under the bar | The ranking rests on part of the evidence: rules only, or one detector alone. | the matching report, the rules, module 8's ratios and relations, and the text answers, together |
| The recall is under the bar on the batch only | Flags compared with hh_id alone: in the small batch every household is in the first 100 rows anyway. |
the region in every key |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Collect every flag the group can raise on a household (each rule it fails, each unmatched key, and the checks of what is unlikely that no rule makes), add up points per household, and rank by the sum: the households with most evidence come first, the others follow in household order.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def review_table(folder: Path) -> pd.DataFrame: """Every household of the batch in `folder`, ranked for revisiting: rank 1 first, with its score and reasons.""" # Exercise K1.6: what goes in, what comes out and how it is checked are in the text above this cell. household = ["region_code", "hh_id"]
def child(name: str) -> pd.DataFrame: prefix = CHILD_PREFIX[name] return course.table(name, folder=folder).rename(columns={f"{prefix}_operator_line": "operator_line", f"{prefix}_unit_no": "unit_no"})
rules = rules_report(folder) flags = [rules[household].assign(points=np.where(rules["rule"] == "B5", 1, 2), reason="a rule"), matching_report(folder)[household].assign(points=2, reason="a key")] units = course.table("fishing_unit", folder=folder)[UNIT_KEY].drop_duplicates() crew = child("crew").merge(units, on=UNIT_KEY, how="left", indicator=True) flags.append(crew.loc[crew["_merge"] == "left_only", household].assign(points=2, reason="a crew row with no unit")) homes = course.table("household", folder=folder).merge(course.table("selection", folder=folder), on=household) ratio = homes["sel_final_weight"] / homes.groupby(["region_code", "province_code", "sel_stratum"])["sel_final_weight"].transform("median") flags.append(homes.loc[(ratio > 3) | (ratio < 1 / 3), household].assign(points=2, reason="the weight")) numbered = (homes["sel_ea"] // 1000).map({1: "A", 2: "B", 3: "C"}) flags.append(homes.loc[numbered.notna() & (numbered != homes["sel_stratum"]), household].assign(points=2, reason="the area's stratum")) boats = child("boat") meters = boats["boat_length"].where(boats["boat_measured_in"] == 2, boats["boat_length"] / 3.281) limit = boats["boat_hull"].map({1: 10, 2: 17, 3: 45}) flags.append(boats.loc[(meters > limit).fillna(False), household].assign(points=2, reason="a boat's size")) catch = child("catch") listed = {name.lower() for name in course.codes("species").query("code < 997")["name"]} named = catch["catch_species_text"].fillna("").str.strip().str.lower().isin(listed) flags.append(catch.loc[(catch["catch_species"] == 997) & named, household].assign(points=2, reason="a listed species as other")) raised = pd.concat(flags, ignore_index=True) scored = raised.groupby(household).agg(score=("points", "sum"), reasons=("reason", lambda r: "; ".join(sorted(set(r))))).reset_index() table = homes[household].merge(scored, on=household, how="left").fillna({"score": 0, "reasons": ""}) table = table.sort_values(["score", "region_code", "hh_id"], ascending=[False, True, True]).reset_index(drop=True) table["rank"] = range(1, len(table) + 1) return table[["region_code", "hh_id", "rank", "score", "reasons"]]Why each part is there
- The rules report and the matching report are flags already: a household in either has something an editor must look at, so each rule and each unmatched key counts two points. B5 counts one: a registration number on two rows is most often a boat two units of the household share, which is no error.
- Module 3 matched every child table, not only the catch: a crew row whose key matches no unit is a flag too.
- A weight more than three times, or less than a third of, its stratum's median weight in its province is treated as a weight outlier: a simpler rule than module 8's (section 3 compares the final weight with the design weight), enough to rank the planted ones first. It matters because such a weight moves every estimate the household is in.
- An enumeration area is numbered by its stratum (from 1001 in A, 2001 in B, 3001 in C, as the codebook says), so a household whose area number belongs to another stratum than its
sel_stratumhas its stratum or its area wrong. - A boat longer than its hull allows is unlikely though no rule forbids it: the limits here are 10 meters for a canoe, 17 for an outrigger boat and 45 for a decked vessel, with feet turned into meters first. Feet written under the code for meters make an outrigger longer than 17 "meters"; inches written under the code for feet, a kind no module planted, make canoes and outrigger boats longer still.
- The other kind no module planted is a listed species written under the code for other species (997), its name in
catch_species_text: the code passes C1, and only reading the text against the species list finds it. - Sorting by score, then region and household, puts every flagged household first and gives each rank once; households with no flag follow in household order, so the table has every household and ranks 1 to n.