|
| 1 | +# Copyright 2024 The PyMC Labs Developers |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +"""Deserialize into a PyMC-Marketing object. |
| 15 | +
|
| 16 | +This is a two step process: |
| 17 | +
|
| 18 | +1. Determine if the data is of the correct type. |
| 19 | +2. Deserialize the data into a python object for PyMC-Marketing. |
| 20 | +
|
| 21 | +This is used to deserialize JSON data into PyMC-Marketing objects |
| 22 | +throughout the package. |
| 23 | +
|
| 24 | +Examples |
| 25 | +-------- |
| 26 | +Make use of the already registered PyMC-Marketing deserializers: |
| 27 | +
|
| 28 | +.. code-block:: python |
| 29 | +
|
| 30 | + from pymc_marketing.deserialize import deserialize |
| 31 | +
|
| 32 | + prior_class_data = { |
| 33 | + "dist": "Normal", |
| 34 | + "kwargs": {"mu": 0, "sigma": 1} |
| 35 | + } |
| 36 | + prior = deserialize(prior_class_data) |
| 37 | + # Prior("Normal", mu=0, sigma=1) |
| 38 | +
|
| 39 | +Register custom class deserialization: |
| 40 | +
|
| 41 | +.. code-block:: python |
| 42 | +
|
| 43 | + from pymc_marketing.deserialize import register_deserialization |
| 44 | +
|
| 45 | + class MyClass: |
| 46 | + def __init__(self, value: int): |
| 47 | + self.value = value |
| 48 | +
|
| 49 | + def to_dict(self) -> dict: |
| 50 | + # Example of what the to_dict method might look like. |
| 51 | + return {"value": self.value} |
| 52 | +
|
| 53 | + register_deserialization( |
| 54 | + is_type=lambda data: data.keys() == {"value"} and isinstance(data["value"], int), |
| 55 | + deserialize=lambda data: MyClass(value=data["value"]), |
| 56 | + ) |
| 57 | +
|
| 58 | +Deserialize data into that custom class: |
| 59 | +
|
| 60 | +.. code-block:: python |
| 61 | +
|
| 62 | + from pymc_marketing.deserialize import deserialize |
| 63 | +
|
| 64 | + data = {"value": 42} |
| 65 | + obj = deserialize(data) |
| 66 | + assert isinstance(obj, MyClass) |
| 67 | +
|
| 68 | +
|
| 69 | +""" |
| 70 | + |
| 71 | +from collections.abc import Callable |
| 72 | +from dataclasses import dataclass |
| 73 | +from typing import Any |
| 74 | + |
| 75 | +IsType = Callable[[Any], bool] |
| 76 | +Deserialize = Callable[[Any], Any] |
| 77 | + |
| 78 | + |
| 79 | +@dataclass |
| 80 | +class Deserializer: |
| 81 | + """Object to store information required for deserialization. |
| 82 | +
|
| 83 | + All deserializers should be stored via the :func:`register_deserialization` function |
| 84 | + instead of creating this object directly. |
| 85 | +
|
| 86 | + Attributes |
| 87 | + ---------- |
| 88 | + is_type : IsType |
| 89 | + Function to determine if the data is of the correct type. |
| 90 | + deserialize : Deserialize |
| 91 | + Function to deserialize the data. |
| 92 | +
|
| 93 | + Examples |
| 94 | + -------- |
| 95 | + .. code-block:: python |
| 96 | +
|
| 97 | + from typing import Any |
| 98 | +
|
| 99 | + class MyClass: |
| 100 | + def __init__(self, value: int): |
| 101 | + self.value = value |
| 102 | +
|
| 103 | + from pymc_marketing.deserialize import Deserializer |
| 104 | +
|
| 105 | + def is_type(data: Any) -> bool: |
| 106 | + return data.keys() == {"value"} and isinstance(data["value"], int) |
| 107 | +
|
| 108 | + def deserialize(data: dict) -> MyClass: |
| 109 | + return MyClass(value=data["value"]) |
| 110 | +
|
| 111 | + deserialize_logic = Deserializer(is_type=is_type, deserialize=deserialize) |
| 112 | +
|
| 113 | + """ |
| 114 | + |
| 115 | + is_type: IsType |
| 116 | + deserialize: Deserialize |
| 117 | + |
| 118 | + |
| 119 | +DESERIALIZERS: list[Deserializer] = [] |
| 120 | + |
| 121 | + |
| 122 | +class DeserializableError(Exception): |
| 123 | + """Error raised when data cannot be deserialized.""" |
| 124 | + |
| 125 | + def __init__(self, data: Any): |
| 126 | + self.data = data |
| 127 | + super().__init__( |
| 128 | + f"Couldn't deserialize {data}. Use register_deserialization to add a deserialization mapping." |
| 129 | + ) |
| 130 | + |
| 131 | + |
| 132 | +def deserialize(data: Any) -> Any: |
| 133 | + """Deserialize a dictionary into a Python object. |
| 134 | +
|
| 135 | + Use the :func:`register_deserialization` function to add custom deserializations. |
| 136 | +
|
| 137 | + Deserialization is a two step process due to the dynamic nature of the data: |
| 138 | +
|
| 139 | + 1. Determine if the data is of the correct type. |
| 140 | + 2. Deserialize the data into a Python object. |
| 141 | +
|
| 142 | + Each registered deserialization is checked in order until one is found that can |
| 143 | + deserialize the data. If no deserialization is found, a :class:`DeserializableError` is raised. |
| 144 | +
|
| 145 | + A :class:`DeserializableError` is raised when the data fails to be deserialized |
| 146 | + by any of the registered deserializers. |
| 147 | +
|
| 148 | + Parameters |
| 149 | + ---------- |
| 150 | + data : Any |
| 151 | + The data to deserialize. |
| 152 | +
|
| 153 | + Returns |
| 154 | + ------- |
| 155 | + Any |
| 156 | + The deserialized object. |
| 157 | +
|
| 158 | + Raises |
| 159 | + ------ |
| 160 | + DeserializableError |
| 161 | + Raised when the data doesn't match any registered deserializations |
| 162 | + or fails to be deserialized. |
| 163 | +
|
| 164 | + Examples |
| 165 | + -------- |
| 166 | + Deserialize a :class:`pymc_marketing.prior.Prior` object: |
| 167 | +
|
| 168 | + .. code-block:: python |
| 169 | +
|
| 170 | + from pymc_marketing.deserialize import deserialize |
| 171 | +
|
| 172 | + data = {"dist": "Normal", "kwargs": {"mu": 0, "sigma": 1}} |
| 173 | + prior = deserialize(data) |
| 174 | + # Prior("Normal", mu=0, sigma=1) |
| 175 | +
|
| 176 | + """ |
| 177 | + for mapping in DESERIALIZERS: |
| 178 | + try: |
| 179 | + is_type = mapping.is_type(data) |
| 180 | + except Exception: |
| 181 | + is_type = False |
| 182 | + |
| 183 | + if not is_type: |
| 184 | + continue |
| 185 | + |
| 186 | + try: |
| 187 | + return mapping.deserialize(data) |
| 188 | + except Exception as e: |
| 189 | + raise DeserializableError(data) from e |
| 190 | + else: |
| 191 | + raise DeserializableError(data) |
| 192 | + |
| 193 | + |
| 194 | +def register_deserialization(is_type: IsType, deserialize: Deserialize) -> None: |
| 195 | + """Register an arbitrary deserialization. |
| 196 | +
|
| 197 | + Use the :func:`deserialize` function to then deserialize data using all registered |
| 198 | + deserialize functions. |
| 199 | +
|
| 200 | + Classes from PyMC-Marketing have their deserialization mappings registered |
| 201 | + automatically. However, custom classes will need to be registered manually |
| 202 | + using this function before they can be deserialized. |
| 203 | +
|
| 204 | + Parameters |
| 205 | + ---------- |
| 206 | + is_type : Callable[[Any], bool] |
| 207 | + Function to determine if the data is of the correct type. |
| 208 | + deserialize : Callable[[dict], Any] |
| 209 | + Function to deserialize the data of that type. |
| 210 | +
|
| 211 | + Examples |
| 212 | + -------- |
| 213 | + Register a custom class deserialization: |
| 214 | +
|
| 215 | + .. code-block:: python |
| 216 | +
|
| 217 | + from pymc_marketing.deserialize import register_deserialization |
| 218 | +
|
| 219 | + class MyClass: |
| 220 | + def __init__(self, value: int): |
| 221 | + self.value = value |
| 222 | +
|
| 223 | + def to_dict(self) -> dict: |
| 224 | + # Example of what the to_dict method might look like. |
| 225 | + return {"value": self.value} |
| 226 | +
|
| 227 | + register_deserialization( |
| 228 | + is_type=lambda data: data.keys() == {"value"} and isinstance(data["value"], int), |
| 229 | + deserialize=lambda data: MyClass(value=data["value"]), |
| 230 | + ) |
| 231 | +
|
| 232 | + Use that custom class deserialization: |
| 233 | +
|
| 234 | + .. code-block:: python |
| 235 | +
|
| 236 | + from pymc_marketing.deserialize import deserialize |
| 237 | +
|
| 238 | + data = {"value": 42} |
| 239 | + obj = deserialize(data) |
| 240 | + assert isinstance(obj, MyClass) |
| 241 | +
|
| 242 | + """ |
| 243 | + mapping = Deserializer(is_type=is_type, deserialize=deserialize) |
| 244 | + DESERIALIZERS.append(mapping) |
0 commit comments