Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rename DataAdapter -> Adapter #222

Merged
merged 2 commits into from
Oct 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions bayesflow/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from . import (
approximators,
benchmarks,
data_adapters,
adapters,
datasets,
diagnostics,
distributions,
Expand All @@ -11,7 +11,7 @@
)

from .approximators import ContinuousApproximator
from .data_adapters import DataAdapter
from .adapters import Adapter
from .datasets import OfflineDataset, OnlineDataset, DiskDataset
from .simulators import make_simulator

Expand Down
2 changes: 2 additions & 0 deletions bayesflow/adapters/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from . import transforms
from .adapter import Adapter
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,16 @@
)


@serializable(package="bayesflow.data_adapters")
class DataAdapter:
@serializable(package="bayesflow.adapters")
class Adapter:
def __init__(self, transforms: Sequence[Transform] | None = None):
if transforms is None:
transforms = []

self.transforms = transforms

@classmethod
def from_config(cls, config: dict, custom_objects=None) -> "DataAdapter":
def from_config(cls, config: dict, custom_objects=None) -> "Adapter":
return cls(transforms=deserialize(config["transforms"], custom_objects))

def get_config(self) -> dict:
Expand Down Expand Up @@ -64,7 +64,7 @@ def __call__(self, data: dict[str, any], *, inverse: bool = False, **kwargs) ->
return self.forward(data, **kwargs)

def __repr__(self):
return f"DataAdapter({' -> '.join(map(repr, self.transforms))})"
return f"Adapter([{' -> '.join(map(repr, self.transforms))}])"

def add_transform(self, transform: Transform):
self.transforms.append(transform)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class Broadcast(ElementwiseTransform):
>>> bc(np.array(5), batch_size=3).shape
(3,)

It is recommended to precede this transform with a :class:`bayesflow.data_adapters.transforms.ToArray` transform.
It is recommended to precede this transform with a :class:`bayesflow.adapters.transforms.ToArray` transform.
"""

def __init__(self, *, expand_scalars: bool = True):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from .transform import Transform


@serializable(package="bayesflow.data_adapters")
@serializable(package="bayesflow.adapters")
class Concatenate(Transform):
"""Concatenate multiple arrays into a new key."""

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from .elementwise_transform import ElementwiseTransform


@serializable(package="bayesflow.data_adapters")
@serializable(package="bayesflow.adapters")
class Constrain(ElementwiseTransform):
def __init__(
self, *, lower: int | float | np.ndarray = None, upper: int | float | np.ndarray = None, method: str = "default"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from .elementwise_transform import ElementwiseTransform


@serializable(package="bayesflow.data_adapters")
@serializable(package="bayesflow.adapters")
class ConvertDType(ElementwiseTransform):
def __init__(self, from_dtype: str, to_dtype: str):
super().__init__()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from .transform import Transform


@serializable(package="bayesflow.data_adapters")
@serializable(package="bayesflow.adapters")
class Drop(Transform):
def __init__(self, keys: Sequence[str]):
self.keys = keys
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import numpy as np


@serializable(package="bayesflow.data_adapters")
@serializable(package="bayesflow.adapters")
class ElementwiseTransform:
def __call__(self, data: np.ndarray, inverse: bool = False, **kwargs) -> np.ndarray:
if inverse:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def __call__(self, key: str, value: np.ndarray, inverse: bool) -> bool:
raise NotImplementedError


@serializable(package="bayesflow.data_adapters")
@serializable(package="bayesflow.adapters")
class FilterTransform(Transform):
def __init__(
self,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from .transform import Transform


@serializable(package="bayesflow.data_adapters")
@serializable(package="bayesflow.adapters")
class Keep(Transform):
def __init__(self, keys: Sequence[str]):
self.keys = keys
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from .elementwise_transform import ElementwiseTransform


@serializable(package="bayesflow.data_adapters")
@serializable(package="bayesflow.adapters")
class LambdaTransform(ElementwiseTransform):
"""
Transforms a parameter using a pair of forward and inverse functions.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from .transform import Transform


