Skip to content

Classification System

Two interfaces. ClassificationSystem is a flat set of codes and is what the retrieval-based classifiers are written against; HierarchicalClassificationSystem adds the parent/child accessors and is what the hierarchy traversal agent and taxonomy refinement require. See Classification Systems for how to implement one for your own taxonomy.

Code

rac4os._shared.Code.Code dataclass

The code class works a the base datatype for storing, retrieving and working with codes from the classification systems. More or less every hierarchical classification system in official statistics, like SEA or COICOP haven a extensive documentation available, what always contains * code - Code in Form of digitis, e.g. 01111 * description - overall description of the content of the code, e.g. Cereals (ND) * level - the level of the code inside the systems hierarchy, e.g. the corresponding level for the code 01111 is 4. * detailled_description - A more detailled description of what should be classified inside of a certain category, can be found in e.g. the COICOP documentation under introductory_notes * details - here will be all other details stored, that come on top of all the previous informations, e.g. explicit exclusion, inclusion, etc.

Source code in rac4os/_shared/Code.py
@dataclass
class Code:
    """
    The code class works a the base datatype for storing, retrieving and working with 
    codes from the classification systems. More or less every hierarchical classification
    system in official statistics, like SEA or COICOP haven a extensive documentation available, 
    what always contains 
    * `code` - Code in Form of digitis, e.g. 01111
    * `description` - overall description of the content of the code, e.g. Cereals (ND)
    * `level` - the level of the code inside the systems hierarchy, e.g. the corresponding level for the code 01111 is 4.
    * `detailled_description` - A more detailled description of what should be classified inside of a certain category, can be found in e.g. the COICOP documentation under introductory_notes
    * `details` - here will be all other details stored, that come on top of all the previous informations, e.g. explicit exclusion, inclusion, etc. 
    """
    code: str = field(default_factory=str)
    description: str = field(default_factory=str)
    level: int = field(default_factory=int)
    detailled_description: str = field(default_factory=str)
    details: dict = field(default_factory=dict)

    @classmethod
    def from_dict(cls, data: dict):
        """
        Loads in a code form a dictionary and saves it as a Code object. 
        All keys that don't exist in the dict but that exist in the Code
        object will be left blank. It is imprtant that the codes inserted 
        here match the required datarypes defined, otherwise it will break here
        or deeper down the pipeline.
        """
        valid_fields: set[str] = {f.name for f in fields(cls)}
        cleaned_data: dict = {k: v for k, v in data.items() if k in valid_fields}
        return cls(**cleaned_data)

    def to_json(self, indent: int=4) -> str:
        """Converts the dataclass instance to a JSON string."""
        return json.dumps(asdict(self), indent=indent, ensure_ascii=False)

    def to_dict(self) -> dict:
        """Converts the dataclass instance to a JSON string."""
        return asdict(self)

from_dict classmethod

from_dict(data)

Loads in a code form a dictionary and saves it as a Code object. All keys that don't exist in the dict but that exist in the Code object will be left blank. It is imprtant that the codes inserted here match the required datarypes defined, otherwise it will break here or deeper down the pipeline.

Source code in rac4os/_shared/Code.py
@classmethod
def from_dict(cls, data: dict):
    """
    Loads in a code form a dictionary and saves it as a Code object. 
    All keys that don't exist in the dict but that exist in the Code
    object will be left blank. It is imprtant that the codes inserted 
    here match the required datarypes defined, otherwise it will break here
    or deeper down the pipeline.
    """
    valid_fields: set[str] = {f.name for f in fields(cls)}
    cleaned_data: dict = {k: v for k, v in data.items() if k in valid_fields}
    return cls(**cleaned_data)

to_json

to_json(indent=4)

Converts the dataclass instance to a JSON string.

Source code in rac4os/_shared/Code.py
def to_json(self, indent: int=4) -> str:
    """Converts the dataclass instance to a JSON string."""
    return json.dumps(asdict(self), indent=indent, ensure_ascii=False)

to_dict

to_dict()

Converts the dataclass instance to a JSON string.

Source code in rac4os/_shared/Code.py
def to_dict(self) -> dict:
    """Converts the dataclass instance to a JSON string."""
    return asdict(self)

ClassificationSystem

rac4os.classification_system.BaseClassificationSystem.ClassificationSystem

Bases: ABC

A flat classification: a set of codes with no structure between them.

This is the smaller of the two interfaces and the one the retrieval-based classifiers are typed against, because they never navigate a taxonomy. They look a code up and ask whether a generated code is one of yours, which is all a flat system has to answer. If your categories genuinely have no hierarchy — a flat code list, a set of labels — this is the whole interface you need, and you can use it directly rather than subclassing it.

