base — Utilities#
This module provides generic helpers and utilities for the hexsample package.
AbstractRandomGenerator is an abstract base class for
any class that implements random number generation functionality. It defines
a single abstract method, rvs()
that must be implemented by any subclass. All the spectrum and beam objects in
the source module use this interface.
AbstractPlottable is an abstract base class for any class
that implements plotting functionality. It defines a single abstract method
render() that must be implemented by any
subclass and is called in the plot()
method to handle matplotlib axes transparently. All the spectrum objects in
the source module use this interface.
TypeProxy is a concrete class that acts as a dispatcher
for different types of objects. This is used when we have to instantiate different
(but related) classes based on user input, as in spectra and beams.
This is best illustrated in the the following example, which is taken from the
source module.
BeamProxy = TypeProxy("beam") # pylint: disable=invalid-name
BeamProxy.register("point", PointBeam)
BeamProxy.register("disk", DiskBeam)
BeamProxy.register("gaussian", GaussianBeam, default=True)
BeamProxy.register("triangular", TriangularBeam)
BeamProxy.register("hexagonal", HexagonalBeam)
The BeamProxy object can be used to instantiate different beam types based on
user input through keyword arguments, using the
hexsample.base.TypeProxy.from_filtered_kwargs() method, e.g.
from hexsample.source import BeamProxy
# Instantiate a Gaussian beam
beam = BeamProxy.from_filtered_kwargs(beam="gaussian", sigma=1.0)
Warning
The TypeProxy mechanism is fragile in that, by definition, is not protected
against errors (e.g., typos) in the keyword arguments. It is mainly intended
to be used in conjunction with the command-line interface of the package, in
which case everything is fine, as all basic sanity checks are performed on the
cli side, but you should always prefer explicit instantiation of the classes
when using the package programmatically.
In addition, the TypeProxy class provides methods to list the registered types
(hexsample.base.TypeProxy.choices()) and to get the default type
(hexsample.base.TypeProxy.default()), which are handy for the
implementation of the command-line interface.
Module documentation#
Base classes and functions shared across modules.
- class hexsample.base.AbstractRandomGenerator[source]#
Abstract base class for random number generators.
- abstractmethod rvs(size: int = 1) Tuple[ndarray, ...][source]#
Generate random variates.
Arguments#
- sizeint
The number of random variates to be generated.
Returns#
- values(tuple of) np.ndarray of shape size
The actual random variates.
- _abc_impl = <_abc._abc_data object>#
- class hexsample.base.AbstractPlottable[source]#
Abstract base class for plottable objects.
- abstractmethod render(axes: Axes, **kwargs) None[source]#
Render the object on the given axes.
Arguments#
- axesmatplotlib.axes.Axes
The axes to plot on.
- kwargskeyword arguments
Additional keyword arguments passed to the rendering method. Note that the specifics depends on how _render() is implemented, and which type of matplotlib object the plottable is representing.
- plot(axes: Axes = None, **kwargs) Axes[source]#
Plot the object on the given axes (or on the current axes if none is passed as an argument).
Arguments#
- axesmatplotlib.axes.Axes, optional
The axes to plot on. If None, the current axes are used.
- kwargskeyword arguments
Additional keyword arguments passed to the _render() method. Note that the specifics depends on how _render() is implemented, and which type of matplotlib object the plottable is representing.
Returns#
- matplotlib.axes.Axes
The axes the object has been plotted on.
- _abc_impl = <_abc._abc_data object>#
- class hexsample.base.TypeProxy(key: str)[source]#
Base class for type proxy classes.
This class implements a simple type proxy mechanism, allowing to register different dataclass types under different names, and to create concrete objects of the desired type based on keyword arguments.
Warning
Only dataclass types can be registered. This is intrumental for the inner workings of the type proxy mechanism, since we rely on the dataclass fields to filter the keyword arguments when creating concrete objects.
Arguments#
- keystr
The name of the keyword argument that will be used to select the desired type when creating objects from keyword arguments.
- _proxy_dict: Dict[str, Type[Any]]#
- key() str[source]#
Return the key used to select the desired type.
This is useful, e.g., for argparse argument names.
Returns#
- str
The key used to select the desired type.
- register(name: str, cls: type, default: bool = False) None[source]#
Register a new dataclass in the proxy dictionary.
Arguments#
- namestr
The name of the type to register.
- clsclass
The dataclass type to register.
- choices() Tuple[str, ...][source]#
Return the available choices.
This is useful for argparse choices, for instance.
Returns#
- tuple of str
The available choices.
- default() str[source]#
Return the default choice.
This is useful for argparse default values, for instance.
Returns#
- str
The default choice.
- _cls(name: str) Type[Any][source]#
Return the type corresponding to the given name.
Arguments#
- namestr
The name of the desired type.
Returns#
- class
The class of the desired type.
- create(name: str, **kwargs) Any[source]#
Create an object of the desired type.
Arguments#
- namestr
The name of the desired type.
- kwargskeyword arguments
The keyword arguments to pass to the constructor.
Returns#
- object
The created object.
- static filter_dataclass_kwargs(cls_: type, kwargs: dict) dict[source]#
Filter keyword arguments to keep only those defined in the dataclass.
Arguments#
- clsclass
The dataclass type.
- kwargsdict
The keyword arguments to filter.
Returns#
- dict
The filtered keyword arguments.
- from_filtered_kwargs(**kwargs) Any[source]#
Create an object of the desired type based only on keyword arguments.
This is extracting the desired type from the keyword arguments using the configured key, and filtering the keyword arguments to keep only those defined in the target dataclass.
Warning
Use this with caution, as we are silently dropping any keyword argument that is not defined in the target dataclass. This may be fine when the class acts as an interface layer to argparse, but if you use the function in the wild, you might end up having typos in your keyword arguments that go undetected.
Arguments#
- kwargskeyword arguments
The keyword arguments to pass to the constructor.
Returns#
- object
The created object.