5"""Load and execute exported trees with the base QDpy install."""
9from pathlib
import Path
13from .modern
import _positive_int
15__all__ = [
"DecisionTreePolicy"]
20def _validate_node(node, width, actions, level=0):
21 if type(node)
is int
and 0 <= node < actions:
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))
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
42 return 1 + max(_depth(node[2]), _depth(node[3]))
if isinstance(node, tuple)
else 0
47 """Evaluate an axis-aligned tree without training state or an environment.
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.
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.
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.")
70 """Return the maximum number of splits encountered along a route."""
71 return _depth(self.
_tree)
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}.")
85 """Write only the tree, action layout, and observation shape."""
86 payload = {
"format":
"qdpy-decision-tree-v1",
"tree": self.
_tree,
89 Path(path).write_text(json.dumps(payload, allow_nan=
False, indent=2) +
"\n", encoding=
"utf-8")
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.