If your codes do nest, use HierarchicalClassificationSystem instead. It adds the parent/child accessors on top of everything here, and the hierarchy traversal agent and the taxonomy refinement module both require them.

Parameters:

Name Type Description Default
loader ClassificationLoader

loader that yields the Code records this system is built from.

required

Attributes:

Name Type Description
loader ClassificationLoader

the loader that was passed in.

codes list[Code]

every record the loader returned, in source order.

Source code in rac4os/classification_system/BaseClassificationSystem.py
class ClassificationSystem(ABC):
    """
    A flat classification: a set of codes with no structure between them.

    This is the smaller of the two interfaces and the one the retrieval-based
    classifiers are typed against, because they never navigate a taxonomy. They look
    a code up and ask whether a generated code is one of yours, which is all a flat
    system has to answer. If your categories genuinely have no hierarchy — a flat code
    list, a set of labels — this is the whole interface you need, and you can use it
    directly rather than subclassing it.

    If your codes do nest, use `HierarchicalClassificationSystem` instead. It adds the
    parent/child accessors on top of everything here, and the hierarchy traversal
    agent and the taxonomy refinement module both require them.

    Parameters:
        loader (ClassificationLoader): loader that yields the `Code` records this system is built from.

    Attributes:
        loader (ClassificationLoader): the loader that was passed in.
        codes (list[Code]): every record the loader returned, in source order.
    """

    def __init__(self, loader: ClassificationLoader) -> None:
        """
        Loads the taxonomy through the loader and builds the code lookup.

        This happens eagerly, so constructing a classification system reads and parses
        the source file.
        """
        self.loader = loader
        self.codes: list[Code] = self.loader.load()
        self._lookup: dict[str, Code] = {c.code: c for c in self.codes}

    def add_code(self, code: dict) -> None:
        """
        Add a single code to the live system without rebuilding it.

        Useful for patching in a category the source documentation omits. Only the lookup
        is touched; `self.codes` stays as the loader returned it, so the addition does not
        survive into a system built freshly from the same source.

        A flat system has nowhere to file the new code, so it takes no parent. The
        hierarchical subclass overrides this and accepts one.

        Parameters:
            code (dict): a `Code`-shaped dict; keys that `Code` does not define are dropped.
        """
        _code = Code.from_dict(code)
        self._lookup[_code.code] = _code

    def get_code(self, code: str) -> Code:
        """
        Look up the full record for a code.

        Parameters:
            code (str): the code to look up, written the way the classification system writes it.

        Returns:
            Code: the record for that code.

        Raises:
            ValueError: if the code is not part of this classification system. This is far more often a formatting mismatch, such as a missing separator, than a genuinely absent category.
        """
        try:
            return self._lookup[code]
        except KeyError as e:
            raise ValueError(
                f"Code {code!r} is not in the classification system. "
                f"Check if your formatting was correct."
            ) from e

    def is_valid_code(self, code: str | None) -> bool:
        """
        Whether a code belongs to this classification system.

        This is what the classifiers check a generated code against, so it decides what
        counts as a usable answer. The comparison is exact: a code in the wrong notation,
        with stray whitespace, or carrying a separator the system does not use is not
        valid, even when the category it refers to exists. Codes added at runtime with
        `add_code` are included.

        Parameters:
            code (str|None): the code to check. None and the empty string are not valid.

        Returns:
            bool: True if the code is one of this system's codes.
        """
        return code in self._lookup

__init__

__init__(loader)

Loads the taxonomy through the loader and builds the code lookup.

This happens eagerly, so constructing a classification system reads and parses the source file.

Source code in rac4os/classification_system/BaseClassificationSystem.py
def __init__(self, loader: ClassificationLoader) -> None:
    """
    Loads the taxonomy through the loader and builds the code lookup.

    This happens eagerly, so constructing a classification system reads and parses
    the source file.
    """
    self.loader = loader
    self.codes: list[Code] = self.loader.load()
    self._lookup: dict[str, Code] = {c.code: c for c in self.codes}

add_code

add_code(code)

Add a single code to the live system without rebuilding it.

Useful for patching in a category the source documentation omits. Only the lookup is touched; self.codes stays as the loader returned it, so the addition does not survive into a system built freshly from the same source.

A flat system has nowhere to file the new code, so it takes no parent. The hierarchical subclass overrides this and accepts one.

Parameters:

Name Type Description Default
code dict

a Code-shaped dict; keys that Code does not define are dropped.