@serializable(package="bayesflow.data_adapters")
@serializable(package="bayesflow.adapters")
class MapTransform(Transform):
"""
Implements a transform that applies a set of elementwise transforms
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from .elementwise_transform import ElementwiseTransform


@serializable(package="bayesflow.data_adapters")
@serializable(package="bayesflow.adapters")
class OneHot(ElementwiseTransform):
def __init__(self, num_classes: int):
super().__init__()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from .transform import Transform


@serializable(package="bayesflow.data_adapters")
@serializable(package="bayesflow.adapters")
class Rename(Transform):
def __init__(self, from_key: str, to_key: str):
super().__init__()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from .elementwise_transform import ElementwiseTransform


@serializable(package="bayesflow.data_adapters")
@serializable(package="bayesflow.adapters")
class Standardize(ElementwiseTransform):
def __init__(self, mean: int | float | np.ndarray = None, std: int | float | np.ndarray = None, axis: int = None):
super().__init__()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from .elementwise_transform import ElementwiseTransform


@serializable(package="bayesflow.data_adapters")
@serializable(package="bayesflow.adapters")
class ToArray(ElementwiseTransform):
def __init__(self):
super().__init__()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import numpy as np


@serializable(package="bayesflow.data_adapters")
@serializable(package="bayesflow.adapters")
class Transform:
def __call__(self, data: dict[str, np.ndarray], *, inverse: bool = False, **kwargs) -> dict[str, np.ndarray]:
if inverse:
Expand Down
12 changes: 6 additions & 6 deletions bayesflow/approximators/approximator.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import keras
import multiprocessing as mp

from bayesflow.data_adapters import DataAdapter
from bayesflow.adapters import Adapter
from bayesflow.datasets import OnlineDataset
from bayesflow.simulators import Simulator
from bayesflow.utils import find_batch_size, filter_kwargs, logging
Expand All @@ -15,7 +15,7 @@ def build(self, data_shapes: any) -> None:
self.build_from_data(mock_data)

@classmethod
def build_data_adapter(cls, **kwargs) -> DataAdapter:
def build_adapter(cls, **kwargs) -> Adapter:
# implemented by each respective architecture
raise NotImplementedError

Expand All @@ -29,7 +29,7 @@ def build_dataset(
*,
batch_size: int = "auto",
num_batches: int,
data_adapter: DataAdapter = "auto",
adapter: Adapter = "auto",
memory_budget: str | int = "auto",
simulator: Simulator,
workers: int = "auto",
Expand All @@ -41,8 +41,8 @@ def build_dataset(
batch_size = find_batch_size(memory_budget=memory_budget, sample=simulator.sample((1,)))
logging.info(f"Using a batch size of {batch_size}.")

if data_adapter == "auto":
data_adapter = cls.build_data_adapter(**filter_kwargs(kwargs, cls.build_data_adapter))
if adapter == "auto":
adapter = cls.build_adapter(**filter_kwargs(kwargs, cls.build_adapter))

if workers == "auto":
workers = mp.cpu_count()
Expand All @@ -54,7 +54,7 @@ def build_dataset(
simulator=simulator,
batch_size=batch_size,
num_batches=num_batches,
data_adapter=data_adapter,
adapter=adapter,
workers=workers,
use_multiprocessing=use_multiprocessing,
max_queue_size=max_queue_size,
Expand Down
38 changes: 17 additions & 21 deletions bayesflow/approximators/continuous_approximator.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
serialize_keras_object as serialize,
)

from bayesflow.data_adapters import DataAdapter
from bayesflow.adapters import Adapter
from bayesflow.networks import InferenceNetwork, SummaryNetwork
from bayesflow.types import Tensor
from bayesflow.utils import logging, expand_left_to
Expand All @@ -25,43 +25,39 @@ class ContinuousApproximator(Approximator):
def __init__(
self,
*,
data_adapter: DataAdapter,
adapter: Adapter,
inference_network: InferenceNetwork,
summary_network: SummaryNetwork = None,
**kwargs,
):
super().__init__(**kwargs)
self.data_adapter = data_adapter
self.adapter = adapter
self.inference_network = inference_network
self.summary_network = summary_network

@classmethod
def build_data_adapter(
def build_adapter(
cls,
inference_variables: Sequence[str],
inference_conditions: Sequence[str] = None,
summary_variables: Sequence[str] = None,
) -> DataAdapter:
data_adapter = (
DataAdapter()
) -> Adapter:
adapter = (
Adapter()
.to_array()
.convert_dtype("float64", "float32")
.concatenate(inference_variables, into="inference_variables")
)

if inference_conditions is not None:
data_adapter = data_adapter.concatenate(inference_conditions, into="inference_conditions")
adapter = adapter.concatenate(inference_conditions, into="inference_conditions")

if summary_variables is not None:
data_adapter = data_adapter.as_set(summary_variables).concatenate(
summary_variables, into="summary_variables"
)
adapter = adapter.as_set(summary_variables).concatenate(summary_variables, into="summary_variables")

data_adapter = data_adapter.keep(
["inference_variables", "inference_conditions", "summary_variables"]
).standardize()
adapter = adapter.keep(["inference_variables", "inference_conditions", "summary_variables"]).standardize()

return data_adapter
return adapter

def compile(
self,
Expand Down Expand Up @@ -120,11 +116,11 @@ def compute_metrics(
return metrics

def fit(self, *args, **kwargs):
return super().fit(*args, **kwargs, data_adapter=self.data_adapter)
return super().fit(*args, **kwargs, adapter=self.adapter)

@classmethod
def from_config(cls, config, custom_objects=None):
config["data_adapter"] = deserialize(config["data_adapter"], custom_objects=custom_objects)
config["adapter"] = deserialize(config["adapter"], custom_objects=custom_objects)
config["inference_network"] = deserialize(config["inference_network"], custom_objects=custom_objects)
config["summary_network"] = deserialize(config["summary_network"], custom_objects=custom_objects)

Expand All @@ -133,7 +129,7 @@ def from_config(cls, config, custom_objects=None):
def get_config(self):
base_config = super().get_config()
config = {
"data_adapter": serialize(self.data_adapter),
"adapter": serialize(self.adapter),
"inference_network": serialize(self.inference_network),
"summary_network": serialize(self.summary_network),
}
Expand All @@ -148,11 +144,11 @@ def sample(
conditions: dict[str, np.ndarray],
**kwargs,
) -> dict[str, np.ndarray]:
conditions = self.data_adapter(conditions, strict=False, batch_size=batch_size, **kwargs)
conditions = self.adapter(conditions, strict=False, batch_size=batch_size, **kwargs)
conditions = keras.tree.map_structure(keras.ops.convert_to_tensor, conditions)
conditions = {"inference_variables": self._sample(num_samples=num_samples, batch_size=batch_size, **conditions)}
conditions = keras.tree.map_structure(keras.ops.convert_to_numpy, conditions)
conditions = self.data_adapter(conditions, inverse=True, strict=False, **kwargs)
conditions = self.adapter(conditions, inverse=True, strict=False, **kwargs)

return conditions

Expand Down Expand Up @@ -191,7 +187,7 @@ def _sample(
return self.inference_network.sample(batch_shape, conditions=inference_conditions)

def log_prob(self, data: dict[str, np.ndarray], *, batch_size: int) -> np.ndarray:
data = self.data_adapter(data, strict=False, batch_size=batch_size)
data = self.adapter(data, strict=False, batch_size=batch_size)
data = keras.tree.map_structure(keras.ops.convert_to_tensor, data)
log_prob = self._log_prob(**data)
log_prob = keras.ops.convert_to_numpy(log_prob)
Expand Down
Loading
Loading