Code Reference¶
Generated API documentation for the modules that implement harmonization,
data loading, and bootstrap analysis. The Streamlit UI layer (src/ui/) is
presentation glue over these modules and is not documented here.
Harmonization¶
src.data.harmonizer
¶
Data harmonization functions for multi-cycle CCHS analysis.
build_crosswalk
¶
Build a crosswalk mapping reference-cycle variable names to each cycle's matching variable name, by fuzzy-matching variable descriptions.
The last entry in cycles is treated as the reference cycle: every
other cycle's variable is matched against each reference variable's
description via difflib.get_close_matches (single best match). This is
a heuristic textual match, not an authoritative concordance - unmatched
or ambiguous descriptions are recorded as None and should be reviewed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycles
|
list
|
Cycle years in order, with the reference cycle last |
required |
descriptions
|
dict
|
Dict mapping cycle -> {variable_name: description} |
required |
cutoff
|
float
|
difflib similarity cutoff (0-1) for a match to count |
0.6
|
Returns:
| Type | Description |
|---|---|
dict
|
Dict mapping reference_var -> {cycle: cycle_specific_var_or_None} |
Source code in src/data/harmonizer.py
auto_harmonize
¶
Normalize a raw codebook category label into a shared harmonized category.
Order matters: "not stated", "valid skip", "don't know", and "female" each contain "no" or "male" as a substring (e.g. "not stated", "female"), so the more specific phrases must be checked before the shorter "no"/"male" rules or they get misclassified.
Source code in src/data/harmonizer.py
get_common_harmonized_vars
¶
Get harmonized variables that exist in all specified cycles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycles
|
list
|
List of cycle years |
required |
crosswalk
|
dict
|
Crosswalk dictionary |
required |
data_dict
|
dict
|
Dictionary mapping cycle -> DataFrame (with cycle-specific column names) |
required |
Returns:
| Type | Description |
|---|---|
list
|
List of harmonized variable names available in all cycles |
Source code in src/data/harmonizer.py
src.data.codebook_extractor
¶
Parsing logic for Statistics Canada CCHS Data Dictionary/Freqs PDF codebooks.
parse_codebook_lines
¶
Parse codebook text lines into a variable -> {description, categories} dict.
Expects the Statistics Canada CCHS Data Dictionary/Freqs layout: each variable starts with a "Variable Name:" line, has a "Concept:" line for its description, and an "Answer Categories" section listing "label code frequency frequency%" rows until a blank line or a Note:/Source:/ Universe:/Total line ends the section.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
Iterable[str]
|
An iterable of text lines, in document order (may span multiple PDF pages - state carries across page boundaries the same way it does across lines within a page). |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dict mapping variable_name -> {"description": str, "categories": {code: label}} |
Source code in src/data/codebook_extractor.py
extract_variables_with_categories
¶
Extract variable/category metadata from a CCHS codebook PDF.
Source code in src/data/codebook_extractor.py
Data loading and precomputation¶
src.data.loader
¶
Data loading functions for CCHS analysis.
build_harmonization_mapping
¶
Build a safe rename mapping for one cycle.
If multiple harmonized variables point at the same source column, prefer the identity mapping (e.g. GEODVHR4 -> GEODVHR4) and otherwise keep the first mapping encountered. This prevents exact-match geography columns from being renamed away by alias entries later in the crosswalk.
Source code in src/data/loader.py
restore_geography_aliases
¶
Restore expected geography columns when an older harmonization pass renamed them to alias fields.
Source code in src/data/loader.py
load_cycle_data
¶
Load main data and bootstrap data for a specific cycle.
Source code in src/data/loader.py
load_variable_descriptions
¶
Load variable descriptions from harmonized JSON file for a specific cycle.
Source code in src/data/loader.py
load_json_variable_descriptions
¶
Load JSON variable descriptions for a specific cycle (legacy function for compatibility).
Source code in src/data/loader.py
load_cycle_variable_info
¶
Load complete variable information (descriptions AND categories) for a specific cycle.
Source code in src/data/loader.py
load_crosswalk
¶
Load harmonization crosswalk.
Source code in src/data/loader.py
load_categories
¶
Load harmonization categories.
Source code in src/data/loader.py
load_ontario_csd_lookup
¶
Load the Ontario census subdivision code-to-name lookup.
Source code in src/data/loader.py
load_ontario_official_municipalities
¶
Load the official Ontario municipalities lookup keyed by CSD code.
Source code in src/data/loader.py
merge_data
¶
Merge survey records with bootstrap weights without pooling cycles.
Multi-cycle trend analysis keeps each survey cycle independent. When a
CYCLE column is present, it must be present on both frames and becomes
part of the join key. The one-to-one validation prevents repeated IDs from
silently multiplying records and biasing estimates.
Source code in src/data/loader.py
load_multi_cycle_data
¶
Load and harmonize data from multiple cycles using pre-computed crosswalk. This uses simple column renaming (no value transformation) for performance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycles
|
list
|
List of cycle years to load (e.g., ["2021", "2022", "2023"]) |
required |
crosswalk
|
dict
|
Crosswalk dictionary mapping harmonized_var -> {cycle: cycle_specific_var} |
required |
categories
|
dict
|
Categories dictionary (not used, kept for compatibility) |
required |
Returns:
| Type | Description |
|---|---|
|
Tuple of (combined_data, combined_bootstrap_data) or (None, None) if error |
Source code in src/data/loader.py
src.data.precompute
¶
Precompute harmonized datasets for multi-cycle analysis.
check_precompute_status
¶
Check which cycles have been precomputed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycles
|
List[str]
|
List of cycle years (e.g., ["2021", "2022", "2023"]) |
required |
save_dir
|
Path
|
Directory where precomputed data is stored |
PRECOMPUTE_DIR
|
Returns:
| Type | Description |
|---|---|
Dict[str, bool]
|
Dictionary mapping cycle -> True/False (precomputed status) |
Source code in src/data/precompute.py
load_precomputed_data
¶
Load precomputed harmonized data for a cycle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycle
|
str
|
Cycle year (e.g., "2021") |
required |
save_dir
|
Path
|
Directory where precomputed data is stored |
PRECOMPUTE_DIR
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with harmonized variables |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If precomputed data doesn't exist |
Source code in src/data/precompute.py
load_precomputed_bootstrap
¶
Load precomputed bootstrap weights for a cycle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycle
|
str
|
Cycle year (e.g., "2021") |
required |
save_dir
|
Path
|
Directory where precomputed data is stored |
PRECOMPUTE_DIR
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with bootstrap weights (ONT_ID and BSW columns) |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If precomputed data doesn't exist |
Source code in src/data/precompute.py
load_precomputed_metadata
¶
Load metadata for precomputed cycle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycle
|
str
|
Cycle year (e.g., "2021") |
required |
save_dir
|
Path
|
Directory where precomputed data is stored |
PRECOMPUTE_DIR
|
Returns:
| Type | Description |
|---|---|
Dict
|
Dictionary with metadata (available_vars, record_count, etc.) |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If metadata doesn't exist |
Source code in src/data/precompute.py
get_common_variables
¶
Get variables available across all selected cycles using precomputed metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycles
|
List[str]
|
List of cycle years |
required |
save_dir
|
Path
|
Directory where precomputed data is stored |
PRECOMPUTE_DIR
|
Returns:
| Type | Description |
|---|---|
List[str]
|
Sorted list of common harmonized variable names |
Source code in src/data/precompute.py
precompute_cycle_data
¶
Precompute harmonized data for a single cycle.
Creates: - harmonized_data_{cycle}.parquet: Harmonized survey data - harmonized_bootstrap_{cycle}.parquet: Bootstrap weights with ONT_ID - metadata_{cycle}.json: Variable metadata and availability
Category value labels are not baked in here - they're resolved at display time from categories.json via get_value_label().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycle
|
str
|
Cycle year (e.g., "2021") |
required |
crosswalk
|
Dict
|
Crosswalk dictionary for variable harmonization |
required |
data_path
|
str
|
Path to raw data files |
'data'
|
save_dir
|
Path
|
Directory to save precomputed files |
PRECOMPUTE_DIR
|
Returns:
| Type | Description |
|---|---|
Tuple[DataFrame, DataFrame, Dict]
|
Tuple of (harmonized_data, harmonized_bootstrap, metadata) |
Source code in src/data/precompute.py
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 | |
precompute_all_cycles
¶
Precompute data for all specified cycles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycles
|
List[str]
|
List of cycle years to precompute |
required |
crosswalk
|
Dict
|
Crosswalk dictionary |
required |
data_path
|
str
|
Path to raw data files |
'data'
|
save_dir
|
Path
|
Directory to save precomputed files |
PRECOMPUTE_DIR
|
Returns:
| Type | Description |
|---|---|
Dict[str, Dict]
|
Dictionary mapping cycle -> {'data': DataFrame, 'bootstrap': DataFrame, 'metadata': Dict} |
Source code in src/data/precompute.py
run_precompute_workflow
¶
Run the full precompute workflow and return a compact status summary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycles
|
List[str]
|
List of cycle years to precompute |
required |
crosswalk
|
Dict
|
Crosswalk dictionary |
required |
data_path
|
str
|
Path to raw data files |
'data'
|
save_dir
|
Path
|
Directory to save precomputed files |
PRECOMPUTE_DIR
|
Returns:
| Type | Description |
|---|---|
Dict
|
Dictionary with success flag, validation results, and per-cycle summary. |
Source code in src/data/precompute.py
load_variable_availability_index
¶
Load the variable availability index (which variables exist in which cycles).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_dir
|
Path
|
Directory where precomputed data is stored |
PRECOMPUTE_DIR
|
Returns:
| Type | Description |
|---|---|
Dict[str, List[str]]
|
Dictionary mapping variable_name -> [list of cycles where it exists] |
Source code in src/data/precompute.py
create_variable_availability_index
¶
Create a variable availability index from precomputed metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycles
|
List[str]
|
List of cycles to include in index |
required |
save_dir
|
Path
|
Directory where precomputed data is stored |
PRECOMPUTE_DIR
|
Returns:
| Type | Description |
|---|---|
Dict[str, List[str]]
|
Dictionary mapping variable_name -> [list of cycles where it exists] |
Source code in src/data/precompute.py
validate_precomputed_data
¶
Validate that precomputed data exists and is loadable for specified cycles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycles
|
List[str]
|
List of cycles to validate |
required |
save_dir
|
Path
|
Directory where precomputed data is stored |
PRECOMPUTE_DIR
|
Returns:
| Type | Description |
|---|---|
Dict[str, bool]
|
Dictionary mapping cycle -> True (valid) or False (invalid/missing) |
Source code in src/data/precompute.py
src.data.smart_loader
¶
Smart data loader that uses precomputed data when available, falls back to real-time.
smart_load_cycle
¶
Smart loader that uses precomputed data when available, falls back to real-time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycle
|
str
|
Cycle name (e.g., "2021") |
required |
crosswalk
|
Dict
|
Crosswalk dictionary (needed for real-time harmonization) |
None
|
use_precompute
|
bool
|
Whether to attempt using precomputed data |
True
|
Returns:
| Type | Description |
|---|---|
Tuple[DataFrame, DataFrame, Dict, bool]
|
Tuple of (harmonized_data, bootstrap_data, metadata, is_precomputed) |
Source code in src/data/smart_loader.py
smart_load_multiple_cycles
¶
Load multiple cycles using smart loading.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycles
|
List[str]
|
List of cycle years to load |
required |
crosswalk
|
Dict
|
Crosswalk dictionary (needed for real-time fallback) |
None
|
use_precompute
|
bool
|
Whether to attempt using precomputed data |
True
|
Returns:
| Type | Description |
|---|---|
Dict[str, Dict]
|
Dict mapping cycle -> { 'data': DataFrame, 'bootstrap': DataFrame, 'metadata': Dict, 'precomputed': bool |
Dict[str, Dict]
|
} |
Source code in src/data/smart_loader.py
get_common_vars_smart
¶
Get common variables across cycles using smart approach. Uses precomputed metadata when available for speed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycles
|
List[str]
|
List of cycle years |
required |
crosswalk
|
Dict
|
Crosswalk dictionary (needed for real-time fallback) |
None
|
use_precompute
|
bool
|
Whether to attempt using precomputed data |
True
|
Returns:
| Type | Description |
|---|---|
List[str]
|
Sorted list of common harmonized variable names |
Source code in src/data/smart_loader.py
load_and_combine_cycles_smart
¶
Load multiple cycles and combine into single DataFrames. Smart loader that uses precomputed data when available.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycles
|
List[str]
|
List of cycle years to load and combine |
required |
crosswalk
|
Dict
|
Crosswalk dictionary (needed for real-time fallback) |
None
|
use_precompute
|
bool
|
Whether to attempt using precomputed data |
True
|
Returns:
| Type | Description |
|---|---|
Tuple[DataFrame, DataFrame]
|
Tuple of (combined_data, combined_bootstrap) |
Source code in src/data/smart_loader.py
get_precompute_summary
¶
Get summary of precompute status for cycles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycles
|
List[str]
|
List of cycle years to check |
required |
Returns:
| Type | Description |
|---|---|
Dict
|
Dictionary with summary information |
Source code in src/data/smart_loader.py
src.data.processor
¶
Data processing functions for CCHS analysis.
create_age_groups
¶
Create age groups from the age column with flexible bin configuration. Automatically detects the correct age column for each cycle: - 2021: DHH_AGE - 2022/2023: AWCAGE - Multi-cycle harmonized: AWCAGE
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame containing age data |
required | |
age_column
|
Optional specific age column name. If None, auto-detects. |
None
|
|
age_bins
|
List of bin edges (e.g., [0, 15, 25, 45, 65, 120]) |
None
|
|
age_labels
|
List of labels for bins (e.g., ['0-14', '15-24', '25-44', '45-64', '65+']) |
None
|
Returns:
| Type | Description |
|---|---|
|
DataFrame with AgeGroup column added |
Source code in src/data/processor.py
apply_region_filter
¶
Apply geographic filters using optional district and health region code lists.
Source code in src/data/processor.py
apply_inclusion_flag_filters
¶
Apply inclusion flag filters to the dataset. Works for all cycles (2021, 2022, 2023).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame to filter |
required |
selected_flags
|
dict
|
Dictionary mapping flag_name -> True/False |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Filtered DataFrame |
Source code in src/data/processor.py
Bootstrap analysis and quality¶
src.analysis.bootstrap
¶
Bootstrap analysis functions for CCHS data.
run_bootstrap_analysis_for_all_values
¶
run_bootstrap_analysis_for_all_values(merged_data, variable_col, weight_col=DEFAULT_WEIGHT_COLUMN, standards_cycle=None)
Perform bootstrap analysis using vectorized groupby operations. Computes weighted prevalences and bootstrap variances.
Source code in src/analysis/bootstrap.py
src.analysis.quality
¶
Helpers for applying CCHS 2022+ data quality reporting standards.
calculate_effective_sample_size
¶
Calculate effective sample size for a proportion estimate.
Formula from the CCHS 2022+ standards: (1 - p) / (p * CV^2) where p and CV are expressed as proportions, not percentages.
Source code in src/analysis/quality.py
classify_proportion_release
¶
classify_proportion_release(prevalence_pct, cv_pct, numerator_n, denominator_n, ci_lower=None, ci_upper=None)
Classify a proportion estimate using the CCHS 2022+ A/E/F rules.
Source code in src/analysis/quality.py
apply_cchs_quality_flags
¶
Append CCHS 2022+ release-quality fields to a result dataframe.
Source code in src/analysis/quality.py
src.analysis.comparison
¶
Comparative analysis functions for multi-cycle CCHS data.
compare_cycles
¶
Pivot results to show cycles side-by-side for comparison.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results_df
|
DataFrame
|
DataFrame with columns including 'Variable', 'Value', 'CYCLE', 'Prevalence', etc. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Pivoted DataFrame with cycles as columns |
Source code in src/analysis/comparison.py
calculate_change
¶
Calculate percentage point change between two cycles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycle1_val
|
float
|
Prevalence value from first cycle |
required |
cycle2_val
|
float
|
Prevalence value from second cycle |
required |
Returns:
| Type | Description |
|---|---|
float
|
Percentage point change (cycle2 - cycle1) |
Source code in src/analysis/comparison.py
calculate_percent_change
¶
Calculate percentage change between two cycles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycle1_val
|
float
|
Prevalence value from first cycle |
required |
cycle2_val
|
float
|
Prevalence value from second cycle |
required |
Returns:
| Type | Description |
|---|---|
float
|
Percentage change ((cycle2 - cycle1) / cycle1 * 100) |
Source code in src/analysis/comparison.py
calculate_trend
¶
Calculate trend direction (increasing/decreasing/stable) across cycles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results_df
|
DataFrame
|
DataFrame with 'CYCLE', 'Variable', 'Value', 'Prevalence' columns |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with added 'Trend' column indicating direction |
Source code in src/analysis/comparison.py
test_significance
¶
Test statistical significance of difference between two cycles.
Uses overlapping confidence intervals as a simple test. More sophisticated tests could be added later.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycle1_results
|
DataFrame
|
Results DataFrame for first cycle |
required |
cycle2_results
|
DataFrame
|
Results DataFrame for second cycle |
required |
variable
|
str
|
Variable name to test |
required |
value
|
Optional[str]
|
Optional specific value to test |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with test results including 'significant' boolean |
Source code in src/analysis/comparison.py
create_comparison_summary
¶
Create a summary table comparing cycles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results_df
|
DataFrame
|
DataFrame with cycle comparison results |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Summary DataFrame with comparison statistics |
Source code in src/analysis/comparison.py
Helpers¶
src.utils.helpers
¶
Utility helper functions for the CCHS application.
format_number
¶
Format numbers with different styles.
Source code in src/utils/helpers.py
create_excel_download
¶
Create Excel file in memory for download.
Source code in src/utils/helpers.py
validate_data_columns
¶
Validate that required columns exist in the dataset.
Source code in src/utils/helpers.py
safe_division
¶
Safely divide two numbers, returning default if denominator is zero.
Source code in src/utils/helpers.py
filter_dataframe_by_values
¶
get_memory_usage_mb
¶
get_cycle_varname
¶
Helper to get cycle-specific variable name from harmonization crosswalk.
get_value_label
¶
Helper to get value label for cycle from harmonization categories.
Source code in src/utils/helpers.py
get_cycle_value_label
¶
Get value label from cycle-specific JSON (CCHS_YYYY.json). Used for single-cycle analysis to show proper category labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
varname
|
str
|
Variable name (cycle-specific, not harmonized) |
required |
value
|
The value to get label for |
required | |
cycle_var_info
|
dict
|
Full cycle variable info from CCHS_YYYY.json |
required |
Returns:
| Type | Description |
|---|---|
str
|
Label string or original value if not found |
Source code in src/utils/helpers.py
get_available_harmonized_vars
¶
Helper to get available harmonized variables for the selected cycle and data.
Source code in src/utils/helpers.py
merge_descriptions
¶
create_multi_cycle_excel
¶
Create Excel file with multiple sheets for multi-cycle results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results_df
|
DataFrame
|
DataFrame with multi-cycle results (must contain 'CYCLE' column) |
required |
cycles
|
list
|
List of cycles included in the results |
required |
Returns:
| Type | Description |
|---|---|
bytes
|
Excel file as bytes |
Source code in src/utils/helpers.py
get_inclusion_flags
¶
Detect inclusion flag variables in the dataset. Inclusion flags are identified by having "Inclusion Flag" in their description. Works for all cycles (2021, 2022, 2023).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame with columns |
required |
desc_dict
|
dict
|
Dictionary mapping variable names to descriptions (required) |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary mapping flag_name -> description |