required
Source code in rac4os/classification_system/BaseClassificationSystem.py
def add_code(self, code: dict) -> None:
    """
    Add a single code to the live system without rebuilding it.

    Useful for patching in a category the source documentation omits. Only the lookup
    is touched; `self.codes` stays as the loader returned it, so the addition does not
    survive into a system built freshly from the same source.

    A flat system has nowhere to file the new code, so it takes no parent. The
    hierarchical subclass overrides this and accepts one.

    Parameters:
        code (dict): a `Code`-shaped dict; keys that `Code` does not define are dropped.
    """
    _code = Code.from_dict(code)
    self._lookup[_code.code] = _code

get_code

get_code(code)

Look up the full record for a code.

Parameters:

Name Type Description Default
code str

the code to look up, written the way the classification system writes it.

required

Returns:

Name Type Description
Code Code

the record for that code.

Raises:

Type Description
ValueError

if the code is not part of this classification system. This is far more often a formatting mismatch, such as a missing separator, than a genuinely absent category.

Source code in rac4os/classification_system/BaseClassificationSystem.py
def get_code(self, code: str) -> Code:
    """
    Look up the full record for a code.

    Parameters:
        code (str): the code to look up, written the way the classification system writes it.

    Returns:
        Code: the record for that code.

    Raises:
        ValueError: if the code is not part of this classification system. This is far more often a formatting mismatch, such as a missing separator, than a genuinely absent category.
    """
    try:
        return self._lookup[code]
    except KeyError as e:
        raise ValueError(
            f"Code {code!r} is not in the classification system. "
            f"Check if your formatting was correct."
        ) from e

is_valid_code

is_valid_code(code)

Whether a code belongs to this classification system.

This is what the classifiers check a generated code against, so it decides what counts as a usable answer. The comparison is exact: a code in the wrong notation, with stray whitespace, or carrying a separator the system does not use is not valid, even when the category it refers to exists. Codes added at runtime with add_code are included.

Parameters:

Name Type Description Default
code str | None

the code to check. None and the empty string are not valid.

required

Returns:

Name Type Description
bool bool

True if the code is one of this system's codes.

Source code in rac4os/classification_system/BaseClassificationSystem.py
def is_valid_code(self, code: str | None) -> bool:
    """
    Whether a code belongs to this classification system.

    This is what the classifiers check a generated code against, so it decides what
    counts as a usable answer. The comparison is exact: a code in the wrong notation,
    with stray whitespace, or carrying a separator the system does not use is not
    valid, even when the category it refers to exists. Codes added at runtime with
    `add_code` are included.

    Parameters:
        code (str|None): the code to check. None and the empty string are not valid.

    Returns:
        bool: True if the code is one of this system's codes.
    """
    return code in self._lookup

HierarchicalClassificationSystem

rac4os.classification_system.BaseClassificationSystem.HierarchicalClassificationSystem

Bases: ClassificationSystem

A classification whose codes nest: the interface for a taxonomy with levels.

On top of the flat system's lookup it answers the structural questions — what the first level is, and what sits below or above a code. This is what the hierarchy traversal agent walks and what taxonomy refinement reads children from; the retrieval-based classifiers accept it too, since it is a classification system like any other, but they only use the flat part.

Subclasses implement get_prefixes and get_root_categories and nothing else. The parent/child register, get_children, get_parent and get_code_trace are all derived from those two, so describing your own taxonomy comes down to answering two questions about how its codes are written.

Parameters:

Name Type Description Default
loader ClassificationLoader

loader that yields the Code records this system is built from.

required

Attributes:

Name Type Description
loader ClassificationLoader

the loader that was passed in.

codes list[Code]

every record the loader returned, in source order.

