|
| 1 | +from collections.abc import Sequence |
| 2 | +import numpy as np |
| 3 | + |
| 4 | +from keras.saving import ( |
| 5 | + deserialize_keras_object as deserialize, |
| 6 | + register_keras_serializable as serializable, |
| 7 | + serialize_keras_object as serialize, |
| 8 | +) |
| 9 | + |
| 10 | +from .transform import Transform |
| 11 | + |
| 12 | + |
| 13 | +@serializable(package="bayesflow.adapters") |
| 14 | +class Split(Transform): |
| 15 | + """This is the effective inverse of the :py:class:`~Concatenate` Transform. |
| 16 | +
|
| 17 | + Parameters |
| 18 | + ---------- |
| 19 | + key : str |
| 20 | + The key to split in the forward transform. |
| 21 | + into: Sequence[str] |
| 22 | + The names of each split after the forward transform. |
| 23 | + indices_or_sections : int | Sequence[int], optional, default: None |
| 24 | + The number of sections or indices to split on. If not given, will split evenly into len(into) parts. |
| 25 | + axis: int, optional, default: -1 |
| 26 | + The axis to split on. |
| 27 | + """ |
| 28 | + |
| 29 | + def __init__(self, key: str, into: Sequence[str], indices_or_sections: int | Sequence[int] = None, axis: int = -1): |
| 30 | + self.axis = axis |
| 31 | + self.key = key |
| 32 | + self.into = into |
| 33 | + |
| 34 | + if indices_or_sections is None: |
| 35 | + indices_or_sections = len(into) |
| 36 | + |
| 37 | + self.indices_or_sections = indices_or_sections |
| 38 | + |
| 39 | + @classmethod |
| 40 | + def from_config(cls, config: dict, custom_objects=None) -> "Split": |
| 41 | + return cls( |
| 42 | + key=deserialize(config["key"], custom_objects), |
| 43 | + into=deserialize(config["into"], custom_objects), |
| 44 | + indices_or_sections=deserialize(config["indices_or_sections"], custom_objects), |
| 45 | + axis=deserialize(config["axis"], custom_objects), |
| 46 | + ) |
| 47 | + |
| 48 | + def get_config(self) -> dict: |
| 49 | + return { |
| 50 | + "key": serialize(self.key), |
| 51 | + "into": serialize(self.into), |
| 52 | + "indices_or_sections": serialize(self.indices_or_sections), |
| 53 | + "axis": serialize(self.axis), |
| 54 | + } |
| 55 | + |
| 56 | + def forward(self, data: dict[str, np.ndarray], strict: bool = True, **kwargs) -> dict[str, np.ndarray]: |
| 57 | + # avoid side effects |
| 58 | + data = data.copy() |
| 59 | + |
| 60 | + if strict and self.key not in data: |
| 61 | + raise KeyError(self.key) |
| 62 | + elif self.key not in data: |
| 63 | + # we cannot produce a result, but also don't have to |
| 64 | + return data |
| 65 | + |
| 66 | + splits = np.split(data.pop(self.key), self.indices_or_sections, axis=self.axis) |
| 67 | + |
| 68 | + if len(splits) != len(self.into): |
| 69 | + raise ValueError(f"Requested {len(self.into)} splits, but produced {len(splits)}.") |
| 70 | + |
| 71 | + for key, split in zip(self.into, splits): |
| 72 | + data[key] = split |
| 73 | + |
| 74 | + return data |
| 75 | + |
| 76 | + def inverse(self, data: dict[str, np.ndarray], strict: bool = False, **kwargs) -> dict[str, np.ndarray]: |
| 77 | + # avoid side effects |
| 78 | + data = data.copy() |
| 79 | + |
| 80 | + required_keys = set(self.into) |
| 81 | + available_keys = set(data.keys()) |
| 82 | + common_keys = available_keys & required_keys |
| 83 | + missing_keys = required_keys - available_keys |
| 84 | + |
| 85 | + if strict and missing_keys: |
| 86 | + # invalid call |
| 87 | + raise KeyError(f"Missing keys: {missing_keys!r}") |
| 88 | + elif missing_keys: |
| 89 | + # we cannot produce a result, but should still remove the keys |
| 90 | + for key in common_keys: |
| 91 | + data.pop(key) |
| 92 | + |
| 93 | + return data |
| 94 | + |
| 95 | + # remove each part |
| 96 | + splits = [data.pop(key) for key in self.into] |
| 97 | + |
| 98 | + # concatenate them all |
| 99 | + result = np.concatenate(splits, axis=self.axis) |
| 100 | + |
| 101 | + # store the result |
| 102 | + data[self.key] = result |
| 103 | + |
| 104 | + return data |
| 105 | + |
| 106 | + def extra_repr(self) -> str: |
| 107 | + result = "[" + ", ".join(map(repr, self.key)) + "] -> " + repr(self.into) |
| 108 | + |
| 109 | + if self.axis != -1: |
| 110 | + result += f", axis={self.axis}" |
| 111 | + |
| 112 | + return result |
0 commit comments