{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Demonstration for parsing JSON/UBJSON tree model files\n\nSee :doc:`/tutorials/saving_model` for details about the model serialization.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import argparse\nimport json\nfrom dataclasses import dataclass\nfrom enum import IntEnum, unique\nfrom typing import Any, Dict, List, Sequence, Union\n\nimport numpy as np\n\ntry:\n    import ubjson\nexcept ImportError:\n    ubjson = None\n\n\nParamT = Dict[str, str]\n\n\ndef to_integers(data: Union[bytes, List[int]]) -> List[int]:\n    \"\"\"Convert a sequence of bytes to a list of Python integer\"\"\"\n    return [v for v in data]\n\n\n@unique\nclass SplitType(IntEnum):\n    numerical = 0\n    categorical = 1\n\n\n@dataclass\nclass Node:\n    # properties\n    left: int\n    right: int\n    parent: int\n    split_idx: int\n    split_cond: float\n    default_left: bool\n    split_type: SplitType\n    categories: List[int]\n    # statistic\n    base_weight: float\n    loss_chg: float\n    sum_hess: float\n\n\nclass Tree:\n    \"\"\"A tree built by XGBoost.\"\"\"\n\n    def __init__(self, tree_id: int, nodes: Sequence[Node]) -> None:\n        self.tree_id = tree_id\n        self.nodes = nodes\n\n    def loss_change(self, node_id: int) -> float:\n        \"\"\"Loss gain of a node.\"\"\"\n        return self.nodes[node_id].loss_chg\n\n    def sum_hessian(self, node_id: int) -> float:\n        \"\"\"Sum Hessian of a node.\"\"\"\n        return self.nodes[node_id].sum_hess\n\n    def base_weight(self, node_id: int) -> float:\n        \"\"\"Base weight of a node.\"\"\"\n        return self.nodes[node_id].base_weight\n\n    def split_index(self, node_id: int) -> int:\n        \"\"\"Split feature index of node.\"\"\"\n        return self.nodes[node_id].split_idx\n\n    def split_condition(self, node_id: int) -> float:\n        \"\"\"Split value of a node.\"\"\"\n        return self.nodes[node_id].split_cond\n\n    def split_categories(self, node_id: int) -> List[int]:\n        \"\"\"Categories in a node.\"\"\"\n        return self.nodes[node_id].categories\n\n    def is_categorical(self, node_id: int) -> bool:\n        \"\"\"Whether a node has categorical split.\"\"\"\n        return self.nodes[node_id].split_type == SplitType.categorical\n\n    def is_numerical(self, node_id: int) -> bool:\n        return not self.is_categorical(node_id)\n\n    def parent(self, node_id: int) -> int:\n        \"\"\"Parent ID of a node.\"\"\"\n        return self.nodes[node_id].parent\n\n    def left_child(self, node_id: int) -> int:\n        \"\"\"Left child ID of a node.\"\"\"\n        return self.nodes[node_id].left\n\n    def right_child(self, node_id: int) -> int:\n        \"\"\"Right child ID of a node.\"\"\"\n        return self.nodes[node_id].right\n\n    def is_leaf(self, node_id: int) -> bool:\n        \"\"\"Whether a node is leaf.\"\"\"\n        return self.nodes[node_id].left == -1\n\n    def is_deleted(self, node_id: int) -> bool:\n        \"\"\"Whether a node is deleted.\"\"\"\n        return self.split_index(node_id) == np.iinfo(np.uint32).max\n\n    def __str__(self) -> str:\n        stack = [0]\n        nodes = []\n        while stack:\n            node: Dict[str, Union[float, int, List[int]]] = {}\n            nid = stack.pop()\n\n            node[\"node id\"] = nid\n            node[\"gain\"] = self.loss_change(nid)\n            node[\"cover\"] = self.sum_hessian(nid)\n            nodes.append(node)\n\n            if not self.is_leaf(nid) and not self.is_deleted(nid):\n                left = self.left_child(nid)\n                right = self.right_child(nid)\n                stack.append(left)\n                stack.append(right)\n                categories = self.split_categories(nid)\n                if categories:\n                    assert self.is_categorical(nid)\n                    node[\"categories\"] = categories\n                else:\n                    assert self.is_numerical(nid)\n                    node[\"condition\"] = self.split_condition(nid)\n            if self.is_leaf(nid):\n                node[\"weight\"] = self.split_condition(nid)\n\n        string = \"\\n\".join(map(lambda x: \"  \" + str(x), nodes))\n        return string\n\n\nclass Model:\n    \"\"\"Gradient boosted tree model.\"\"\"\n\n    def __init__(self, model: dict) -> None:\n        \"\"\"Construct the Model from a JSON object.\n\n        parameters\n        ----------\n         model : A dictionary loaded by json representing a XGBoost boosted tree model.\n        \"\"\"\n        # Basic properties of a model\n        self.learner_model_shape: ParamT = model[\"learner\"][\"learner_model_param\"]\n        self.num_output_group = int(self.learner_model_shape[\"num_class\"])\n        self.num_feature = int(self.learner_model_shape[\"num_feature\"])\n        self.base_score: List[float] = json.loads(\n            self.learner_model_shape[\"base_score\"]\n        )\n        # A field encoding which output group a tree belongs\n        self.tree_info = model[\"learner\"][\"gradient_booster\"][\"model\"][\"tree_info\"]\n\n        model_shape: ParamT = model[\"learner\"][\"gradient_booster\"][\"model\"][\n            \"gbtree_model_param\"\n        ]\n\n        # JSON representation of trees\n        j_trees = model[\"learner\"][\"gradient_booster\"][\"model\"][\"trees\"]\n\n        # Load the trees\n        self.num_trees = int(model_shape[\"num_trees\"])\n\n        trees: List[Tree] = []\n        for i in range(self.num_trees):\n            tree: Dict[str, Any] = j_trees[i]\n            tree_id = int(tree[\"id\"])\n            assert tree_id == i, (tree_id, i)\n            # - properties\n            left_children: List[int] = tree[\"left_children\"]\n            right_children: List[int] = tree[\"right_children\"]\n            parents: List[int] = tree[\"parents\"]\n            split_conditions: List[float] = tree[\"split_conditions\"]\n            split_indices: List[int] = tree[\"split_indices\"]\n            # when ubjson is used, this is a byte array with each element as uint8\n            default_left = to_integers(tree[\"default_left\"])\n\n            # - categorical features\n            # when ubjson is used, this is a byte array with each element as uint8\n            split_types = to_integers(tree[\"split_type\"])\n            # categories for each node is stored in a CSR style storage with segment as\n            # the begin ptr and the `categories' as values.\n            cat_segments: List[int] = tree[\"categories_segments\"]\n            cat_sizes: List[int] = tree[\"categories_sizes\"]\n            # node index for categorical nodes\n            cat_nodes: List[int] = tree[\"categories_nodes\"]\n            assert len(cat_segments) == len(cat_sizes) == len(cat_nodes)\n            cats = tree[\"categories\"]\n            assert len(left_children) == len(split_types)\n\n            # The storage for categories is only defined for categorical nodes to\n            # prevent unnecessary overhead for numerical splits, we track the\n            # categorical node that are processed using a counter.\n            cat_cnt = 0\n            if cat_nodes:\n                last_cat_node = cat_nodes[cat_cnt]\n            else:\n                last_cat_node = -1\n            node_categories: List[List[int]] = []\n            for node_id in range(len(left_children)):\n                if node_id == last_cat_node:\n                    beg = cat_segments[cat_cnt]\n                    size = cat_sizes[cat_cnt]\n                    end = beg + size\n                    node_cats = cats[beg:end]\n                    # categories are unique for each node\n                    assert len(set(node_cats)) == len(node_cats)\n                    cat_cnt += 1\n                    if cat_cnt == len(cat_nodes):\n                        last_cat_node = -1  # continue to process the rest of the nodes\n                    else:\n                        last_cat_node = cat_nodes[cat_cnt]\n                    assert node_cats\n                    node_categories.append(node_cats)\n                else:\n                    # append an empty node, it's either a numerical node or a leaf.\n                    node_categories.append([])\n\n            # - stats\n            base_weights: List[float] = tree[\"base_weights\"]\n            loss_changes: List[float] = tree[\"loss_changes\"]\n            sum_hessian: List[float] = tree[\"sum_hessian\"]\n\n            # Construct a list of nodes that have complete information\n            nodes: List[Node] = [\n                Node(\n                    left_children[node_id],\n                    right_children[node_id],\n                    parents[node_id],\n                    split_indices[node_id],\n                    split_conditions[node_id],\n                    default_left[node_id] == 1,  # to boolean\n                    SplitType(split_types[node_id]),\n                    node_categories[node_id],\n                    base_weights[node_id],\n                    loss_changes[node_id],\n                    sum_hessian[node_id],\n                )\n                for node_id in range(len(left_children))\n            ]\n\n            pytree = Tree(tree_id, nodes)\n            trees.append(pytree)\n\n        self.trees = trees\n\n    def print_model(self) -> None:\n        for i, tree in enumerate(self.trees):\n            print(\"\\ntree_id:\", i)\n            print(tree)\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(\n        description=\"Demonstration for loading XGBoost JSON/UBJSON model.\"\n    )\n    parser.add_argument(\n        \"--model\", type=str, required=True, help=\"Path to .json/.ubj model file.\"\n    )\n    args = parser.parse_args()\n    if args.model.endswith(\"json\"):\n        # use json format\n        with open(args.model, \"r\") as fd:\n            model = json.load(fd)\n    elif args.model.endswith(\"ubj\"):\n        if ubjson is None:\n            raise ImportError(\"ubjson is not installed.\")\n        # use ubjson format\n        with open(args.model, \"rb\") as bfd:\n            model = ubjson.load(bfd)\n    else:\n        raise ValueError(\n            \"Unexpected file extension. Supported file extension are json and ubj.\"\n        )\n    model = Model(model)\n    model.print_model()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.17"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}