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

Initial implementation of text #44

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
17 changes: 17 additions & 0 deletions data_prototype/artist.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from bisect import insort
from collections import namedtuple
from typing import Sequence

import numpy as np
Expand Down Expand Up @@ -234,6 +235,7 @@ def __init__(self, axes):
self.figure = None
self._clippath = None
self.zorder = 2
self.sticky_edges = namedtuple("Sticky", ["x", "y"])([], [])

@property
def axes(self):
Expand All @@ -248,7 +250,10 @@ def axes(self, ax):
return

desc: Desc = Desc(("N",), coordinates="data")
desc_scal: Desc = Desc((), coordinates="data")
xy: dict[str, Desc] = {"x": desc, "y": desc}
xy_scal: dict[str, Desc] = {"x": desc_scal, "y": desc_scal}

self._graph = Graph(
[
TransformEdge(
Expand All @@ -263,6 +268,18 @@ def axes(self, ax):
desc_like(xy, coordinates="display"),
transform=self._axes.transAxes,
),
TransformEdge(
"data_scal",
xy_scal,
desc_like(xy_scal, coordinates="axes"),
transform=self._axes.transData - self._axes.transAxes,
),
TransformEdge(
"axes_scal",
desc_like(xy_scal, coordinates="axes"),
desc_like(xy_scal, coordinates="display"),
transform=self._axes.transAxes,
),
FuncEdge.from_func(
"xunits",
lambda: self._axes.xaxis.units,
Expand Down
30 changes: 30 additions & 0 deletions data_prototype/axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@


import matplotlib as mpl
from data_prototype.artist import CompatibilityAxes
from matplotlib.axes._axes import Axes as MPLAxes, _preprocess_data
from matplotlib.axes._base import _process_plot_var_args
import matplotlib.collections as mcoll
import matplotlib.cbook as cbook
import matplotlib.lines as mlines
import matplotlib.markers as mmarkers
import matplotlib.projections as mprojections

Expand All @@ -14,13 +17,20 @@
FunctionConversionNode,
RenameConversionNode,
)
from .line import Line
from .wrappers import PathCollectionWrapper


class Axes(MPLAxes):
# Name for registering as a projection so we can experiment with it
name = "data-prototype"

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._ca = CompatibilityAxes(self)
self._get_lines_mirror = _process_plot_var_args("mirror")
self.add_artist(self._ca)

@_preprocess_data(
replace_names=[
"x",
Expand Down Expand Up @@ -142,6 +152,26 @@ def scatter(
self._request_autoscale_view()
return pcw

def plot(self, *args, scalex=True, scaley=True, data=None, **kwargs):
kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
line_args = [
*self._get_lines_mirror(
self, *args, data=data, **kwargs, return_kwargs=True
)
]
print(line_args)
lines = []
for coord, kws in line_args:
cont = ArrayContainer(**{"x": coord[0], "y": coord[1]})
line = Line(cont, **kws)
lines.append(line)
self._ca.add_artist(line)
if scalex:
self._request_autoscale_view("x")
if scaley:
self._request_autoscale_view("y")
return lines


# This is a handy trick to allow e.g. plt.subplots(subplot_kw={'projection': 'data-prototype'})
mprojections.register_projection(Axes)
38 changes: 36 additions & 2 deletions data_prototype/conversion_edge.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from typing import Any
import numpy as np

from data_prototype.description import Desc, desc_like
from data_prototype.description import Desc, desc_like, ShapeSpec

from matplotlib.transforms import Transform

Expand Down Expand Up @@ -112,6 +112,17 @@ def from_default_value(
) -> "DefaultEdge":
return cls(name, {}, {key: output}, weight, invertable=False, value=value)

@classmethod
def from_rc(
cls, rc_name: str, key: str | None = None, coordinates: str = "display"
):
from matplotlib import rcParams

if key is None:
key = rc_name.split(".")[-1]
scalar = Desc((), coordinates)
return cls.from_default_value(f"{rc_name}_rc", key, scalar, rcParams[rc_name])

def evaluate(self, input: dict[str, Any]) -> dict[str, Any]:
return {k: self.value for k in self.output}

Expand Down Expand Up @@ -327,6 +338,7 @@ def edges(self):
import matplotlib.pyplot as plt

self.visualize(input)
self.visualize()
plt.show()
raise NotImplementedError(
"This may be possible, but is not a simple case already considered"
Expand All @@ -344,7 +356,7 @@ def edges(self):
else:
out_edges.append(SequenceEdge.from_edges("eval", edges, output_subset))

found_outputs = set()
found_outputs = set(input)
for out in out_edges:
found_outputs |= set(out.output)
if missing := set(output) - found_outputs:
Expand Down Expand Up @@ -418,3 +430,25 @@ def __add__(self, other: Graph) -> Graph:
aother = {k: v for k, v in other._aliases}
aliases = tuple((aself | aother).items())
return Graph(self._edges + other._edges, aliases)


def coord_and_default(
key: str,
shape: ShapeSpec = (),
coordinates: str = "display",
default_value: Any = None,
default_rc: str | None = None,
):
if default_rc is not None:
if default_value is not None:
raise ValueError(
"Only one of 'default_value' and 'default_rc' may be specified"
)
def_edge = DefaultEdge.from_rc(default_rc, key, coordinates)
else:
scalar = Desc((), coordinates)
def_edge = DefaultEdge.from_default_value(
f"{key}_def", key, scalar, default_value
)
coord_edge = CoordinateEdge.from_coords(key, {key: Desc(shape)}, coordinates)
return coord_edge, def_edge
8 changes: 8 additions & 0 deletions data_prototype/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,14 @@ def __init__(self, container, edges=None, norm=None, cmap=None, **kwargs):
{"image": Desc(("O", "P", 4), "rgba_resampled")},
{"image": Desc(("O", "P", 4), "display")},
),
FuncEdge.from_func(
"rgb_rgba",
lambda image: np.append(
image, np.ones(image.shape[:-1] + (1,)), axis=-1
),
{"image": Desc(("M", "N", 3), "rgb")},
{"image": Desc(("M", "N", 4), "rgba")},
),
self._interpolation_edge,
]

Expand Down
4 changes: 2 additions & 2 deletions data_prototype/line.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def __init__(self, container, edges=None, **kwargs):

scalar = Desc((), "display") # ... this needs thinking...

edges = [
default_edges = [
CoordinateEdge.from_coords("xycoords", {"x": "auto", "y": "auto"}, "data"),
CoordinateEdge.from_coords("color", {"color": Desc(())}, "display"),
CoordinateEdge.from_coords("linewidth", {"linewidth": Desc(())}, "display"),
Expand All @@ -45,7 +45,7 @@ def __init__(self, container, edges=None, **kwargs):
DefaultEdge.from_default_value("mew_def", "markeredgewidth", scalar, 1),
DefaultEdge.from_default_value("marker_def", "marker", scalar, "None"),
]
self._graph = self._graph + Graph(edges)
self._graph = self._graph + Graph(default_edges)
# Currently ignoring:
# - cap/join style
# - url
Expand Down
97 changes: 97 additions & 0 deletions data_prototype/text.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import numpy as np

from matplotlib.font_manager import FontProperties

from .artist import Artist
from .description import Desc
from .conversion_edge import Graph, CoordinateEdge, coord_and_default


class Text(Artist):
def __init__(self, container, edges=None, **kwargs):
super().__init__(container, edges, **kwargs)

edges = [
CoordinateEdge.from_coords(
"xycoords", {"x": Desc((), "auto"), "y": Desc((), "auto")}, "data"
),
*coord_and_default("text", default_value=""),
*coord_and_default("color", default_rc="text.color"),
*coord_and_default("alpha", default_value=1),
*coord_and_default("fontproperties", default_value=FontProperties()),
*coord_and_default("usetex", default_rc="text.usetex"),
*coord_and_default("rotation", default_value=0),
*coord_and_default("antialiased", default_rc="text.antialiased"),
]

self._graph = self._graph + Graph(edges)

def draw(self, renderer, graph: Graph) -> None:
if not self.get_visible():
return
g = graph + self._graph
conv = g.evaluator(
self._container.describe(),
{
"x": Desc((), "display"),
"y": Desc((), "display"),
"text": Desc((), "display"),
"color": Desc((), "display"),
"alpha": Desc((), "display"),
"fontproperties": Desc((), "display"),
"usetex": Desc((), "display"),
# "parse_math": Desc((), "display"),
# "wrap": Desc((), "display"),
# "verticalalignment": Desc((), "display"),
# "horizontalalignment": Desc((), "display"),
"rotation": Desc((), "display"),
# "linespacing": Desc((), "display"),
# "rotation_mode": Desc((), "display"),
"antialiased": Desc((), "display"),
},
)

query, _ = self._container.query(g)
evald = conv.evaluate(query)

text = evald["text"]
if text == "":
return

x = evald["x"]
y = evald["y"]

_, canvash = renderer.get_canvas_width_height()
if renderer.flipy():
y = canvash - y

if not np.isfinite(x) or not np.isfinite(y):
# TODO: log?
return

# TODO bbox?
# TODO implement wrapping/layout?
# TODO implement math?
# TODO implement path_effects?

# TODO gid?
renderer.open_group("text", None)

gc = renderer.new_gc()
gc.set_foreground(evald["color"])
gc.set_alpha(evald["alpha"])
# TODO url?
gc.set_antialiased(evald["antialiased"])
# TODO clipping?

if evald["usetex"]:
renderer.draw_tex(
gc, x, y, text, evald["fontproperties"], evald["rotation"]
)
else:
renderer.draw_text(
gc, x, y, text, evald["fontproperties"], evald["rotation"]
)

gc.restore()
renderer.close_group("text")
16 changes: 10 additions & 6 deletions examples/2Dfunc.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
import matplotlib.pyplot as plt
import numpy as np

from data_prototype.wrappers import ImageWrapper
from data_prototype.artist import CompatibilityAxes
from data_prototype.image import Image
from data_prototype.containers import FuncContainer

from matplotlib.colors import Normalize
Expand All @@ -19,20 +20,23 @@
fc = FuncContainer(
{},
xyfuncs={
"xextent": ((2,), lambda x, y: [x[0], x[-1]]),
"yextent": ((2,), lambda x, y: [y[0], y[-1]]),
"x": ((2,), lambda x, y: [x[0], x[-1]]),
"y": ((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),
),
},
)
norm = Normalize(vmin=-1, vmax=1)
im = ImageWrapper(fc, norm=norm)
im = Image(fc, norm=norm)

fig, nax = plt.subplots()
ax = CompatibilityAxes(nax)
nax.add_artist(ax)

fig, ax = plt.subplots()
ax.add_artist(im)
ax.set_xlim(-5, 5)
ax.set_ylim(-5, 5)
fig.colorbar(im)
# fig.colorbar(im, ax=nax)
plt.show()
27 changes: 18 additions & 9 deletions examples/animation.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@
from data_prototype.conversion_edge import Graph
from data_prototype.description import Desc

from data_prototype.conversion_node import FunctionConversionNode

from data_prototype.wrappers import FormattedText
from data_prototype.artist import CompatibilityArtist as CA
from data_prototype.artist import CompatibilityAxes
from data_prototype.line import Line
from data_prototype.text import Text
from data_prototype.conversion_edge import FuncEdge


class SinOfTime:
Expand Down Expand Up @@ -63,15 +63,24 @@ def update(frame, art):


sot_c = SinOfTime()
lw = CA(Line(sot_c, linewidth=5, color="green", label="sin(time)"))
fc = FormattedText(
lw = Line(sot_c, linewidth=5, color="green", label="sin(time)")
fc = Text(
sot_c,
FunctionConversionNode.from_funcs(
{"text": lambda phase: f"ϕ={phase:.2f}", "x": lambda: 2 * np.pi, "y": lambda: 1}
),
[
FuncEdge.from_func(
"text",
lambda phase: f"ϕ={phase:.2f}",
{"phase": Desc((), "auto")},
{"text": Desc((), "display")},
),
],
x=2 * np.pi,
y=1,
ha="right",
)
fig, ax = plt.subplots()
fig, nax = plt.subplots()
ax = CompatibilityAxes(nax)
nax.add_artist(ax)
ax.add_artist(lw)
ax.add_artist(fc)
ax.set_xlim(0, 2 * np.pi)
Expand Down
Loading
Loading