Files
solon/scripts/fetch-commune-figures.mjs
CatoandClaude e375e45517 places: jobs, building and party strengths for every commune (#628)
The explorer offers jobs per 100 residents, dwellings built a year per 1,000
residents and the six largest parties' strength at the 2023 National Council
election, from the Federal Statistical Office's tables; each commune's page
shows them with its rank. Also fixes the importer overflowing the stack when
a file whose figures are already held (every commune's vote results) is
loaded again.


Claude-Session: https://claude.ai/code/session_019MDtmvTCDbJAYNKQpNyKzz

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-28 02:27:43 +01:00

194 lines
7.7 KiB
JavaScript

#!/usr/bin/env node
/**
* Writes three files of figures the Federal Statistical Office publishes for every Swiss
* commune, read from its PxWeb tables:
* data/places/switzerland/communes-elections.csv party strengths, National Council elections
* data/places/switzerland/communes-jobs.csv jobs per resident (STATENT over STATPOP)
* data/places/switzerland/communes-housing.csv dwellings built per 1,000 residents
* Only communes Solon holds (communes-population.csv) are written: a table that still lists a
* commune since merged into another has no row for the merged one, and the script says how many.
*
* node scripts/fetch-commune-figures.mjs
*/
import { readFileSync, writeFileSync } from "node:fs";
const API = "https://www.pxweb.bfs.admin.ch/api/v1/de";
const DIR = "data/places/switzerland";
async function meta(table) {
const res = await fetch(`${API}/${table}/${table}.px`);
if (!res.ok) throw new Error(`${table}: ${res.status}`);
return (await res.json()).variables;
}
/** The cells of `table` for the chosen values: one entry per cell, its keys in the table's order. */
async function cells(table, selection) {
const query = Object.entries(selection).map(([code, values]) => ({
code,
selection: values === "*" ? { filter: "all", values: ["*"] } : { filter: "item", values },
}));
const res = await fetch(`${API}/${table}/${table}.px`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ query, response: { format: "json" } }),
});
if (!res.ok) throw new Error(`${table}: ${res.status} ${await res.text()}`);
const body = await res.json();
const columns = body.columns.filter((c) => c.type !== "c").map((c) => c.code);
return body.data.map((d) => ({
...Object.fromEntries(columns.map((c, i) => [c, d.key[i]])),
// A cell the office withholds or has no figure for holds a mark, not a number.
value: /^-?\d+(\.\d+)?$/.test(d.values[0]) ? Number(d.values[0]) : null,
}));
}
/** A table's own code for each value of a variable, by the text it shows. */
const codesOf = (variables, code) => {
const v = variables.find((x) => x.code === code);
return v.values.map((value, i) => ({ value, text: v.valueTexts[i] }));
};
const last = (list) => list.at(-1);
const held = new Set(
readFileSync(`${DIR}/communes-population.csv`, "utf8")
.split("\n")
.slice(1)
.map((l) => l.split(",")[0])
.filter(Boolean),
);
const report = (name, rows) => {
const communes = new Set(rows.map((r) => r[0]));
console.log(`${name}: ${rows.length} rows, ${communes.size} of ${held.size} communes`);
};
const write = (file, header, rows) =>
writeFileSync(`${DIR}/${file}`, [header, ...rows.map((r) => r.join(","))].join("\n") + "\n");
// ---- Party strengths at the National Council elections ------------------------------------
{
const table = "px-x-1702020000_105";
const PLACE = "Bezirk (>>) / Gemeinde (......)";
// The six parties with a group of their own in the National Council elected in 2023.
const PARTIES = { 4: "svp", 3: "sp", 34: "mitte", 1: "fdp", 13: "gruene", 31: "glp" };
const YEARS = ["2015", "2019", "2023"];
const data = await cells(table, {
[PLACE]: "*",
Jahr: YEARS,
Partei: Object.keys(PARTIES),
Ergebnisse: ["2"],
});
const rows = [];
for (const d of data) {
const commune = String(Number(d[PLACE]));
// Districts carry six digits; a commune that put up no list of a party has no figure.
if (d[PLACE].length !== 4 || !held.has(commune) || d.value === null) continue;
rows.push([commune, d.Jahr, PARTIES[d.Partei], d.value.toFixed(2)]);
}
rows.sort((a, b) => a[1] - b[1] || a[0] - b[0] || a[2].localeCompare(b[2]));
write("communes-elections.csv", "commune,year,party,strength_percent", rows);
report("elections", rows);
}
// ---- Residents on 31 December, the denominator of the two rates below ---------------------
const residents = new Map();
{
const table = "px-x-0102020000_201";
const variables = await meta(table);
const PLACE = "Kanton (-) / Bezirk (>>) / Gemeinde (......)";
const COMPONENT = "Demografische Komponente";
const endOfYear = codesOf(variables, COMPONENT).find((c) => c.text === "Bestand am 31. Dezember");
const years = codesOf(variables, "Jahr").filter((y) => Number(y.text) >= 2019);
const data = await cells(table, {
Jahr: years.map((y) => y.value),
[PLACE]: "*",
"Staatsangehörigkeit (Kategorie)": [
codesOf(variables, "Staatsangehörigkeit (Kategorie)")[0].value,
],
Geschlecht: [codesOf(variables, "Geschlecht")[0].value],
[COMPONENT]: [endOfYear.value],
});
const text = new Map(codesOf(variables, PLACE).map((c) => [c.value, c.text]));
const yearOf = new Map(years.map((y) => [y.value, y.text]));
for (const d of data) {
const m = /^\.{6}(\d{4}) /.exec(text.get(d[PLACE]) ?? "");
if (m && d.value) residents.set(`${Number(m[1])}:${yearOf.get(d.Jahr)}`, d.value);
}
}
// ---- Jobs (STATENT) -------------------------------------------------------------------------
{
const table = "px-x-0602010000_102";
const variables = await meta(table);
const years = codesOf(variables, "Jahr").filter((y) => Number(y.text) >= 2019);
const data = await cells(table, {
Jahr: years.map((y) => y.value),
Gemeinde: "*",
Wirtschaftssektor: ["999"],
Beobachtungseinheit: ["2", "5"],
});
const byKey = new Map();
for (const d of data) {
if (d.value === null || !held.has(d.Gemeinde)) continue;
const key = `${d.Gemeinde}:${d.Jahr}`;
byKey.set(key, { ...byKey.get(key), [d.Beobachtungseinheit]: d.value });
}
const rows = [];
for (const [key, v] of byKey) {
const [commune, year] = key.split(":");
const people = residents.get(key);
if (!people || v[2] === undefined || v[5] === undefined) continue;
rows.push([
commune,
year,
v[2],
((v[2] / people) * 100).toFixed(2),
((v[5] / people) * 100).toFixed(2),
]);
}
rows.sort((a, b) => a[1] - b[1] || a[0] - b[0]);
write(
"communes-jobs.csv",
"commune,year,jobs,jobs_per_100_residents,fte_per_100_residents",
rows,
);
report("jobs", rows);
}
// ---- Dwellings built ------------------------------------------------------------------------
{
const table = "px-x-0904030000_105";
const variables = await meta(table);
const PLACE = "Grossregion (<<) / Kanton (-) / Gemeinde (......)";
// One year's building in a village is a handful of dwellings or none, so the rate is the
// yearly average over five years: the first year written needs the four before it.
const SPAN = 5;
const years = codesOf(variables, "Jahr").filter((y) => Number(y.text) >= 2019 - (SPAN - 1));
const data = await cells(table, {
[PLACE]: "*",
"Anzahl Zimmer": ["0"],
Jahr: years.map((y) => y.value),
});
const text = new Map(codesOf(variables, PLACE).map((c) => [c.value, c.text]));
const yearOf = new Map(years.map((y) => [y.value, y.text]));
const built = new Map();
for (const d of data) {
const m = /^\.{6}(\d{4}) /.exec(text.get(d[PLACE]) ?? "");
if (m && d.value !== null) built.set(`${Number(m[1])}:${yearOf.get(d.Jahr)}`, d.value);
}
const rows = [];
for (const [key, value] of built) {
const [commune, year] = key.split(":");
const people = residents.get(key);
const span = Array.from({ length: SPAN }, (_, i) => built.get(`${commune}:${year - i}`));
if (!held.has(commune) || !people || year < 2019 || span.includes(undefined)) continue;
const average = span.reduce((sum, v) => sum + v, 0) / SPAN;
rows.push([commune, year, value, ((average / people) * 1000).toFixed(2)]);
}
rows.sort((a, b) => a[1] - b[1] || a[0] - b[0]);
write(
"communes-housing.csv",
"commune,year,dwellings_built,dwellings_built_per_1000_residents_5y",
rows,
);
report("housing", rows);
}