Source code in rac4os/classification_system/BaseClassificationSystem.py
class HierarchicalClassificationSystem(ClassificationSystem):
    """
    A classification whose codes nest: the interface for a taxonomy with levels.

    On top of the flat system's lookup it answers the structural questions — what the
    first level is, and what sits below or above a code. This is what the hierarchy
    traversal agent walks and what taxonomy refinement reads children from; the
    retrieval-based classifiers accept it too, since it is a classification system like
    any other, but they only use the flat part.

    Subclasses implement `get_prefixes` and `get_root_categories` and nothing else. The
    parent/child register, `get_children`, `get_parent` and `get_code_trace` are all
    derived from those two, so describing your own taxonomy comes down to answering two
    questions about how its codes are written.

    Parameters:
        loader (ClassificationLoader): loader that yields the `Code` records this system is built from.

    Attributes:
        loader (ClassificationLoader): the loader that was passed in.
        codes (list[Code]): every record the loader returned, in source order.
    """

    def __init__(self, loader: ClassificationLoader) -> None:
        """
        Loads the taxonomy as the flat system does, then derives the hierarchy from it.

        The parent/child register is built here, which means `get_prefixes` is called once
        per code at construction: a mistake in it surfaces as a wrong hierarchy right
        away rather than at the first navigation call.
        """
        super().__init__(loader)
        self.__initialise()

    def __initialise(self) -> None:
        """
        Builds the register the navigation accessors rely on.

        `_children_register` maps a code to the records directly below it, filled by asking
        `get_prefixes` for each code's second-to-last prefix, which is that code's parent.
        The code lookup itself is built by the flat base class.
        """
        self._children_register: dict[str, list[Code]] = {
            c.code: [] for c in self.codes
        }

        for child in self.codes:
            prefixes = self.get_prefixes(code=child.code)
            num_prefixes = len(prefixes)

            if (
                num_prefixes >= 2
                and prefixes[num_prefixes - 2] in self._children_register
            ):
                self._children_register[prefixes[num_prefixes - 2]].append(child)

    @abstractmethod
    def get_prefixes(self, code: str) -> list[str]:
        """
        Return every prefix of a code, from the broadest level down to the code itself.

        This is the one method that encodes how your taxonomy writes its codes: separators,
        fixed-width levels, padding. The last element is the code itself and the
        second-to-last is its parent, which is what the parent/child register is built from.

        Parameters:
            code (str): a code of this classification system.

        Returns:
            list[str]: the code's prefixes, broadest first, ending with the code itself.
        """
        ...

    @abstractmethod
    def get_root_categories(
        self,
    ) -> list[dict]:
        """
        Return the first level of the taxonomy.

        The hierarchy traversal agent starts here and descends, so this is the entry point
        into your classification. Each entry carries at least `code` and `description`.

        Returns:
            list[dict]: the categories at the first level of the hierarchy.
        """
        ...

    def _is_child(self, parent: str, potential_child: str) -> bool:
        """
        Whether one code sits directly below another.

        Compares the parent against the second-to-last prefix of the candidate, so only
        direct children count and a grandchild returns False.

        Parameters:
            parent (str): the code to test against.
            potential_child (str): the code that may sit directly below it.

        Returns:
            bool: True if `potential_child` is a direct child of `parent`.
        """
        potential_child_prefixes = self.get_prefixes(potential_child)
        num_prefixes = len(potential_child_prefixes)
        if num_prefixes < 2:
            return False
        return parent == potential_child_prefixes[num_prefixes - 2]

    @override
    def add_code(self, code: dict, parent: str | None = None):
        """
        Add a single code to the live system without rebuilding it, optionally under a parent.

        Useful for patching in a category the source documentation omits. Only the lookup and
        the parent's child list are touched; `self.codes` stays as the loader returned it, so
        the addition does not survive into a system built freshly from the same source.

        Parameters:
            code (dict): a `Code`-shaped dict; keys that `Code` does not define are dropped.
            parent (str|None): code to file the new entry under. Left out, the code is reachable through `get_code` but appears in no `get_children` result.
        """
        _code = Code.from_dict(code)
        self._lookup[_code.code] = _code
        if parent:
            if parent in self._children_register.keys():
                self._children_register[parent].append(_code)
            else:
                self._children_register[parent] = [_code]

    def get_children(self, code: str) -> list[Code]:
        """
        Return the categories directly below a code.

        Parameters:
            code (str): the parent code.

        Returns:
            list[Code]: the direct children; an empty list for a leaf or for a code the system does not know.
        """
        try:
            return self._children_register.get(code, [])
        except Exception as e:
            print(f"Code {code!r} hat no children.")
            raise ValueError(f"Code {code!r} hat no children. Exeption: {e}")

    def get_parent(self, parent: str) -> Code | None:
        """
        Return the category directly above a code.

        Parameters:
            parent (str): the code whose parent is wanted.

        Returns:
            Code|None: the parent record, or None if the code is already at the first level.
        """
        prefixes = self.get_prefixes(parent)
        num_prefixes = len(prefixes)
        if num_prefixes > 1:
            return self.get_code(code=prefixes[num_prefixes - 2])

    def get_code_trace(self, code: str) -> list[tuple[str, str]]:
        """
        Return the path from the first level down to a code.

        Each step is a `(code, description)` pair, so the trace reads as the chain of
        categories a human coder would have walked through. Prefixes that are not themselves
        categories of the system are skipped rather than raising, which keeps the trace usable
        for taxonomies whose levels are not all populated.

        Parameters:
            code (str): the code whose path is wanted.

        Returns:
            list[tuple[str, str]]: `(code, description)` pairs, broadest first, ending with the code itself.
        """
        prefixes = self.get_prefixes(code=code)
        trace = []
        for prefix in prefixes:
            try:
                trace.append((prefix, self._lookup[prefix].description))
            except (ValueError, KeyError):
                continue
        return trace

