QDpy
Loading...
Searching...
No Matches
tree_policy.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Load and execute exported trees with the base QDpy install."""
6
7import json
8from math import prod
9from pathlib import Path
10
11import numpy as np
12
13from .modern import _positive_int
14
15__all__ = ["DecisionTreePolicy"]
16
17_MAX_DEPTH = 12
18
19
20def _validate_node(node, width, actions, level=0):
21 if type(node) is int and 0 <= node < actions:
22 return node
23 if (not isinstance(node, (list, tuple)) or len(node) != 4 or level >= _MAX_DEPTH
24 or type(node[0]) is not int or not 0 <= node[0] < width
25 or type(node[1]) not in (int, float)):
26 raise ValueError("Expected a valid action index or [feature, threshold, left, right] split.")
27 feature, threshold, left, right = node
28 if not np.isfinite(float(threshold)):
29 raise ValueError("Split thresholds must be finite.")
30 return (feature, float(threshold), _validate_node(left, width, actions, level + 1),
31 _validate_node(right, width, actions, level + 1))
32
33
34def _leaf(node, observation):
35 while isinstance(node, tuple):
36 feature, threshold, left, right = node
37 node = left if float(observation[feature]) <= threshold else right
38 return node
39
40
41def _depth(node):
42 return 1 + max(_depth(node[2]), _depth(node[3])) if isinstance(node, tuple) else 0
43
44
45
47 """Evaluate an axis-aligned tree without training state or an environment.
48
49 A node is either a zero-based action index or a list of four values
50 containing a flat feature index, threshold, and the two child nodes.
51 The left branch includes observations equal to the threshold. The
52 action offset preserves Gymnasium Discrete spaces with nonzero starts.
53
54 :param tree: Nested axis-aligned splits and greedy leaf action indices.
55 :param observation_shape: Shape of the original numeric Box space.
56 :param action_count: Number of possible categorical actions.
57 :param action_start: First action in the original Discrete space.
58 """
59
60 def __init__(self, tree, observation_shape, action_count, action_start=0):
61 self._shape = tuple(_positive_int(size, "Observation axis") for size in observation_shape)
62 self._action_count = _positive_int(action_count, "action_count")
63 if isinstance(action_start, (bool, np.bool_)) or not isinstance(action_start, (int, np.integer)):
64 raise ValueError("action_start must be an integer.")
65 self._action_start = int(action_start)
66 self._tree = _validate_node(tree, prod(self._shape), self._action_count)
67
68 @property
69 def depth(self):
70 """Return the maximum number of splits encountered along a route."""
71 return _depth(self._tree)
72
73
75 def act(self, observation):
76 """Follow the tree and add the environment's action offset."""
77 values = np.asarray(observation, dtype=np.float32)
78 if values.shape != self._shape or not np.isfinite(values).all():
79 raise ValueError(f"Expected a finite observation with shape {self._shape}.")
80 return self._action_start + _leaf(self._tree, values.reshape(-1))
81
82
84 def save(self, path):
85 """Write only the tree, action layout, and observation shape."""
86 payload = {"format": "qdpy-decision-tree-v1", "tree": self._tree,
87 "observation_shape": self._shape, "action_count": self._action_count,
88 "action_start": self._action_start}
89 Path(path).write_text(json.dumps(payload, allow_nan=False, indent=2) + "\n", encoding="utf-8")
90
91
93 @classmethod
94 def load(cls, path):
95 """Read and validate a policy independently of the search instance."""
96 payload = json.loads(Path(path).read_text(encoding="utf-8"))
97 if not isinstance(payload, dict) or payload.pop("format", None) != "qdpy-decision-tree-v1":
98 raise ValueError("Unsupported decision tree policy format.")
99 if set(payload) != {"tree", "observation_shape", "action_count", "action_start"}:
100 raise ValueError("Invalid decision tree policy fields.")
101 return cls(**payload)
A deterministic decision tree with portable JSON inference.
save(self, path)
Export the fitted policy as versioned JSON.
load(cls, path)
Reconstruct a fitted policy from a versioned JSON file.
act(self, observation)
Return the greedy environment action for one observation.