|
| 1 | +from typing import Optional |
| 2 | + |
| 3 | +import numpy as np |
| 4 | + |
| 5 | +from ._cluster_model import ClusterModel |
| 6 | +from ..base import Estimator |
| 7 | + |
| 8 | + |
| 9 | +class BoxDiscretizationModel(ClusterModel): |
| 10 | + r""" Model produced by :class:`BoxDiscretization`. Can be used to discretize and/or one-hot transform data. |
| 11 | +
|
| 12 | + Parameters |
| 13 | + ---------- |
| 14 | + cluster_centers : ndarray |
| 15 | + The cluster centers. |
| 16 | + v0 : ndarray |
| 17 | + Lower left vertex of box. |
| 18 | + v1 : ndarray |
| 19 | + Upper right vertex of box. |
| 20 | + n_boxes : int |
| 21 | + Number of boxes. |
| 22 | + """ |
| 23 | + |
| 24 | + def __init__(self, cluster_centers: np.ndarray, v0, v1, n_boxes): |
| 25 | + super().__init__(cluster_centers) |
| 26 | + self.v0 = v0 |
| 27 | + self.v1 = v1 |
| 28 | + self.n_boxes = n_boxes |
| 29 | + |
| 30 | + def transform_onehot(self, data, n_jobs=None): |
| 31 | + r"""Transforms data into discrete states with subsequent one-hot encoding. |
| 32 | +
|
| 33 | + Parameters |
| 34 | + ---------- |
| 35 | + data : ndarray |
| 36 | + Input data |
| 37 | + n_jobs : int or None, optional, default=None |
| 38 | + Number of jobs. |
| 39 | +
|
| 40 | + Returns |
| 41 | + ------- |
| 42 | + one_hot : ndarray |
| 43 | + A (T, n_boxes) shaped array with one-hot encoded data. |
| 44 | + """ |
| 45 | + dtraj = self.transform(data, n_jobs=n_jobs) |
| 46 | + traj_onehot = np.zeros((len(data), self.n_clusters)) |
| 47 | + traj_onehot[np.arange(len(data)), dtraj] = 1. |
| 48 | + return traj_onehot |
| 49 | + |
| 50 | + |
| 51 | +class BoxDiscretization(Estimator): |
| 52 | + r"""An n-dimensional box discretization of Euclidean space. |
| 53 | +
|
| 54 | + It spans an n-dimensional grid based on linspaces along each axis which is then used as cluster centers. |
| 55 | + The linspaces are bounded either by the user (attributes :attr:`v0` and :attr:`v1`) or estimated from data. |
| 56 | +
|
| 57 | + Parameters |
| 58 | + ---------- |
| 59 | + dim : int |
| 60 | + Dimension of the box discretization. |
| 61 | + n_boxes : int or list of int |
| 62 | + Number of boxes per dimension of - if given as single integer - for all dimensions. |
| 63 | + v0 : array or None, optional, default=None |
| 64 | + Lower left vertex of the box discretization. If not given this is estimated from data. |
| 65 | + v1 : array or None, optional, default=None |
| 66 | + Upper right vertex of the box discretization. If not given this is estimated from data. |
| 67 | + """ |
| 68 | + |
| 69 | + def __init__(self, dim: int, n_boxes, v0=None, v1=None): |
| 70 | + super().__init__() |
| 71 | + if not isinstance(n_boxes, (list, tuple, np.ndarray)): |
| 72 | + if int(n_boxes) == n_boxes: |
| 73 | + n_boxes = [int(n_boxes)] * dim |
| 74 | + if len(n_boxes) != dim: |
| 75 | + raise ValueError(f"Dimension and number of boxes per dimension did not match ({len(n_boxes)} and {dim}).") |
| 76 | + if v0 is not None and len(v0) != dim: |
| 77 | + raise ValueError("Length of v0 did not match dimension.") |
| 78 | + if v1 is not None and len(v1) != dim: |
| 79 | + raise ValueError("Length of v1 did not match dimension.") |
| 80 | + self.dim = dim |
| 81 | + self.n_boxes = n_boxes |
| 82 | + self.v0 = v0 |
| 83 | + self.v1 = v1 |
| 84 | + |
| 85 | + def fit(self, data: np.ndarray, **kwargs): |
| 86 | + assert data.shape[1] == self.dim |
| 87 | + if self.v0 is None or self.v1 is None: |
| 88 | + v0 = np.empty((self.dim,), dtype=data.dtype) if self.v0 is None else self.v0 |
| 89 | + v1 = np.empty((self.dim,), dtype=data.dtype) if self.v1 is None else self.v1 |
| 90 | + for d in range(self.dim): |
| 91 | + if self.v0 is None: |
| 92 | + v0[d] = np.min(data[:, d]) |
| 93 | + if self.v1 is None: |
| 94 | + v1[d] = np.max(data[:, d]) |
| 95 | + else: |
| 96 | + v0 = self.v0 |
| 97 | + v1 = self.v1 |
| 98 | + linspaces = [np.linspace(v0[d], v1[d], num=self.n_boxes[d], endpoint=True) for d in range(self.dim)] |
| 99 | + mesh = np.vstack(np.meshgrid(*tuple(linspaces))).reshape(self.dim, -1).T |
| 100 | + self._model = BoxDiscretizationModel(mesh, v0, v1, self.n_boxes) |
| 101 | + return self |
| 102 | + |
| 103 | + def fetch_model(self) -> Optional[BoxDiscretizationModel]: |
| 104 | + r""" Yields the estimated model. |
| 105 | +
|
| 106 | + Returns |
| 107 | + ------- |
| 108 | + model : BoxDiscretizationModel or None |
| 109 | + The model. |
| 110 | + """ |
| 111 | + return super().fetch_model() |
0 commit comments