__init__

__init__(loader)

Loads the taxonomy as the flat system does, then derives the hierarchy from it.

The parent/child register is built here, which means get_prefixes is called once per code at construction: a mistake in it surfaces as a wrong hierarchy right away rather than at the first navigation call.

Source code in rac4os/classification_system/BaseClassificationSystem.py
def __init__(self, loader: ClassificationLoader) -> None:
    """
    Loads the taxonomy as the flat system does, then derives the hierarchy from it.

    The parent/child register is built here, which means `get_prefixes` is called once
    per code at construction: a mistake in it surfaces as a wrong hierarchy right
    away rather than at the first navigation call.
    """
    super().__init__(loader)
    self.__initialise()

get_prefixes abstractmethod

get_prefixes(code)

Return every prefix of a code, from the broadest level down to the code itself.

This is the one method that encodes how your taxonomy writes its codes: separators, fixed-width levels, padding. The last element is the code itself and the second-to-last is its parent, which is what the parent/child register is built from.

Parameters:

Name Type Description Default
code str

a code of this classification system.

required

Returns:

Type Description
list[str]

list[str]: the code's prefixes, broadest first, ending with the code itself.

Source code in rac4os/classification_system/BaseClassificationSystem.py
@abstractmethod
def get_prefixes(self, code: str) -> list[str]:
    """
    Return every prefix of a code, from the broadest level down to the code itself.

    This is the one method that encodes how your taxonomy writes its codes: separators,
    fixed-width levels, padding. The last element is the code itself and the
    second-to-last is its parent, which is what the parent/child register is built from.

    Parameters:
        code (str): a code of this classification system.

    Returns:
        list[str]: the code's prefixes, broadest first, ending with the code itself.
    """
    ...

get_root_categories abstractmethod

get_root_categories()

Return the first level of the taxonomy.

The hierarchy traversal agent starts here and descends, so this is the entry point into your classification. Each entry carries at least code and description.

Returns:

Type Description
list[dict]

list[dict]: the categories at the first level of the hierarchy.

Source code in rac4os/classification_system/BaseClassificationSystem.py
@abstractmethod
def get_root_categories(
    self,
) -> list[dict]:
    """
    Return the first level of the taxonomy.

    The hierarchy traversal agent starts here and descends, so this is the entry point
    into your classification. Each entry carries at least `code` and `description`.

    Returns:
        list[dict]: the categories at the first level of the hierarchy.
    """
    ...

add_code

add_code(code, parent=None)

Add a single code to the live system without rebuilding it, optionally under a parent.

Useful for patching in a category the source documentation omits. Only the lookup and the parent's child list are touched; self.codes stays as the loader returned it, so the addition does not survive into a system built freshly from the same source.

Parameters:

Name Type Description Default
code dict

a Code-shaped dict; keys that Code does not define are dropped.

required
parent str | None

code to file the new entry under. Left out, the code is reachable through get_code but appears in no get_children result.

None
Source code in rac4os/classification_system/BaseClassificationSystem.py
@override
def add_code(self, code: dict, parent: str | None = None):
    """
    Add a single code to the live system without rebuilding it, optionally under a parent.

    Useful for patching in a category the source documentation omits. Only the lookup and
    the parent's child list are touched; `self.codes` stays as the loader returned it, so
    the addition does not survive into a system built freshly from the same source.

    Parameters:
        code (dict): a `Code`-shaped dict; keys that `Code` does not define are dropped.
        parent (str|None): code to file the new entry under. Left out, the code is reachable through `get_code` but appears in no `get_children` result.
    """
    _code = Code.from_dict(code)
    self._lookup[_code.code] = _code
    if parent:
        if parent in self._children_register.keys():
            self._children_register[parent].append(_code)
        else:
            self._children_register[parent] = [_code]

get_children

get_children(code)

Return the categories directly below a code.

Parameters:

Name Type Description Default
code str

the parent code.

required

Returns:

Type Description
list[Code]

list[Code]: the direct children; an empty list for a leaf or for a code the system does not know.

Source code in rac4os/classification_system/BaseClassificationSystem.py
def get_children(self, code: str) -> list[Code]:
    """
    Return the categories directly below a code.

    Parameters:
        code (str): the parent code.

    Returns:
        list[Code]: the direct children; an empty list for a leaf or for a code the system does not know.
    """
    try:
        return self._children_register.get(code, [])
    except Exception as e:
        print(f"Code {code!r} hat no children.")
        raise ValueError(f"Code {code!r} hat no children. Exeption: {e}")

get_parent

get_parent(parent)

Return the category directly above a code.

Parameters:

Name Type Description Default
parent str

