Skip to content

Rewrap (with black) to 88 chars instead of 115 #32

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

Merged
merged 2 commits into from
Jun 9, 2023
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 .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ default_language_version:
python: python3
repos:
- repo: https://github.com/ambv/black
rev: stable
rev: 23.3.0
hooks:
- id: black
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.0.0
hooks:
- id: flake8
- repo: https://github.com/kynan/nbstripout
rev: 0.3.9
rev: 0.6.1
hooks:
- id: nbstripout
21 changes: 16 additions & 5 deletions data_prototype/containers.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,9 @@ def query(
coord_transform: _MatplotlibTransform,
size: Tuple[int, int],
) -> Tuple[Dict[str, Any], Union[str, int]]:
return {k: np.random.randn(*d.shape) for k, d in self._desc.items()}, str(uuid.uuid4())
return {k: np.random.randn(*d.shape) for k, d in self._desc.items()}, str(
uuid.uuid4()
)

def describe(self) -> Dict[str, Desc]:
return dict(self._desc)
Expand All @@ -127,9 +129,15 @@ class FuncContainer:
def __init__(
self,
# TODO: is this really the best spelling?!
xfuncs: Optional[Dict[str, Tuple[Tuple[Union[str, int], ...], Callable[[Any], Any]]]] = None,
yfuncs: Optional[Dict[str, Tuple[Tuple[Union[str, int], ...], Callable[[Any], Any]]]] = None,
xyfuncs: Optional[Dict[str, Tuple[Tuple[Union[str, int], ...], Callable[[Any, Any], Any]]]] = None,
xfuncs: Optional[
Dict[str, Tuple[Tuple[Union[str, int], ...], Callable[[Any], Any]]]
] = None,
yfuncs: Optional[
Dict[str, Tuple[Tuple[Union[str, int], ...], Callable[[Any], Any]]]
] = None,
xyfuncs: Optional[
Dict[str, Tuple[Tuple[Union[str, int], ...], Callable[[Any, Any], Any]]]
] = None,
):
"""
A container that wraps several functions. They are split into 3 categories:
Expand Down Expand Up @@ -274,7 +282,10 @@ def query(
coord_transform: _MatplotlibTransform,
size: Tuple[int, int],
) -> Tuple[Dict[str, Any], Union[str, int]]:
return {self._index_name: self._data.index.values, self._col_name: self._data.values}, self._hash_key
return {
self._index_name: self._data.index.values,
self._col_name: self._data.values,
}, self._hash_key

def describe(self) -> Dict[str, Desc]:
return dict(self._desc)
Expand Down
13 changes: 10 additions & 3 deletions data_prototype/conversion_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ def from_nodes(cls, *nodes: ConversionNode, trim_keys=False):
return cls(required, tuple(output), trim_keys, nodes)

def evaluate(self, input: dict[str, Any]) -> dict[str, Any]:
return super().evaluate({k: v for n in self.nodes for k, v in n.evaluate(input).items()})
return super().evaluate(
{k: v for n in self.nodes for k, v in n.evaluate(input).items()}
)


@dataclass
Expand All @@ -66,7 +68,9 @@ def from_mapping(cls, mapping: dict[str, str], trim_keys=False):
return cls(required, tuple(output), trim_keys, mapping)

def evaluate(self, input: dict[str, Any]) -> dict[str, Any]:
return super().evaluate({**input, **{out: input[inp] for (inp, out) in self.mapping.items()}})
return super().evaluate(
{**input, **{out: input[inp] for (inp, out) in self.mapping.items()}}
)


@dataclass
Expand All @@ -91,7 +95,10 @@ def evaluate(self, input: dict[str, Any]) -> dict[str, Any]:
return super().evaluate(
{
**input,
**{k: func(**{p: input[p] for p in sig.parameters}) for (k, (func, sig)) in self._sigs.items()},
**{
k: func(**{p: input[p] for p in sig.parameters})
for (k, (func, sig)) in self._sigs.items()
},
}
)

Expand Down
15 changes: 13 additions & 2 deletions data_prototype/patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,11 @@ def __init__(self, data: DataContainer, converters=None, /, **kwargs):

@_stale_wrapper
def draw(self, renderer):
self._update_wrapped(self._query_and_transform(renderer, xunits=self._xunits, yunits=self._yunits))
self._update_wrapped(
self._query_and_transform(
renderer, xunits=self._xunits, yunits=self._yunits
)
)
return self._wrapped_instance.draw(renderer)

def _update_wrapped(self, data):
Expand All @@ -75,7 +79,14 @@ class RectangleWrapper(PatchWrapper):
)
_xunits = ("x", "width")
_yunits = ("y", "height")
required_keys = PatchWrapper.required_keys | {"x", "y", "width", "height", "angle", "rotation_point"}
required_keys = PatchWrapper.required_keys | {
"x",
"y",
"width",
"height",
"angle",
"rotation_point",
}

def _update_wrapped(self, data):
for k, v in data.items():
Expand Down
4 changes: 3 additions & 1 deletion data_prototype/tests/test_containers.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@

@pytest.fixture
def ac():
return containers.ArrayContainer(a=np.arange(5), b=np.arange(42, dtype=float).reshape(6, 7))
return containers.ArrayContainer(
a=np.arange(5), b=np.arange(42, dtype=float).reshape(6, 7)
)


def _verify_describe(container):
Expand Down
69 changes: 55 additions & 14 deletions data_prototype/wrappers.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@
from matplotlib.patches import StepPatch as _StepPatch
from matplotlib.text import Text as _Text
import matplotlib.transforms as mtransforms
from matplotlib.collections import LineCollection as _LineCollection, PathCollection as _PathCollection
from matplotlib.collections import (
LineCollection as _LineCollection,
PathCollection as _PathCollection,
)
from matplotlib.artist import Artist as _Artist

from data_prototype.containers import DataContainer, _MatplotlibTransform
Expand Down Expand Up @@ -60,7 +63,9 @@ def identity(**kwargs):
(_,) = kwargs.values()
return _

identity.__signature__ = inspect.Signature([inspect.Parameter(k, inspect.Parameter.POSITIONAL_OR_KEYWORD)])
identity.__signature__ = inspect.Signature(
[inspect.Parameter(k, inspect.Parameter.POSITIONAL_OR_KEYWORD)]
)
return identity


Expand Down Expand Up @@ -116,7 +121,9 @@ def draw(self, renderer):
def _update_wrapped(self, data):
raise NotImplementedError

def _query_and_transform(self, renderer, *, xunits: List[str], yunits: List[str]) -> Dict[str, Any]:
def _query_and_transform(
self, renderer, *, xunits: List[str], yunits: List[str]
) -> Dict[str, Any]:
"""
Helper to centralize the data querying and python-side transforms

