-
Notifications
You must be signed in to change notification settings - Fork 149
Automation of import Finland_Census #2087
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
smarthg-gi
wants to merge
14
commits into
datacommonsorg:master
Choose a base branch
from
smarthg-gi:Finland_Census_automation
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 10 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
fd6f7f2
Automation of import refresh
smarthg-gi 369131a
updating download script after tests
smarthg-gi ac1bff9
updated download script and shell script with suggested changed
smarthg-gi f729202
Merge branch 'datacommonsorg:master' into Finland_Census_automation
smarthg-gi 89792c7
added golden checks
smarthg-gi d55922f
updated manifest cron
smarthg-gi b56e0dd
Updated data_download.py and manifest
smarthg-gi 6104ff2
updated download script
smarthg-gi 66e2531
updated validation config
smarthg-gi a53d2b8
Merge branch 'master' into Finland_Census_automation
smarthg-gi 168b92f
updated goldens
smarthg-gi e6cd000
Merge branch 'Finland_Census_automation' of https://github.com/smarth…
smarthg-gi e8300a3
updated download script
smarthg-gi f9ad8b4
updated download script
smarthg-gi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 |
|---|---|---|
| @@ -1,40 +1,68 @@ | ||
| # Finland Demographics Dataset | ||
| ## Overview | ||
|
|
||
| This dataset contains demographic information from Finland sourced from Statistics Finland (Tilastokeskus). This dataset provides comprehensive longitudinal coverage of Finland’s national demographics over a 34-year span, featuring annual data from 1990 to 2024. The geographic scope is standardized according to the January 1, 2025 regional division, ensuring consistency across the time series despite historical administrative changes. It offers high-resolution granularity through 43 unique statistical metrics that encompass population growth, age distribution, linguistic diversity, religious affiliation and urban-rural classification. Data is reported in multiple units for versatile analysis, including absolute counts, percentages (%), and population density (persons/km²), allowing for both scale-based and proportional statistical modeling. | ||
| This dataset contains demographic information from Finland sourced from Statistics Finland (Tilastokeskus). This dataset provides comprehensive longitudinal coverage of Finland’s national demographics over a 34-year span, featuring annual data from 1990 to 2025. The geographic scope is standardized according to the January 1, 2025 regional division, ensuring consistency across the time series despite historical administrative changes. It offers high-resolution granularity through 43 unique statistical metrics that encompass population growth, age distribution, linguistic diversity, religious affiliation and urban-rural classification. Data is reported in multiple units for versatile analysis, including absolute counts, percentages (%), and population density (persons/km²), allowing for both scale-based and proportional statistical modeling. | ||
|
|
||
| ## Data Acquisition | ||
| **type of place:** Country | ||
| **years:** 1990 to 2025 | ||
|
|
||
| To download the latest version of this data or refresh the dataset for new years: | ||
| ## Data Source | ||
| **Source URL:** | ||
| https://pxdata.stat.fi/PxWeb/pxweb/en/StatFin/StatFin__vaerak/11ra.px | ||
|
|
||
| 1. Navigate to the source: https://pxdata.stat.fi/PxWeb/pxweb/en/StatFin/StatFin__vaerak/statfin_vaerak_pxt_11ra.px/table/tableViewLayout1/ | ||
| ## License | ||
| **License Type:** | ||
| Creative Commons Attribution 4.0 International | ||
| **License URL:** | ||
| https://creativecommons.org/licenses/by/4.0/ | ||
| **License Description:** | ||
| The [Statistics Finland Terms of Use](https://stat.fi/en/about-us/get-to-know-statistics-finland/legislation/terms-of-use) state the following: | ||
| "Statistics Finland's open data materials and public content of the web service are covered by the Creative Commons Attribution 4.0 International licence. According to the licence, you can copy, edit and share these data either in original or edited format. You can also combine the data with other data and use the data for commercial purposes as well. This licence applies to texts, tables and statistical graphs." | ||
|
|
||
| 2. Selection Criteria: | ||
| - Area: Select WHOLE COUNTRY (or all individual municipalities for more granularity). | ||
| - Information: Select all variables (Population, Language, Religion, Urban/Rural, etc.). | ||
| - Year: Select the full range from 1990 to the most recent year. | ||
| ## Refresh Type | ||
| Automatic Refresh | ||
|
|
||
| 3. Show and Save table Format: Choose "CSV (comma delimited)". | ||
| The refresh is automated using the provided `run.sh` script, which handles both data download and processing. | ||
|
|
||
| ## Processing Instructions | ||
|
|
||
| To process the Finland Census data and generate statistical variables, use the following command from the "data" directory: | ||
|
|
||
| To execute the complete import process (download and processing), run: | ||
| ```bash | ||
| python ./data/tools/statvar_importer/stat_var_processor.py --input_data="./test_data/Finland_Census_input.csv" --pv_map=Finland_Census_pvmap.csv --config_file=Finland_Census_metadata.csv --output_path=Finland_Census_output | ||
|
|
||
| ## Data Refresh & Maintenance | ||
|
|
||
| When Statistics Finland releases new annual updates (typically in the Spring), follow these steps: | ||
|
|
||
| 1. Execute the Data Acquisition steps to get the latest CSV. | ||
| ./run.sh | ||
| ``` | ||
|
|
||
| 2. Check if new demographic categories were added. Update finland_census_pvmap.csv if new labels appear in the source. | ||
| ### Script Details: | ||
| - **Download**: The download is handled by `data_download.py` script which downloads census data from Finland's official database, formats it, and saves it to the designated file path (input_files). | ||
| - **Processing**: Uses `stat_var_processor.py` to map raw data to Data Commons StatVarObservations using the PV map and metadata configuration. | ||
|
|
||
| 3. The source uses . to represent unavailable data (e.g., Economic dependency ratio for the current year). The processor is configured to skip these entries during import. | ||
| For Test Data Run | ||
|
|
||
| 4. Because the source applies the 2025 regional division retrospectively, check for municipal merger updates if downloading municipality-level data. | ||
|
|
||
| 5. Ensure total population counts match the previous year's trend to verify no rows were dropped. | ||
|
|
||
| 6. Execute the data processing step. | ||
| ```bash | ||
| python3 ../../tools/statvar_importer/stat_var_processor.py \ | ||
| "--input_data=./test_data/finland_census_input.csv" \ | ||
| "--pv_map=./finland_census_pvmap.csv" \ | ||
| "--output_path=./test_data/finland_census_output" \ | ||
| "--config_file=./finland_census_metadata.csv" \ | ||
| "--existing_statvar_mcf=gs://unresolved_mcf/scripts/statvar/stat_vars.mcf" | ||
| ``` | ||
|
|
||
| ## Key Files | ||
| - `run.sh`: Main execution script for download and processing. | ||
| - `data_download.py`: Downloads the data from Finland's official database, formats it, and saves it to input_files directory | ||
| - `finland_census_pvmap.csv`: Property-Value mapping for StatVar definitions and dimensions. | ||
| - `finland_census_metadata.csv`: Configuration parameters for the processor. | ||
| - `output_files/finland_census_output.csv`: Processed statistical observations. | ||
| - `output_files/finland_census_output.tmcf`: Template MCF mapping the CSV columns to Data Commons schema. | ||
|
|
||
| ## Validation | ||
| To validate the generated data, use the Data Commons import tool (lint mode): | ||
| ```bash | ||
| java -jar datacommons-import-tool.jar lint output_files/*.csv | ||
| ``` | ||
| The resulting reports (`report.json`, `summary_report.html`) in `dc_generated/` provide detailed insights into data quality and validation status. | ||
|
|
||
| ## Testing | ||
| Testing is performed using the `test_data` directory: | ||
| - Raw Input: `test_data/finland_census_input.csv` | ||
| - Expected Output: `test_data/finland_census_output.csv` | ||
| - Expected TMCF: `test_data/finland_census_output.tmcf` |
This file contains hidden or 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,157 @@ | ||
| #!/usr/bin/env python3 | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| """Downloader for Finland Census data from Statistics Finland PxWeb API using download_util.""" | ||
|
|
||
| import csv | ||
| import io | ||
| import os | ||
| import sys | ||
|
|
||
| _CODEDIR = os.path.dirname(os.path.abspath(__file__)) | ||
| sys.path.insert(1, _CODEDIR) | ||
| sys.path.insert(1, os.path.join(_CODEDIR, '../../util/')) | ||
|
|
||
| from absl import app | ||
| from absl import flags | ||
| from absl import logging | ||
| import download_util | ||
| from file_util import FileIO | ||
|
|
||
| _FLAGS = flags.FLAGS | ||
| flags.DEFINE_string( | ||
| 'output_path', | ||
| None, | ||
| 'Local or GCS path to save the downloaded CSV.', | ||
| required=True, | ||
| ) | ||
|
|
||
| API_URL = 'https://pxdata.stat.fi/PXWeb/api/v1/en/StatFin/vaerak/11ra.px' | ||
|
|
||
|
|
||
| def get_variable_codes() -> tuple[str, str, str]: | ||
| """Fetches table metadata and maps structural concepts to API codes.""" | ||
| logging.info('Fetching table metadata from %s...', API_URL) | ||
|
|
||
| metadata = download_util.request_url( | ||
| url=API_URL, | ||
| output='json', | ||
| retries=3, | ||
| retry_secs=5, | ||
| ) | ||
| if not metadata or not isinstance(metadata, dict): | ||
| raise RuntimeError('Failed to fetch valid JSON metadata from PxWeb API.') | ||
|
|
||
| area_code = None | ||
| info_code = None | ||
| year_code = None | ||
|
|
||
| # Cleaner matching using case-insensitive checks | ||
| for var in metadata.get('variables', []): | ||
| text = var.get('text', '').lower() | ||
| code = var.get('code') | ||
|
|
||
| if 'area' in text or 'alue' in text: | ||
| area_code = code | ||
| elif 'information' in text or 'tiedot' in text: | ||
| info_code = code | ||
| elif 'year' in text or 'vuosi' in text: | ||
| year_code = code | ||
| return area_code, info_code, year_code | ||
|
|
||
|
|
||
| def format_csv_content(raw_csv_content: str) -> str: | ||
| """Safely prepends a title block to the CSV payload using standard CSV writing.""" | ||
| if not raw_csv_content or not raw_csv_content.strip(): | ||
| return raw_csv_content | ||
|
|
||
| # Read incoming CSV properly to avoid newline/comma split issues | ||
| csv_file = io.StringIO(raw_csv_content.strip()) | ||
| reader = csv.reader(csv_file) | ||
| header = next(reader) | ||
| rows = list(reader) | ||
|
|
||
| num_columns = len(header) | ||
| title = "Key figures on population by Area, Information and Year" | ||
| # Title and blank lines are added to match the pvmap layout | ||
| # Construct the padded rows cleanly without manual string multiplication | ||
| title_row = [title] + [''] * (num_columns - 1) | ||
| blank_row = [''] * num_columns | ||
|
|
||
| output = io.StringIO() | ||
| writer = csv.writer(output, lineterminator='\n') | ||
|
|
||
| writer.writerow(title_row) | ||
| writer.writerow(blank_row) | ||
| writer.writerow(header) | ||
| writer.writerows(rows) | ||
|
|
||
| return output.getvalue() | ||
|
|
||
|
|
||
| def download_data(output_path: str) -> None: | ||
| """Downloads, formats, and saves the Finland Census CSV data.""" | ||
| area_code, info_code, year_code = get_variable_codes() | ||
| logging.info( | ||
| 'Mapped variable codes -> Area: %s, Info: %s, Year: %s', | ||
| area_code, info_code, year_code, | ||
| ) | ||
|
|
||
| query = { | ||
| 'query': [ | ||
| { | ||
| 'code': area_code, | ||
| 'selection': {'filter': 'item', 'values': ['SSS']}, # 'SSS' selects the 'WHOLE COUNTRY' | ||
| }, | ||
| { | ||
| 'code': info_code, | ||
| 'selection': {'filter': 'all', 'values': ['*']}, # '*' selects all metrics | ||
| }, | ||
| { | ||
| 'code': year_code, | ||
| 'selection': {'filter': 'all', 'values': ['*']}, # '*' selects all years | ||
| }, | ||
| ], | ||
| 'response': {'format': 'csv'}, | ||
| } | ||
|
|
||
| logging.info('Sending POST query to retrieve CSV data...') | ||
| content_bytes = download_util.request_url( | ||
| url=API_URL, | ||
| params=query, | ||
| method='POST', | ||
| output='bytes', | ||
| retries=3, | ||
| retry_secs=5, | ||
| ) | ||
|
|
||
| if not content_bytes: | ||
| raise RuntimeError('Failed to download CSV data: empty response.') | ||
|
|
||
| content = content_bytes.decode('utf-8-sig') | ||
| formatted_content = format_csv_content(content) | ||
|
|
||
| # Trust the imported FileIO dependency entirely; drop the redundant fallback | ||
| with FileIO(output_path, 'w') as f: | ||
| f.write(formatted_content) | ||
|
|
||
| logging.info('Successfully downloaded data and saved to %s', output_path) | ||
|
|
||
|
|
||
| def main(_) -> None: | ||
| download_data(_FLAGS.output_path) | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| app.run(main) | ||
5 changes: 5 additions & 0 deletions
5
statvar_imports/finland_census/golden_data/golden_summary_report.csv
This file contains hidden or 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,5 @@ | ||
| "MinDate","MeasurementMethods","observationPeriods","StatVar","NumPlaces","ScalingFactors","Units" | ||
| "1990","[]","[]","IncrementalCount_Person","1","[]","[]" | ||
| "1990","[]","[]","Count_Person","1","[]","[]" | ||
| "1990","[]","[]","GrowthRate_Count_Person","1","[]","[Percent]" | ||
| "1990","[]","[]","Count_Person_PerArea","1","[]","[PersonPerSquareKilometer]" |
This file contains hidden or 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 hidden or 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,22 @@ | ||
| #!/bin/bash | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| set -e | ||
| mkdir -p input_files | ||
| mkdir -p output_files | ||
|
|
||
| python data_download.py --output_path=./input_files/finland_census_input.csv | ||
|
|
||
| python ../../tools/statvar_importer/stat_var_processor.py --input_data="input_files/*.csv" --pv_map="finland_census_pvmap.csv" --config_file="finland_census_metadata.csv" --output_path="output_files/finland_census_output" --existing_statvar_mcf="gs://unresolved_mcf/scripts/statvar/stat_vars.mcf" |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.