the code whose parent is wanted.

required

Returns:

Type Description
Code | None

Code|None: the parent record, or None if the code is already at the first level.

Source code in rac4os/classification_system/BaseClassificationSystem.py
def get_parent(self, parent: str) -> Code | None:
    """
    Return the category directly above a code.

    Parameters:
        parent (str): the code whose parent is wanted.

    Returns:
        Code|None: the parent record, or None if the code is already at the first level.
    """
    prefixes = self.get_prefixes(parent)
    num_prefixes = len(prefixes)
    if num_prefixes > 1:
        return self.get_code(code=prefixes[num_prefixes - 2])

get_code_trace

get_code_trace(code)

Return the path from the first level down to a code.

Each step is a (code, description) pair, so the trace reads as the chain of categories a human coder would have walked through. Prefixes that are not themselves categories of the system are skipped rather than raising, which keeps the trace usable for taxonomies whose levels are not all populated.

Parameters:

Name Type Description Default
code str

the code whose path is wanted.

required

Returns:

Type Description
list[tuple[str, str]]

list[tuple[str, str]]: (code, description) pairs, broadest first, ending with the code itself.

Source code in rac4os/classification_system/BaseClassificationSystem.py
def get_code_trace(self, code: str) -> list[tuple[str, str]]:
    """
    Return the path from the first level down to a code.

    Each step is a `(code, description)` pair, so the trace reads as the chain of
    categories a human coder would have walked through. Prefixes that are not themselves
    categories of the system are skipped rather than raising, which keeps the trace usable
    for taxonomies whose levels are not all populated.

    Parameters:
        code (str): the code whose path is wanted.

    Returns:
        list[tuple[str, str]]: `(code, description)` pairs, broadest first, ending with the code itself.
    """
    prefixes = self.get_prefixes(code=code)
    trace = []
    for prefix in prefixes:
        try:
            trace.append((prefix, self._lookup[prefix].description))
        except (ValueError, KeyError):
            continue
    return trace

Registry and dataset mapping

rac4os.classification_system.registry

register

register(name)

Class decorator that registers a HierarchicalClassificationSystem implementation under a name.

The name is the one a dataset refers to in mapping through its classification_system key, which is how get_classification_system finds the class to build.

Parameters:

Name Type Description Default
name str

key to register the decorated class under.

required

Returns:

Name Type Description
Callable Callable

the decorator, which registers the class and returns it unchanged.

Source code in rac4os/classification_system/registry.py
def register(name: str) -> Callable:
    """
    Class decorator that registers a `HierarchicalClassificationSystem` implementation
    under a name.

    The name is the one a dataset refers to in `mapping` through its
    `classification_system` key, which is how `get_classification_system` finds the class
    to build.

    Parameters:
        name (str): key to register the decorated class under.

    Returns:
        Callable: the decorator, which registers the class and returns it unchanged.
    """

    def deco(cls):
        """
        Registers the decorated class under the captured name.

        Parameters:
            cls (type[ClassificationSystem]): the class being decorated.

        Returns:
            type[HierarchicalClassificationSystem]: the same class, unmodified.
        """
        _REGISTRY_CS[name] = cls
        return cls

    return deco

get_classification_system

get_classification_system(name)

Build the classification system for a registered dataset name.

Looks the name up in mapping, builds the loader named there for the data path given there, and hands that loader to the registered ClassificationSystem subclass. This is purely a convenience: it exists so a dataset can be referred to by one name instead of wiring a loader and a system class together at every call site. Constructing the two by hand stays equally valid and is what you do for a taxonomy you have not registered.

Parameters:

Name Type Description Default
name str

a key of mapping, such as "COICOP_2018", or one you registered yourself.

required

Returns:

Name Type Description
HierarchicalClassificationSystem HierarchicalClassificationSystem

a system built from that dataset, ready to query. Every registered dataset is hierarchical; a flat classification is built by constructing ClassificationSystem with your loader directly.

Raises:

Type Description
ValueError

if the name is not in mapping, or if the class it names was never registered.

Source code in rac4os/classification_system/registry.py
def get_classification_system(name: str) -> HierarchicalClassificationSystem:
    """
    Build the classification system for a registered dataset name.

    Looks the name up in `mapping`, builds the loader named there for the data path given
    there, and hands that loader to the registered `ClassificationSystem` subclass. This
    is purely a convenience: it exists so a dataset can be referred to by one name instead
    of wiring a loader and a system class together at every call site. Constructing the
    two by hand stays equally valid and is what you do for a taxonomy you have not
    registered.

    Parameters:
        name (str): a key of `mapping`, such as "COICOP_2018", or one you registered yourself.

    Returns:
        HierarchicalClassificationSystem: a system built from that dataset, ready to query.
            Every registered dataset is hierarchical; a flat classification is built by
            constructing `ClassificationSystem` with your loader directly.

    Raises:
        ValueError: if the name is not in `mapping`, or if the class it names was never registered.
    """
    try:
        cls = _REGISTRY_CS[mapping[name]["classification_system"]]
        loader = get_loader(mapping[name]["loader_name"], mapping[name]["data_path"])
        return cls(loader)
    except KeyError:
        raise ValueError(f"Unknown format {name!r}; known: {sorted(_REGISTRY_CS)}")
        return

