SDMX to B-UML¶
Build a B-UML structural model from the structure of an SDMX dataflow.
SDMX is the ISO standard (ISO 17369) official statistics are published with: Eurostat, the ECB,
the OECD, the IMF, national statistical institutes. Every dataflow describes its data with a data
structure definition (dimensions, codelists, attributes, measure); this package reads it from the
provider’s SDMX 2.1 REST API, or from an SDMX-ML file, and turns it into a validated
DomainModel.
from besser.utilities.sdmx_to_buml import sdmx_to_buml
model = sdmx_to_buml("eurostat", "une_rt_m") # a preset provider
model = sdmx_to_buml("ecb", "ECB,EXR,1.0") # agency, id, version
model = sdmx_to_buml("https://example.org/sdmx/rest", "DF_POP") # any SDMX 2.1 API
See builder for the mapping rules, roles for the dimension roles the model’s
metadata records and client for the limits every import runs under.
-
besser.utilities.sdmx_to_buml.sdmx_to_buml(provider: SDMXProvider | str, dataflow: DataflowRef | str, model_name: str | None =
None, enum_max: int =50, prefix_hierarchy: Iterable[str] | None =None, class_names: dict[str, str] | None =None, lang: str ='en', timeout: float =120.0, max_bytes: int =33554432, safe: bool =False) DomainModel[source]¶ Read a dataflow’s structure from an SDMX 2.1 REST API and build its B-UML domain model.
- Parameters:¶
provider – a key of
PROVIDERS("eurostat","ecb","oecd"…) or the base URL of any SDMX 2.1 REST API.dataflow –
ID,AGENCY,ID,AGENCY,ID,VERSIONorAGENCY:ID(VERSION).model_name – name of the domain model; defaults to the dataflow id.
enum_max – flat codelists with at most this many codes become enumerations, larger ones classes.
prefix_hierarchy – dimension ids whose codes nest by prefix;
Noneauto-detects them.class_names – names for the generated classes, keyed by dimension or codelist id.
lang – language of the names read from the structure.
timeout – seconds allowed for the whole import.
max_bytes – largest structure message accepted (default 32 MB).
safe – only https, public hosts, pinned connections (for servers fetching for others).
- Returns:¶
the validated structural model.
- Return type:¶
- Raises:¶
SDMXFetchError – the provider failed, the dataflow does not exist, or the import ran out of time (
SDMXTimeoutError) or size (SDMXTooLargeError).ValueError – an invalid provider or dataflow reference, or an unusable structure message.
-
besser.utilities.sdmx_to_buml.sdmx_xml_to_buml(xml: bytes | str, dataflow_id: str | None =
None, model_name: str | None =None, enum_max: int =50, prefix_hierarchy: Iterable[str] | None =None, class_names: dict[str, str] | None =None, lang: str ='en') DomainModel[source]¶ Build the B-UML domain model of an SDMX-ML 2.1 structure message (a downloaded file).
The message must hold the data structure definition and its codelists, as an SDMX API returns for
dataflow/{agency}/{id}/latest?references=descendants. The other arguments are those ofsdmx_to_buml().- Raises:¶
ValueError – the message is not SDMX-ML, holds no data structure, or holds dataflows but not
dataflow_id.
SDMX data structure definition -> B-UML domain model.
Mapping rules:
The dataflow becomes an
Observationclass holding the time period, the observed value and the SDMX attributes (e.g.OBS_FLAG), all optional except the time period.A coded dimension with a small, flat codelist becomes an
Enumeration, typed attribute ofObservation.A coded dimension with a large or hierarchical codelist becomes a class (
codeas identifier,label) linked toObservationby a 1 to 0..* association. Dimensions that share a codelist (reporter and partner -> one country list) share the class.A hierarchical codelist (SDMX parent references, a hierarchical codelist, or code prefixes) adds a
parent/childrenself-association and alevelattribute.A dimension whose codelist is not in the message, or that is not coded, becomes a string.
Each class carries Metadata: the dimension’s role, total and default code (see roles)
and an sdmx: URI of its codelist or dataflow, so the model documents how to read the data.
- besser.utilities.sdmx_to_buml.builder.pascal(text: str) str[source]¶
REF_AREA->RefArea: a class or enumeration name.
- besser.utilities.sdmx_to_buml.builder.snake(text: str) str[source]¶
TIME_PERIOD->time_period: an attribute name (never a Python keyword).
- besser.utilities.sdmx_to_buml.builder.literal_name(code: str, label: str, taken: set[str]) str[source]¶
A valid, unique enumeration literal for an SDMX code: the code itself, else its label.
- class besser.utilities.sdmx_to_buml.builder.DimensionMapping(id: str, kind: str, attr: str, type_name: str | None = None, literals: dict[str, str] = <factory>, hierarchy: str | None = None, role: str = 'breakdown', label: str = '', total_code: str | None = None, default_code: str | None = None)[source]¶
Bases:
objectHow one SDMX dimension maps onto the model.
-
class besser.utilities.sdmx_to_buml.builder.ImportMapping(dataflow: str, agency: str, observation_class: str, time_attr: str | None, value_attr: str, dimensions: list[DimensionMapping], attributes: dict[str, str], title: str =
'')[source]¶ Bases:
objectHow the dataflow maps onto the model: what a data loader needs to fill the generated database.
-
besser.utilities.sdmx_to_buml.builder.structure_to_buml(dsd: DataStructure, model_name: str | None =
None, enum_max: int =50, prefix_hierarchy: Iterable[str] | None =None, observation_class: str ='Observation', class_names: dict[str, str] | None =None) tuple[DomainModel, ImportMapping][source]¶ Build a validated B-UML domain model from a parsed SDMX data structure.
- Parameters:¶
dsd – parsed structure (see
besser.utilities.sdmx_to_buml.parse_structure()).model_name – name of the domain model; defaults to the dataflow id.
enum_max – flat codelists with at most this many codes become enumerations.
prefix_hierarchy – dimension ids whose codes nest by prefix;
Noneauto-detects numeric nomenclatures.observation_class – name of the fact class.
class_names – optional names for the generated classes, keyed by dimension id or codelist id (e.g.
{"CL_AREA": "Country"}).
- Returns:¶
The domain model and the import mapping (how codes and columns map onto it).
- Raises:¶
ValueError – the model fails validation (its warnings are logged).
A small SDMX 2.1 REST client for structure messages (SDMX-ML), built on requests.
It reads what a B-UML model needs: a dataflow with its data structure, concepts and codelists, completed when the provider allows with the content constraint and hierarchical codelists.
Every SDMXClient.fetch_structure() runs under one budget: a total deadline, a size cap per
message and for the whole import, and a number of requests.
safe=True is the mode for servers that fetch on behalf of someone else (the web editor):
only
httpson port 443, with no credentials, backslash, whitespace or control character in the URL, read with the same parserrequestsconnects with;only hosts that resolve to public addresses, checked again on every redirect;
the connection goes to the address that was checked (the host name is kept for SNI and the certificate check), so a DNS answer that changes between the check and the request (DNS rebinding) cannot reach another address;
environment proxies are not used (they would connect on their own); the CA bundle of
REQUESTS_CA_BUNDLEorCURL_CA_BUNDLEis, for servers behind a TLS-inspecting gateway.
-
exception besser.utilities.sdmx_to_buml.client.SDMXFetchError(message: str, status: int | None =
None)[source]¶ Bases:
RuntimeErrorThe provider could not be reached, refused the query, or answered with something unusable.
statusis the HTTP status when there was one (404: the dataflow does not exist).
-
exception besser.utilities.sdmx_to_buml.client.SDMXTooLargeError(message: str, status: int | None =
None)[source]¶ Bases:
SDMXFetchErrorOne answer is larger than the client’s
max_bytes.
-
exception besser.utilities.sdmx_to_buml.client.SDMXImportLimitError(message: str, status: int | None =
None)[source]¶ Bases:
SDMXTooLargeErrorThe import as a whole needs more bytes (
max_total_bytes) or requests than its budget.
-
exception besser.utilities.sdmx_to_buml.client.SDMXTimeoutError(message: str, status: int | None =
None)[source]¶ Bases:
SDMXFetchErrorThe import took longer than the client’s
timeout.
-
class besser.utilities.sdmx_to_buml.client.SDMXProvider(key: str, name: str, base_url: str, agency: str =
'all', references: tuple[str, ...] =('descendants', 'all'))[source]¶ Bases:
objectAn SDMX 2.1 REST endpoint.
referencesis the order in which the client asks for the dataflow’s descendants: some providers rejectall(Eurostat), others only return the data structure with it (.Stat Suite).
-
class besser.utilities.sdmx_to_buml.client.DataflowRef(id: str, agency: str | None =
None, version: str ='latest')[source]¶ Bases:
objectA dataflow reference: agency (
None: the provider’s default), id and version.
-
besser.utilities.sdmx_to_buml.client.parse_dataflow(text: str, agency: str | None =
None, version: str | None =None) DataflowRef[source]¶ Read
ID,AGENCY,ID,AGENCY,ID,VERSIONorAGENCY:ID(VERSION).- Raises:¶
ValueError – when a part is not a valid SDMX id or version.
- besser.utilities.sdmx_to_buml.client.resolve_provider(source: SDMXProvider | str) SDMXProvider[source]¶
A provider from its key (see
PROVIDERS) or from the base URL of an SDMX 2.1 REST API.
- besser.utilities.sdmx_to_buml.client.check_public_url(url: str) str[source]¶
Refuse anything but
httpson port 443 to a host that resolves only to public addresses.The URL is read with
urllib3’s parser, the onerequestsconnects with, and must give the same host with the standard library’s: two parsers that disagree are how a check is fooled.- Returns:¶
connect to it (not to the name) so the check holds.
- Return type:¶
The public address the host resolves to
- Raises:¶
ValueError – for any other URL (private, loopback, link-local, credentials in the URL…).
-
class besser.utilities.sdmx_to_buml.client.SDMXClient(provider: SDMXProvider | str, timeout: float =
120.0, max_bytes: int =33554432, safe: bool =False, retries: int =2, max_total_bytes: int =67108864, max_requests: int =50)[source]¶ Bases:
objectReads SDMX-ML structure messages from one provider.
- Parameters:¶
provider – a
SDMXProvider, a key ofPROVIDERSor an SDMX 2.1 base URL.timeout – seconds for one whole
fetch_structure()(or oneget()), retries included.max_bytes – largest single answer accepted.
safe – refuse non-public hosts and non-https URLs, and pin each connection (see the module doc).
retries – attempts on connection errors, 429 and 5xx answers.
max_total_bytes – bytes read by one import, all answers together.
max_requests – requests made by one import.
- url(*path: str) str[source]¶
The URL of a resource below the provider’s base URL.
- Raises:¶
ValueError – a part is not an SDMX id or version (
..,/or?could leave the API).
-
get(*path: str, params: dict | None =
None, max_bytes: int | None =None) bytes[source]¶ GET a structure resource and return its body.
Outside
fetch_structure(), the call has a budget of its own.- Raises:¶
SDMXFetchError – network failure or an HTTP error (
statusset).SDMXTooLargeError – the body is larger than
max_bytes.SDMXImportLimitError – the import’s byte or request budget is spent.
SDMXTimeoutError – the import’s deadline has passed.
-
fetch_structure(flow: DataflowRef | str, lang: str =
'en', with_constraint: bool =True, with_hierarchies: bool =True) DataStructure[source]¶ The dataflow’s structure, parsed, with its codelists, constraint and hierarchies when available.
The whole call runs under one budget (
timeout,max_total_bytes,max_requests).- Raises:¶
SDMXFetchError – the dataflow does not exist (
status404) or the provider failed.SDMXTimeoutError, SDMXImportLimitError – the import ran out of time, bytes or requests.
ValueError – the provider’s answer holds no data structure definition, or not this dataflow.
Detect what each SDMX dimension is, so that the model documents how to read its data.
Every dimension gets exactly one role:
frequencythe FREQ dimension (annual, monthly, …). One value at a time.unitanything that must never be summed across its codes: units of measure,indicators and measures, adjustments, and dimensions with a single code in the data (constants such as
_Z). One value at a time.
geocountries and areas: the codes are mostly ISO 3166 alpha-2 codes, or theconcept is an area, country, partner or reporter.
hierarchya nomenclature with levels: SDMX parent references, a .Stat SuiteHIER_CONTEXThierarchical codelist, or numeric codes nesting by prefix (e.g. HS2 > HS4 > HS6 > CN8, NACE digits).
breakdownevery other categorical dimension (sex, age, sector…).
Each dimension also gets a total_code (the code holding the sum of the others: _T,
TOTAL, WORLD… or a label such as “Total”) and a default_code: the code a query
should use when the dimension is not being analysed, so that values are never double counted.
- class besser.utilities.sdmx_to_buml.roles.DimensionRole(id: str, role: str, label: str, total_code: str | None = None, default_code: str | None = None, hierarchy: str | None = None, used_codes: list[str] = <factory>, reason: str = '')[source]¶
The role of one dimension, with its total and default code.
- besser.utilities.sdmx_to_buml.roles.infer_prefix_parents(codes: Iterable[str]) dict[str, str | None][source]¶
Parent of each code: the longest other code that is a strict prefix of it.
Works for nested numeric nomenclatures (
84>8471>847130>84713000). Numeric codes without a prefix parent are attached toTOTALwhen that code exists.
- besser.utilities.sdmx_to_buml.roles.looks_prefix_hierarchical(codes: Iterable[str]) bool[source]¶
True for numeric codes where most have a strictly shorter code as prefix (a nomenclature).
-
besser.utilities.sdmx_to_buml.roles.find_total(codelist: Codelist | None, used: list[str], parents: dict | None =
None) str | None[source]¶ The code holding the total of a dimension, by SDMX conventions, labels, or the hierarchy root.
-
besser.utilities.sdmx_to_buml.roles.detect_roles(dsd: DataStructure, prefix_hierarchy: Iterable[str] | None =
None) dict[str, DimensionRole][source]¶ Assign a role, a total and a default code to every dimension of
dsd(deterministic).- Parameters:¶
dsd – the parsed data structure.
prefix_hierarchy – dimension ids whose codes nest by prefix;
Nonedetects them.
Parse an SDMX-ML 2.1 structure message into plain Python objects.
Only the parts needed to build a B-UML model are read: the dataflow, its data structure definition (dimensions, time dimension, attributes, primary measure), concepts (for human-readable names), codelists (codes, names, parents), content constraints (the codes actually used) and hierarchical codelists. Tags are matched by local name so the parser does not depend on the namespace prefixes a given SDMX provider uses.
-
class besser.utilities.sdmx_to_buml.structure.Code(id: str, name: str, parent: str | None =
None)[source]¶ A code of a codelist, with its name and (optional) parent code.
- class besser.utilities.sdmx_to_buml.structure.Codelist(id: str, agency: str, version: str, name: str, codes: dict[str, ~besser.utilities.sdmx_to_buml.structure.Code] = <factory>)[source]¶
An SDMX codelist.
-
class besser.utilities.sdmx_to_buml.structure.StructureRef(agency: str, id: str, version: str =
'latest')[source]¶ A reference to a maintainable artefact (agency, id, version).
-
class besser.utilities.sdmx_to_buml.structure.Component(id: str, kind: str, position: int =
0, concept: str | None =None, codelist_ref: str | None =None, name: str | None =None, codelist_source: StructureRef | None =None)[source]¶ A dimension, the time dimension, an attribute or the primary measure.
- class besser.utilities.sdmx_to_buml.structure.DataStructure(id: str, agency: str, version: str, name: str, dataflow_id: str, dataflow_name: str, dimensions: list[~besser.utilities.sdmx_to_buml.structure.Component], time_dimension: ~besser.utilities.sdmx_to_buml.structure.Component | None, attributes: list[~besser.utilities.sdmx_to_buml.structure.Component], measure: ~besser.utilities.sdmx_to_buml.structure.Component | None, codelists: dict[str, ~besser.utilities.sdmx_to_buml.structure.Codelist], constraints: dict[str, list[str]] = <factory>, annotations: list[tuple[str, str, str]] = <factory>, hierarchies: dict[str, dict[str, str | None]] = <factory>)[source]¶
A dataflow and its data structure definition (DSD).
- codelist_for(comp: Component) Codelist | None[source]¶
The codelist of a component, or None when it is not coded (or not in the message).
- used_codes(comp: Component) list[str][source]¶
Codes of a dimension that occur in the data (constraint), else every code of its codelist.
-
besser.utilities.sdmx_to_buml.structure.parse_codelists(xml: bytes | str, lang: str =
'en') dict[str, Codelist][source]¶ The codelists defined in a structure message, by id.
-
besser.utilities.sdmx_to_buml.structure.parse_constraint(xml: bytes | str, dataflow_id: str | None =
None) dict[str, list[str]][source]¶ Codes per dimension from a standalone content-constraint message.
-
besser.utilities.sdmx_to_buml.structure.parse_hierarchy(xml: bytes | str, hierarchy_id: str | None =
None) dict[str, str | None][source]¶ Parent of each code in an SDMX 2.1 HierarchicalCodelist (one hierarchy).
-
besser.utilities.sdmx_to_buml.structure.dataflow_structure_ref(xml: bytes | str, dataflow_id: str | None =
None, lang: str ='en') tuple[StructureRef, str, str] | None[source]¶ For a message that holds the dataflow only: (its data structure reference, flow id, flow name).
- Raises:¶
ValueError –
dataflow_idis given and the message holds other dataflows only.
-
besser.utilities.sdmx_to_buml.structure.parse_structure(xml: bytes | str, dataflow_id: str | None =
None, lang: str ='en') DataStructure[source]¶ Parse an SDMX-ML 2.1 structure message.
xmlshould contain the data structure definition and, ideally, its codelists and concepts (request it withreferences=childrenorreferences=descendants).- Raises:¶
ValueError – when the message is not XML, holds no data structure definition, or holds dataflows but not
dataflow_id.