Skip to content
Learn Python with BNHR

Capstone

On this page
  1. Overview
  2. K1.1 · The flat table
  3. K1.2 · The matching report
  4. K1.3 · The rules report
  5. K1.4 · The domain table
  6. K1.5 · The workbook
  7. K1.6 · The review table

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_on filled) or voided in editing (row_void = 1 in household), the households excluded by the sampling side (sel_excluded = 1 in selection) 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_code as zero-padded text (2, 3, 2 and 3 characters); hh_id; the key parts operator_line and unit_no; the unit's scale unit_scale; and its household's stratum sel_stratum, enumeration area sel_ea and final weight sel_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.

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.

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.

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.

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.

  • Estimates holds the domain table (output 4), Rule failures the rules report (output 3) and Orphans the 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.
  • Notes says which weight the estimates use, naming the variable sel_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.

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.

Something new

Identify results
LayerExplore a module
ModuleCollections
AboutModule 3 of Python Essentials: lists, tuples, sets and dictionaries, and a barangay's records as a list of dictionaries. Its sections, its notebooks to read on the web, and the companion's solutions and explanations.
CoursePython Essentials, free