Bundled systems

ClassificationSystemICATUS

Bases: HierarchicalClassificationSystem

Classification system for ICATUS 2016, registered under "ICATUS".

ICATUS codes are plain digit strings whose length is their level, so each additional digit descends one level: 1 above 11 above 111.

Source code in rac4os/classification_system/systems/ClassificationSystems.py
@register("ICATUS")
class ClassificationSystemICATUS(HierarchicalClassificationSystem):
    """
    Classification system for ICATUS 2016, registered under "ICATUS".

    ICATUS codes are plain digit strings whose length is their level, so each additional
    digit descends one level: `1` above `11` above `111`.
    """

    def get_root_categories(self) -> list[dict]:
        """
        Return the first level of the hierarchy.

        Returns:
            list[dict]: one `code`/`description` dict per single-digit major division.
        """
        return [
            {"code": c.code, "description": c.description}
            for c in self.codes
            if len(c.code) == 1
        ]

    def get_prefixes(self, code: str) -> list[str]:
        """
        Return the prefixes of a ICATUS code, broadest first.

        One prefix per leading digit, since a code's length is its level.

        Parameters:
            code (str): a ICATUS code.

        Returns:
            list[str]: the code's prefixes, ending with the code itself.
        """
        return [code[:i] for i in range(1, len(code) + 1)]

get_root_categories

get_root_categories()

Return the first level of the hierarchy.

Returns:

Type Description
list[dict]

list[dict]: one code/description dict per single-digit major division.

Source code in rac4os/classification_system/systems/ClassificationSystems.py
def get_root_categories(self) -> list[dict]:
    """
    Return the first level of the hierarchy.

    Returns:
        list[dict]: one `code`/`description` dict per single-digit major division.
    """
    return [
        {"code": c.code, "description": c.description}
        for c in self.codes
        if len(c.code) == 1
    ]

get_prefixes

get_prefixes(code)

Return the prefixes of a ICATUS code, broadest first.

One prefix per leading digit, since a code's length is its level.

Parameters:

Name Type Description Default
code str

a ICATUS code.

required

Returns:

Type Description
list[str]

list[str]: the code's prefixes, ending with the code itself.

Source code in rac4os/classification_system/systems/ClassificationSystems.py
def get_prefixes(self, code: str) -> list[str]:
    """
    Return the prefixes of a ICATUS code, broadest first.

    One prefix per leading digit, since a code's length is its level.

    Parameters:
        code (str): a ICATUS code.

    Returns:
        list[str]: the code's prefixes, ending with the code itself.
    """
    return [code[:i] for i in range(1, len(code) + 1)]

ClassificationSystemCOICOP

Bases: HierarchicalClassificationSystem

Classification system for COICOP 2018, registered under "COICOP".

COICOP codes are dot-separated groups of digits and the number of groups is the level, so 01 sits above 01.1, which sits above 01.1.1.

Source code in rac4os/classification_system/systems/ClassificationSystems.py
@register("COICOP")
class ClassificationSystemCOICOP(HierarchicalClassificationSystem):
    """
    Classification system for COICOP 2018, registered under "COICOP".

    COICOP codes are dot-separated groups of digits and the number of groups is the level,
    so `01` sits above `01.1`, which sits above `01.1.1`.
    """

    def get_root_categories(self) -> list[dict]:
        """
        Return the first level of the hierarchy.

        Returns:
            list[dict]: one `code`/`description` dict per two-digit division.
        """
        return [
            {"code": c.code, "description": c.description}
            for c in self.codes
            if len(c.code) == 2
        ]

    def get_prefixes(self, code: str) -> list[str]:
        """
        Return the prefixes of a COICOP code, broadest first.

        The code is split on the dot and rejoined one group at a time, so the separator is
        preserved in every prefix.

        Parameters:
            code (str): a COICOP code.

        Returns:
            list[str]: the code's prefixes, ending with the code itself.
        """
        codes = code.split(".")
        return [".".join(codes[:i]) for i in range(1, len(codes) + 1)]

get_root_categories

get_root_categories()

Return the first level of the hierarchy.

Returns:

Type Description
list[dict]

list[dict]: one code/description dict per two-digit division.

Source code in rac4os/classification_system/systems/ClassificationSystems.py
def get_root_categories(self) -> list[dict]:
    """
    Return the first level of the hierarchy.

    Returns:
        list[dict]: one `code`/`description` dict per two-digit division.
    """
    return [
        {"code": c.code, "description": c.description}
        for c in self.codes
        if len(c.code) == 2
    ]

get_prefixes

get_prefixes(code)

Return the prefixes of a COICOP code, broadest first.

The code is split on the dot and rejoined one group at a time, so the separator is preserved in every prefix.

Parameters:

Name Type Description Default
code str

a COICOP code.

required

Returns:

Type Description
list[str]

list[str]: the code's prefixes, ending with the code itself.

Source code in rac4os/classification_system/systems/ClassificationSystems.py
def get_prefixes(self, code: str) -> list[str]:
    """
    Return the prefixes of a COICOP code, broadest first.

    The code is split on the dot and rejoined one group at a time, so the separator is
    preserved in every prefix.

    Parameters:
        code (str): a COICOP code.

    Returns:
        list[str]: the code's prefixes, ending with the code itself.
    """
    codes = code.split(".")
    return [".".join(codes[:i]) for i in range(1, len(codes) + 1)]

ClassificationSystemSEA

Bases: HierarchicalClassificationSystem

Classification system for the SEA 2021, registered under "SEA".

SEA codes follow COICOP down to four digits and then continue after a space, so 01 sits above 0111, which sits above 0111 100. Spaces are stripped before the hierarchy is derived and re-inserted after the fourth digit.

Source code in rac4os/classification_system/systems/ClassificationSystems.py
@register("SEA")
class ClassificationSystemSEA(HierarchicalClassificationSystem):
    """
    Classification system for the SEA 2021, registered under "SEA".

    SEA codes follow COICOP down to four digits and then continue after a space, so `01`
    sits above `0111`, which sits above `0111 100`. Spaces are stripped before the
    hierarchy is derived and re-inserted after the fourth digit.
    """

    def get_root_categories(self) -> list[dict]:
        """
        Return the first level of the hierarchy.

        Returns:
            list[dict]: one `code`/`description` dict per two-digit division.
        """
        return [
            {"code": c.code, "description": c.description}
            for c in self.codes
            if len(c.code) == 2
        ]

    def get_prefixes(self, code: str) -> list[str]:
        """
        Return the prefixes of a SEA code, broadest first.

        Spaces are removed first; prefixes up to four digits are cut directly, and longer ones
        get a space re-inserted after the fourth digit, which is the notation the published
        SEA uses.

        Parameters:
            code (str): a SEA code.

        Returns:
            list[str]: the code's prefixes, ending with the code itself.
        """
        code = code.replace(" ", "")
        prefixes = []
        for i in range(2, len(code) + 1):
            if i <= 4:
                prefixes.append(code[:i])
            else:
                prefixes.append(code[:4] + " " + code[4:i])
        return prefixes

get_root_categories

get_root_categories()

Return the first level of the hierarchy.

Returns:

Type Description
list[dict]

list[dict]: one code/description dict per two-digit division.

Source code in rac4os/classification_system/systems/ClassificationSystems.py
def get_root_categories(self) -> list[dict]:
    """
    Return the first level of the hierarchy.

    Returns:
        list[dict]: one `code`/`description` dict per two-digit division.
    """
    return [
        {"code": c.code, "description": c.description}
        for c in self.codes
        if len(c.code) == 2
    ]

get_prefixes

get_prefixes(code)

Return the prefixes of a SEA code, broadest first.

Spaces are removed first; prefixes up to four digits are cut directly, and longer ones get a space re-inserted after the fourth digit, which is the notation the published SEA uses.

Parameters:

Name Type Description Default
code str

a SEA code.

required

Returns:

Type Description
list[str]

list[str]: the code's prefixes, ending with the code itself.

Source code in rac4os/classification_system/systems/ClassificationSystems.py
def get_prefixes(self, code: str) -> list[str]:
    """
    Return the prefixes of a SEA code, broadest first.

    Spaces are removed first; prefixes up to four digits are cut directly, and longer ones
    get a space re-inserted after the fourth digit, which is the notation the published
    SEA uses.

    Parameters:
        code (str): a SEA code.

    Returns:
        list[str]: the code's prefixes, ending with the code itself.
    """
    code = code.replace(" ", "")
    prefixes = []
    for i in range(2, len(code) + 1):
        if i <= 4:
            prefixes.append(code[:i])
        else:
            prefixes.append(code[:4] + " " + code[4:i])
    return prefixes