Expand Down Expand Up @@ -152,7 +159,9 @@ def _query_and_transform(self, renderer, *, xunits: List[str], yunits: List[str]
self._cache[cache_key] = transformed_data
return transformed_data

def __init__(self, data, converters: ConversionNode | list[ConversionNode] | None, **kwargs):
def __init__(
self, data, converters: ConversionNode | list[ConversionNode] | None, **kwargs
):
super().__init__(**kwargs)
self.data = data
self._cache = LFUCache(64)
Expand Down Expand Up @@ -180,23 +189,43 @@ def __getattr__(self, key):
return getattr(self._wrapped_instance, key)

def __setattr__(self, key, value):
if key in ("_wrapped_instance", "data", "_cache", "_converters", "stale", "_sigs"):
if key in (
"_wrapped_instance",
"data",
"_cache",
"_converters",
"stale",
"_sigs",
):
super().__setattr__(key, value)
elif hasattr(self, "_wrapped_instance") and hasattr(self._wrapped_instance, key):
elif hasattr(self, "_wrapped_instance") and hasattr(
self._wrapped_instance, key
):
setattr(self._wrapped_instance, key, value)
else:
super().__setattr__(key, value)


class LineWrapper(ProxyWrapper):
_wrapped_class = _Line2D
_privtized_methods = ("set_xdata", "set_ydata", "set_data", "get_xdata", "get_ydata", "get_data")
_privtized_methods = (
"set_xdata",
"set_ydata",
"set_data",
"get_xdata",
"get_ydata",
"get_data",
)
required_keys = {"x", "y"}

def __init__(self, data: DataContainer, converters=None, /, **kwargs):
super().__init__(data, converters)
self._wrapped_instance = self._wrapped_class(np.array([]), np.array([]), **kwargs)
self._converters.insert(-1, RenameConversionNode.from_mapping({"x": "xdata", "y": "ydata"}))
self._wrapped_instance = self._wrapped_class(
np.array([]), np.array([]), **kwargs
)
self._converters.insert(
-1, RenameConversionNode.from_mapping({"x": "xdata", "y": "ydata"})
)
setters = [f[4:] for f in dir(self._wrapped_class) if f.startswith("set_")]
self._converters[-1] = LimitKeysConversionNode.from_keys(setters)

Expand Down Expand Up @@ -252,7 +281,9 @@ class ImageWrapper(ProxyWrapper):
_wrapped_class = _AxesImage
required_keys = {"xextent", "yextent", "image"}

def __init__(self, data: DataContainer, converters=None, /, cmap=None, norm=None, **kwargs):
def __init__(
self, data: DataContainer, converters=None, /, cmap=None, norm=None, **kwargs
):
converters = converters or []
if cmap is not None or norm is not None:
if converters is not None and "image" in converters:
Expand All @@ -261,7 +292,11 @@ def __init__(self, data: DataContainer, converters=None, /, cmap=None, norm=None
cmap = mpl.colormaps["viridis"]
if norm is None:
raise ValueError("not sure how to do autoscaling yet")
converters.append(FunctionConversionNode.from_funcs({"image": lambda image: cmap(norm(image))}))
converters.append(
FunctionConversionNode.from_funcs(
{"image": lambda image: cmap(norm(image))}
)
)
super().__init__(data, converters)
kwargs.setdefault("origin", "lower")
self._wrapped_instance = self._wrapped_class(None, **kwargs)
Expand Down Expand Up @@ -341,7 +376,9 @@ def __setattr__(self, key, value):
super().__setattr__(key, value)
if hasattr(self, "_wrapped_instances"):
# We can end up with out wrapped instance as part of init
children_have_attrs = [hasattr(c, key) for c in self._wrapped_instances.values()]
children_have_attrs = [
hasattr(c, key) for c in self._wrapped_instances.values()
]
if any(children_have_attrs):
if not all(children_have_attrs):
raise Exception("mixed attributes 😱")
Expand All @@ -356,7 +393,9 @@ def get_children(self):

class ErrorbarWrapper(MultiProxyWrapper):
required_keys = {"x", "y"}
expected_keys = {f"{axis}{dirc}" for axis in ["x", "y"] for dirc in ["upper", "lower"]}
expected_keys = {
f"{axis}{dirc}" for axis in ["x", "y"] for dirc in ["upper", "lower"]
}

def __init__(self, data: DataContainer, converters=None, /, **kwargs):
super().__init__(data, converters)
Expand Down Expand Up @@ -387,7 +426,9 @@ def __init__(self, data: DataContainer, converters=None, /, **kwargs):
def draw(self, renderer):
self._update_wrapped(
self._query_and_transform(
renderer, xunits=["x", "xupper", "xlower"], yunits=["y", "yupper", "ylower"]
renderer,
xunits=["x", "xupper", "xlower"],
yunits=["y", "yupper", "ylower"],
),
)
for k, v in self._wrapped_instances.items():
Expand Down
18 changes: 15 additions & 3 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,11 @@ def matplotlib_reduced_latex_scraper(block, block_vars, gallery_conf, **kwargs):
#
html_logo = "_static/logo2.svg"
html_theme_options = {
"logo": {"link": "index", "image_light": "images/logo2.svg", "image_dark": "images/logo_dark.svg"},
"logo": {
"link": "index",
"image_light": "images/logo2.svg",
"image_dark": "images/logo_dark.svg",
},
}

# Add any paths that contain custom static files (such as style sheets) here,
Expand Down Expand Up @@ -214,15 +218,23 @@ def matplotlib_reduced_latex_scraper(block, block_vars, gallery_conf, **kwargs):
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, "data_prototype.tex", "data_prototype Documentation", "Contributors", "manual"),
(
master_doc,
"data_prototype.tex",
"data_prototype Documentation",
"Contributors",
"manual",
),
]


# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(master_doc, "data_prototype", "data_prototype Documentation", [author], 1)]
man_pages = [
(master_doc, "data_prototype", "data_prototype Documentation", [author], 1)
]


# -- Options for Texinfo output -------------------------------------------
Expand Down
5 changes: 4 additions & 1 deletion examples/2Dfunc.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@
xyfuncs={
"xextent": ((2,), lambda x, y: [x[0], x[-1]]),
"yextent": ((2,), lambda x, y: [y[0], y[-1]]),
"image": (("N", "M"), lambda x, y: np.sin(x).reshape(1, -1) * np.cos(y).reshape(-1, 1)),
"image": (
("N", "M"),
lambda x, y: np.sin(x).reshape(1, -1) * np.cos(y).reshape(-1, 1),
),
},
)
norm = Normalize(vmin=-1, vmax=1)
Expand Down
4 changes: 3 additions & 1 deletion examples/data_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@

th = np.linspace(0, 4 * np.pi, 256)

dc1 = DataFrameContainer(pd.DataFrame({"x": th, "y": np.cos(th)}), index_name=None, col_names=lambda n: n)
dc1 = DataFrameContainer(
pd.DataFrame({"x": th, "y": np.cos(th)}), index_name=None, col_names=lambda n: n
)

df = pd.DataFrame(
{
Expand Down
4 changes: 3 additions & 1 deletion examples/errorbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
xupper = x + 0.5
xlower = x - 0.5

ac = ArrayContainer(x=x, y=y, yupper=yupper, ylower=ylower, xlower=xlower, xupper=xupper)
ac = ArrayContainer(
x=x, y=y, yupper=yupper, ylower=ylower, xlower=xlower, xupper=xupper
)


fig, ax = plt.subplots()
Expand Down
4 changes: 3 additions & 1 deletion examples/hist.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
from data_prototype.wrappers import StepWrapper
from data_prototype.containers import HistContainer

hc = HistContainer(np.concatenate([np.random.randn(5000), 0.1 * np.random.randn(500) + 5]), 25)
hc = HistContainer(
np.concatenate([np.random.randn(5000), 0.1 * np.random.randn(500) + 5]), 25
)


fig, (ax1, ax2) = plt.subplots(1, 2, layout="constrained")
Expand Down
8 changes: 6 additions & 2 deletions examples/lissajous.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,19 @@ def query(
) -> Tuple[Dict[str, Any], Union[str, int]]:
def next_time():
cur_time = time.time()
cur_time = np.array([cur_time, cur_time - 0.1, cur_time - 0.2, cur_time - 0.3])
cur_time = np.array(
[cur_time, cur_time - 0.1, cur_time - 0.2, cur_time - 0.3]
)

phase = 15 * np.pi * (self.scale * cur_time % 60) / 150
marker_obj = mmarkers.MarkerStyle("o")
return {
"x": np.cos(5 * phase),
"y": np.sin(3 * phase),
"sizes": np.array([256]),
"paths": [marker_obj.get_path().transformed(marker_obj.get_transform())],
"paths": [
marker_obj.get_path().transformed(marker_obj.get_transform())
],
"edgecolors": "k",
"facecolors": ["#4682b4ff", "#82b446aa", "#46b48288", "#8246b433"],
"time": cur_time[0],
Expand Down
Loading