diff --git a/CHANGELOG.md b/CHANGELOG.md index f4caa088..820d7918 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,457 @@ # Changelog +## 1.2.1 (2026-11-24) + +Follows 1.2.0. Animated trails now work with line-and-marker formats (GH +#299), and six small layout points in the gallery figures are fixed (GH +#297). + +### Fixed + +- **A `legend_colors=` pair legend draws each key in its dataset's line + styling.** `legend_colors=[(label, color), ...]` drew every key as the + same 2-point solid line (or 8-point marker), whatever was plotted: with + `linewidth=[1.1, 1.1, 3.4]` the heavy line's key was as thin as the + others (1.1.0 and 1.2.0 too; found in the gallery's market-sectors + clip, whose "Market" key had been thick while the example drew its own + legend). When there is exactly one pair per drawn dataset, in order, + each key now takes that dataset's own `fmt` and its `linewidth`, + `linestyle`, `marker`, `markersize` and `alpha`, on static plots, + animations and `panels=` grids (plotly: the line width). A property + that was not given keeps the swatch's value, so a call without + per-dataset styling is drawn as before, as is a pair list with any + other number of entries and the palette swatches of a matrix or mixture + `hue=`. The legend hypertools builds itself (`legend=[...]`) already + showed each dataset's styling. +- **A static 3-D plot whose cube needs no fitting is drawn exactly as in + 1.2.0.** The cube fit added for GH #297 set the box aspect of every + static 3-D plot again at zoom 1, and matplotlib's rescaling of the + aspect moved it by one unit in the last place. Nothing visible changed, + but a few antialiased pixels did (2 to 7 pixels, one color level each, + in three gallery figures). A cube that is clear already is no longer + touched. +- **An animation given a format string and `linestyle=` or `marker=` no + longer warns.** `hyp.plot(x, '-', linestyle=['-', '--'], animate=True)` + made matplotlib warn "linestyle is redundantly defined by the + 'linestyle' keyword argument and the fmt string" once per dataset; the + static plot of the same call was silent. The keyword still wins and the + frames are drawn as before. +- **An animated line-and-marker format draws its trails (GH #299).** + `hyp.plot(x, '-o', animate=True, chemtrails=True)` drew the tail and no + chemtrail, with no warning; `precog=` and `bullettime=` were dropped the + same way, for every format that has both a line and a marker (`'-o'`, + `'o-'`, `'.-'`, `'--s'`), on the matplotlib backend. The trail artists + were only created when some dataset of the call had a pure line format. + Every dataset that asks for a trail now gets one, drawn in its own + format: a line-and-marker trail is the faded line with faded markers on + the observations, as its tail is drawn. A markers-only format now gets + its trail of faded markers on its own too (it used to get one only when + another dataset of the same call was a pure line), which is what the + plotly backend has always drawn. Single plots, serial reveals, animated + `panels=` grids and continuous `hue=` coloring are all covered: with a + continuous `hue=` a line-and-marker format draws the colored line and a + colored marker on each observation, on the tail and on the trail. +- **Continuous `hue=` in an animation (found in review).** A serial reveal + of a markers-only format with a trail flag (`hyp.plot(x, 'o', hue=h, + animate='serial', chemtrails=True)`) raised `AttributeError` on its + first frame; a serial trail stayed on screen after its dataset was + finished and when the animation started over; a trail was drawn at + `trail_alpha=` alone instead of `trail_alpha=` times the dataset's + `alpha=` (a faint dataset had a trail stronger than its head); an + animated hue-colored line ignored `alpha=` and was drawn opaque (the + static plot has honored it since 1.1); and a call that mixes formats + (`['-', 'o']`) drew every dataset as markers, static or animated. Each + dataset is now drawn by its own format, at its own opacity. Matplotlib + backend. +- **`dataset_fade=` fades the right trail.** With a per-dataset flag list + such as `chemtrails=[False, True]` the one trail was faded as the first + dataset's. A dataset's `head_marker=` fades with it under a continuous + `hue=` too. +- **A trail is drawn in its own dataset's color when only some datasets + have one.** With a per-dataset list such as `chemtrails=[False, True]` + the trail took the next color of the color cycle, which was another + dataset's (matplotlib backend). Found while fixing GH #299. +- **The cube of an animated 3-D plot stays inside the canvas and off the + legend (GH #297).** An animated 3-D plot fills its canvas with the cube + zoomed in, so on a square or portrait figure (`size=(8, 8)`) the cube, + seen corner-on, reached the left and right canvas edges and ran past + them, and at its widest view its right corner reached into the box of + the legend beside the plot. A legend placed in a corner of the axes + (`legend_kwargs={'loc': 'upper left'}`) could meet the cube's top + corner, in a static plot too. The cube is now measured at every camera + angle the plot is seen from and drawn smaller until it keeps a margin of + about 2% of the canvas's shorter side (measured on every frame: 1.95% + to 2%) from the canvas edges, from the legend and from the colorbar. + What changes in existing figures: an animated 3-D plot on a + square or portrait figure draws its cube about 10% smaller, an animated + landscape plot with a legend about 5% smaller, and a plot whose cube + was already clear (an animated landscape plot without a legend, every + static plot whose legend is in its default place) is drawn as before. A + `zoom=` above 1 is left alone, and so are `panels=` grids (they have + their own fit) and plots drawn into an `ax=`. To clear a large legend + the cube is drawn no smaller than 55% of its size. An animated plot's + figure now shows the first frame as soon as `hyp.plot` returns (it was + empty until the first frame was drawn). Matplotlib backend. +- **Observation labels are not drawn on top of each other (GH #297).** + Every `labels=` box hangs up and to the left of its point, so the labels + of two points that are close on screen covered each other. A label whose + box is covered by an earlier label's now moves to another place around + its point (a corner or a side, at the usual distance or further out): + a free place on the canvas at the shortest distance, and of those the + one nearest to where it was. A label that covers nothing stays where it + was. The placement is made at draw time, so it holds after a resize and + when a 3-D plot is rotated by hand, where it is stable: a label keeps + its place until its box is covered and does not go back when its old + place becomes free (the labels are hidden while the mouse button is + down, as before, and come back where they were). A static figure saves + the same picture every time the same call is made, and the placement is + worked out in points from the figure's own size, not from the pixels of + the draw, so the screen, a PNG at any dpi, a PDF and an SVG show the + same arrangement; a figure whose size is changed is placed again. A + redraw of an unchanged figure does not work the placement out again. + Several labeled calls into one `ax=` are kept off each other as one + set (and share one pair of mouse callbacks, where every call used to + connect its own), and an axes that was cleared (`ax.clear()`) and + plotted into again has its new labels placed. A label that is rotated + or otherwise restyled after the plot was made is measured again at the + next draw. With very many labels on a small figure some boxes still + overlap (for an animation's labels see the next entry). + The arrow of a 3-D label points at its point after the cube is drawn + smaller to clear a legend. A 2-D label the reader has dragged is left + where it was put. Above 300 visible labels nothing is moved. Matplotlib + backend. +- **An animation's labels are placed on every frame, without hopping.** + In 1.2.0 every label of an animation hung at one fixed offset, so + labels covered each other whenever their points came close. Now every + frame's labels are placed for that frame by the rule of a static + figure: each label is attached to its point where the frame shows it + (in a turning 3-D plot the labels turn with their points), kept off + the other labels shown on that frame, off the legend, the colorbar, the + titles, the suptitle and the caption, and inside the canvas. Labels of + points a frame does not show are hidden, as before. Placing every + frame on its own made labels hop back and forth (8 labels on a + 60-frame spin changed place 95 times, 29 of them out and straight + back; 30 labels 720 times), so every label is given a plan for the + whole animation before a frame is drawn: the cheapest path through + the frames among 72 places round its point (16 directions, up to 130 + points out) in which it stays at a place for as long as the place is + clear, moves BEFORE another label arrives (a glide of about a third + of a second), then stays for a second, and prefers the nearer place + and the one whose leader line points out of the cloud. A glide that + would cross another label is planned again, labels that are still + not clear are planned again among all the others, and a spin of + whole turns is planned round the loop. Measured on 60-frame spins, + pairs of overlapping labels per frame: 0 on every frame with 8 and + with 12 labels and in a sliding 3-D window; with 30 labels on a + default-size cube 0.75 on average and at most 3 (5.6 and 10 when each + frame is placed on its own); in a 2 x 2 grid with 12 labels a panel, + one pair on 4 frames of 60. (With the wider text of matplotlib 3.11: + 1.5 on average with 30 labels, pairs on 11 frames in the grid.) + No label turns back (29, 46, 164 and 251 turn-backs when each frame + is placed on its own). Frame + `i` is the same picture however it is reached (in order, out of order + with `draw_frame`, in a saved file, in a second identical call), and + the placement is worked out again if the figure is given another + size. Where a glide would carry a label across the legend or a title + the label jumps instead. Cost, at the time the plot is made (nothing + is rendered for it), for a 60-frame 3-D spin, in CPU seconds: 0.4 + with 20 labels, 1.5 with 60, 2.4 with 200 (0.05, 0.14 and 0.48 when + the labels were placed once). The more labels, the fewer times each + plan is revised: above 80 labels a label that still lies on another + is not planned a second time. A frame itself draws no slower (29, 84 + and 271 ms: drawing the label boxes is what a frame costs). + With many labels on a small cube some still overlap. Matplotlib + backend; on plotly the labels are annotations at one fixed offset + that follow their points and are shown on every frame, as before. +- **Observation labels are arranged the same at every resolution under + matplotlib 3.11, and a corner legend is cleared there.** Matplotlib + 3.11 measures a text at its figure's resolution whatever renderer it + is given, so a figure saved at another `dpi=` (or as PDF or SVG) had + some labels at other places than on screen; the labels are now + measured at one fixed resolution on both versions. 3.11 also gives a + line of text its font's full line height, so a legend is about a + quarter taller, and an animated cube that had to stop at 70% of its + size was drawn under a ten-entry corner legend on 8 of 36 frames: to + clear a legend the cube may now come down to 55%. Matplotlib backend. +- **An animation's label plan is bounded, freed, picklable and kept up + to date.** Found by a source review of the plan above, each + reproduced first. With more than 300 labels (which stay at their usual + places) every frame was still run and a table of every frame kept: 58 + bytes a label and frame, 13.9 MB for 400 labels on 600 frames; the + table now has one row (11 kB) and no frame is run. Planning took time + in proportion to the frames (30 CPU seconds for 60 labels on 600 + frames, against 1.6 on 60): an animation of more than 3600 labels x + frames is now planned at evenly spaced frames, with the labels moving + evenly between them (2.3 s on 600 frames, 2.4 s on 3000), and the table + is 28 bytes a label and planned frame, at most about 0.4 MB an axes. + A closed animated figure with labels was never freed (the labels' + state held the animation's frame function), nor was the last static + figure with labels (a module global); both are freed now. + `pickle.loads(pickle.dumps(anim.figure)).canvas.draw()` and + `copy.deepcopy(anim.figure)` raised `TypeError`; the copy now draws + and saves with its labels where the frame it was taken at had them. + A text or legend added to the figure, or a label given a longer text + or a larger font, after the plan was made was not planned for; the + plan is now made again, once (and for a figure that changes on every + frame, at the first two changes and when it stops changing). +- **Legends, titles and the cube keep one layout for a whole animation, + and a 3-D plot's axis labels stay inside the canvas as it turns.** The + cube of a single animated 3-D plot was fitted to the canvas without + its axis labels (`xlabel=`, `ylabel=`, `zlabel=`, or a DataFrame's + column names), which hang outside the cube and turn with it: on a + 5 x 5 inch figure "the z axis" was up to 61 px off the canvas for + part of each turn, and with a legend, a title and a caption the axis + labels crossed them on 6 of 60 frames. The cube is now drawn small + enough that, at the camera angle of EVERY frame (not a sample: which + edge a label hangs from changes from one view to the next), each axis + label is on the canvas and clear of the legend, the colorbar, the + title, the suptitle and the caption. That one layout holds for the + whole animation: nothing that does not turn moves or changes size + between frames. A static 3-D plot is fitted the same way for its one + view. Observation labels keep off the cube's axis labels, and off the + other panels of a grid (a label that reached into the next panel was + painted over by that panel's background, cut off at its edge), in + static figures too. Matplotlib backend. +- **Labels keep off the legend, the colorbar, the titles and the + caption.** The labels were only kept off each other, so a label moved + out of another label's way could land on the shared legend of a + `panels=` grid (which no label did in 1.2.0), and a label could lie on + a panel title, a `suptitle=` or a `caption=` (as in 1.2.0). Every + legend, every colorbar with its tick labels, every panel title and + every figure text is now something a label is kept off, in 2-D and + 3-D, in a static figure and in the one placement an animation makes. + A single label that lies on a title moves too. A place on one of + them is the last resort: on a very small figure with large texts, + where there is not room for every label, labels lie on each other + rather than on a title or the legend. + Matplotlib backend. +- **`legend_kwargs={'loc': 'upper left'}` on a 2-D plot puts the legend + inside the frame.** A 2-D hypertools axes fills the canvas and the + frame is drawn inside it, so a named `loc` put the legend across the + frame's border with its keys outside (in 1.2.0 too, static and + animated). A named `loc` is now read against the drawn frame, as + matplotlib reads it against the axes' frame. A `bbox_to_anchor`, a + coordinate pair as `loc`, 3-D plots and `panels=` grids are unchanged. +- **`labels=` with `animate='morph'` says that no label is drawn.** A + morph draws one cloud that moves from each dataset's shape to the next, + so it has no observation for a label to stay on. The matplotlib backend + hid every label without a word, and the plotly backend drew them in 2-D + at the first cloud's positions while the cloud moved away. Both now + draw no label and give one `UserWarning`. +- **A per-dataset trail list works with a categorical `hue=` or + `cluster=`.** `hyp.plot([a, b, c], '-', hue=categories, animate=True, + chemtrails=[False, True, True])` raised "3 entries but there are 5 + datasets" when the categories split the three datasets into five drawn + traces. Each trace now takes the flag of the dataset it comes from, for + `chemtrails=`, `precog=`, `bullettime=` and a `surface=` list. A list + with one entry per drawn trace is still accepted. A markers-only format + colored by category draws one trace per category, so there a list needs + one entry per category, and the error says so. +- **Markers colored by a continuous `hue=` keep their marker styling.** + `markerfacecolor=`, `markeredgecolor=`, `markeredgewidth=`, `fillstyle=` + and the short names (`mfc=`, `mec=`, `mew=`, `ms=`) were dropped, so + hollow markers with a black edge were drawn as filled dots. They are + now honored by the static plot and, in an animation, on the tail and on + the trail. A half `fillstyle=` (`'left'`, `'right'`, `'top'`, + `'bottom'`) draws the whole outlined marker with that half filled in + the hue color, as matplotlib draws it on a line; the other half is + empty, or filled with `markerfacecoloralt=` when that is given. Without + those arguments the markers are drawn as before. Matplotlib backend. +- **`hyp.plot` leaves a figure on its own canvas.** To measure a legend, + a caption or a `panels=` grid, `hyp.plot` drew the figure on a new Agg + canvas and left that canvas attached. In a window (macosx, QtAgg, + TkAgg) the figure's canvas was then no longer the one its window shows. + The figure's own canvas, and its dpi on a high-resolution display, are + now put back after every measurement. +- **A per-frame title has room on every frame.** The room above an + animated plot was sized from the first, middle and last frames' titles, + so a callable or `'{index}'` title that was tallest on another frame + ran off the canvas. Every frame's title is now measured, which calls a + callable title once per frame before the animation is returned. + Matplotlib backend. +- **An animated markers-only plot with a continuous `hue=` is animated + (GH #297).** `hyp.plot(x, 'o', animate=True, hue=values)` drew every + observation on every frame: in 3-D only the camera moved, in 2-D every + frame was the same picture, and `chemtrails=`/`precog=`/`bullettime=` + drew nothing. The markers are now revealed over the same window as + without `hue=`, each in its own color, with their trail of faded + markers. `animate='spin'` still shows every observation, as it should. + Matplotlib backend (plotly already animated this call). +- **A line-and-marker stream draws a marker on every sample.** With a + format such as `'-o'`, a streaming plot drew the first `stream_init` + samples twice, as a line without markers and as a markers-only copy, + and only the line was updated as samples arrived. So the samples that + streamed in had no marker, and the first samples' markers stayed where + they were for the whole stream, after `stream_window=` had scrolled + those samples away as well. The streamed line now carries the markers + itself, one per sample shown. A stream drawn into a caller's `ax=` that + already held lines also updates its own line now, not the first line of + the figure's first axes. +- **A bad sample in the middle of a chunk keeps the samples before it.** A + stream sample that could not be read ended the stream and dropped the + samples of the same `stream_chunk` that had arrived before it. They are + now kept and drawn, as the samples of earlier chunks always were. + +### Examples + +- `animate_market_sectors` draws its key with the library's legend + (`legend_colors=` pairs and `legend_kwargs={'loc': 'upper left'}`) + instead of a hand-made `ax.legend`, so the library keeps the cube clear + of it (GH #297). +- `animate_weather_decades`: the map and time-series panels, which the + example places itself, end at 0.985 of the figure width instead of + 0.995, so the marker on the last month is no longer cut by the canvas + edge (GH #297). +- `plot_shapes_zoo`: the teapot, the one sparse cloud (1,728 rows, 301 + distinct points), is drawn with the `.` marker instead of the one-pixel + `,` (GH #297). +- `plot_datasets_tour`: the Bechdel panel plots its dollar columns on a + log scale. Budgets and grosses span six orders of magnitude, so a few + blockbusters stretched the axes and squeezed every other film into one + corner of the cube (GH #297). + +### Added + +- **`labels=` on streaming plots.** A stream (an iterator, a generator or + a Hugging Face `IterableDataset` passed to `hyp.plot`) used to ignore + `labels=` with a warning. It now draws them, in 2-D and 3-D, on + matplotlib (the backend every stream is drawn with). A stream's length + is not known, so the labels are a callable `labels(index, sample)`, + called once per consumed sample (with dict samples it can read a text + field: `labels=lambda i, row: row['title']`), or an iterable consumed in + step with the samples: a list, tuple, array or Series, or an iterator or + generator, which may be endless. A list shorter than the stream labels + the first samples only. `None`, NaN or a blank string draws no label. A + bare string or a non-iterable raises `TypeError` before a sample is + consumed. `label_alpha=` is honored as well. Each label is attached to + its sample's drawn position on every frame, and with `stream_window=` it + is removed when its sample leaves the window. The labels of every + consumed sample are kept in `fig.stream_info['labels']` (`None` when no + `labels=` was given). A `labels=` callable or iterator that raises for a + sample ends the stream like a source error: a `RuntimeWarning`, the + exception under `stream_info['error']`, and a figure holding every + sample before that one, each with its own label, in the middle of a + chunk and inside the first `stream_init` samples as well. Only a + failure on the very first sample raises out of the call. + + The samples to come are unknown, so the labels are placed once per + update, by the placement rule of every other label (off each other, off + the title, legends and figure texts, inside the canvas), from where the + update before left them. A label keeps its place while that place is + clear. A new label takes a free place and the labels already shown stay + where they are. A label that has to move (the figure was resized or + turned, or room came free for a label that had none) glides to the + nearest free place over about 0.4 seconds of frames, rests there for + three glides, and does not go back to the place it left for six glides + unless nothing else is free. The title, the axes and the display box are + laid out once, from the first `stream_init` samples. The same stream in + the same chunks saves the same frames: the labels are stepped once per + emitted frame, never per draw or by a clock. + + Measured (3-D, a new label on every update): placing the labels of one + update takes a median 0.6 ms with 10 visible labels, 1.1 ms with 50 and + 2.7 ms with 200. At most 300 visible labels are kept off each other (the + oldest); the others hang at the usual place, and a `UserWarning` says so + once. With 12 labels arriving next to each other no two overlap on any + frame and no label moves. When the view is turned in the middle of a + stream the labels overlap on the frame of the turn (the turn was not + known in advance) and are clear again within one glide, with no label + turning back. With `stream_window=` the number of labels on the figure + is bounded by the window. Without it every label stays, so memory grows + with the number of labeled samples. + + The arguments a stream does not implement (`head_marker=`, + `tail_linewidth=`, `trail_alpha=` and the rest) are still ignored with + the warning that names them. +- **`legend=`, `caption=` and `suptitle=` on streaming plots.** A stream + used to ignore them with a warning. They are now drawn, in 2-D and 3-D, + with their styling arguments (`legend_kwargs=`, `legend_colors=`, + `caption_kwargs=`, `suptitle_kwargs=`). Each is laid out once, when the + first `stream_init` samples are drawn, and stays where it is for the + whole stream: the display box is frozen from those samples, so the room + made for the legend holds on every later frame. The legend key is drawn + in the style of the streamed line, and a stream's labels keep off the + legend, the caption and the suptitle. A stream's caption is one fixed + string: a callable raises `TypeError` before a sample is consumed, + because the number of frames of a stream is not known. With `ax=`, + `caption=` and `suptitle=` raise `ValueError` as on any plot drawn into + a caller's axes, and `legend=` is drawn in that axes. A stream is one + dataset: a `legend=` list or a `legend_colors=` color list of another + length raises `ValueError` before a sample is consumed. + +- **`head_marker=`: a marker at the reveal head (GH #299).** + `hyp.plot(x, '-', animate=True, head_marker='o')` draws one marker on the + last revealed point of each dataset, on every frame. Pass a matplotlib + marker, `True` for `'o'`, or a dict such as `{'marker': 'D', 'size': 10, + 'color': 'k'}`. Its color, alpha and size follow the dataset unless the + dict sets them (with a continuous `hue=` it takes the color of the point + it is on). The marker may be any marker matplotlib draws, an array of + vertices included. In an `on_frame=` callback, hiding a dataset's + artist in `ctx.artists` hides its head marker too, and with a + continuous `hue=` on a line-and-marker format the markers follow the + visibility and alpha of the listed line. There is one marker per + dataset: when a categorical `hue=` or `cluster=` colors a dataset in + several pieces, the marker is on the dataset's current point, in that + point's category color. The first frame of a serial reveal shows the + first dataset's marker on its first point. The dict also takes a face + color (`facecolor`, or matplotlib's `markerfacecolor`/`mfc`) and + matplotlib's short names `ms`, `mec`, `mew`, `mfcalt` and `c`. + Matplotlib only. +- **`tail_linewidth=`: a tail thicker (or thinner) than its trail (GH + #299).** The line width of the recent window that `tail_duration=` + sizes; a `chemtrails=`/`precog=`/`bullettime=` trail keeps `linewidth=`. + Matplotlib only. +- **`trail_alpha=`: the opacity of the trails (GH #299).** A fraction of + each dataset's own `alpha=`. The default stays 0.3. Both backends. +- **`hold=`: hold the last frame (GH #299).** `hold=2` appends two seconds + of frames (`round(hold * frame_rate)`) that draw the last frame again, in + saved `.mp4` and `.gif` files as well as on screen. An `.mp4` stores + every held frame; a `.gif` plays for the same time with fewer stored + frames, because its writer (Pillow) stores a run of identical frames as + one frame with the run's duration. A hold shorter than half a frame + adds no frame, and a warning says so. Per-frame titles, + captions and `on_frame=` callbacks see the last frame's context during + the hold. Works with every `animate=` style, with `loop=True` and on + animated `panels=` grids. Matplotlib only. +- **`caption_kwargs=`: caption size, color and position (GH #299).** + `caption_kwargs={'size': 14, 'color': 'gray', 'position': 'top', 'loc': + 'left'}`. The style is applied before the caption is wrapped and its + room is measured, and a per-frame caption is measured on every frame + (a callable caption is called once per frame before the animation is + returned), so a caption of any size is never clipped. +- **`suptitle=`: a title for the whole figure (GH #299).** With `panels=`, + `title=` names the panels; `suptitle=` is the one title above the grid, + static or animated (it works on a single plot too). Its room is measured + like a caption's, so it clears the panel titles, the shared legend and + colorbar, and a caption placed at the top, at the tallest text a + per-frame caption shows on any frame. + `suptitle_kwargs=` styles it. Matplotlib only. +- `head_marker=`, `tail_linewidth=`, `trail_alpha=` and `hold=` may also be + given inside the `animate={...}` dict. The matplotlib-only arguments + raise `NotImplementedError` on an animated plot under + `backend='plotly'`. On a static plot, on either backend, + `head_marker=`, `tail_linewidth=` and `trail_alpha=` are ignored with a + warning (as the trail flags are) and `hold=` raises `ValueError`. + `tail_linewidth=` also warns when no dataset is drawn with a line, and + leaves the lines of `animate='spin'` at `linewidth=`. Under + `animate='window'`, which draws no trail, the `trail_alpha=` warning + says that instead of asking for a trail flag. In a `panels=` + grid each of these warnings is given once for the figure, and only when + it is true of every panel. +- **Values inside styling dicts are checked.** matplotlib decides what + each key of `head_marker=`, `caption_kwargs=`, `suptitle_kwargs=` and + `title_kwargs=` accepts, so whatever it takes is taken: `None` where it + takes `None`, a size as a number, a numeric string or a size name, a + weight as a number or a name. A value matplotlib refuses raises + `ValueError` naming the argument and the key (it already raised, from + matplotlib, without naming the argument). hypertools also refuses a + size that is not positive and finite, and a line spacing that is not + positive and finite. What changes for existing calls: + `title_kwargs={'size': -3}` (or 0, `False`, NaN, or those as strings) + was accepted and drew no readable title, and `title_kwargs= + {'linespacing': 0}` (or a negative number, or NaN) was accepted; both + now raise. + ## 1.2.0 (2026-11-22) A feature release. `animate=` now works with `panels=` (one animation of the diff --git a/RELEASE_CHECKLIST.md b/RELEASE_CHECKLIST.md index 3de6a945..112c87fc 100644 --- a/RELEASE_CHECKLIST.md +++ b/RELEASE_CHECKLIST.md @@ -1,6 +1,27 @@ # HyperTools 1.1 release checklist -## The 1.2.0 release: read this first +## The 1.2.1 release: read this first + +`pyproject.toml` and `CHANGELOG.md` declare **1.2.1** (GH #299 and GH #297, +on top of 1.2.0, which was released on 2026-11-22: PyPI, GitHub release, Read +the Docs "stable", conda-forge). Follow the 1.2.0 notes below and read `1.2.1` +for `1.2.0` (and `v1.2.1` for `v1.2.0`) in every command, with these +differences: + +- **Step 6, Read the Docs:** "stable" follows the highest version tag by + itself; confirm it instead of setting it. +- **Step 6, PyPI check:** `https://pypi.org/pypi/hypertools//json` + can keep answering a cached 404 for minutes after the upload; read + `https://pypi.org/pypi/hypertools/json` or the simple index instead. +- **Step 6, clean-environment check:** build the environment on Python 3.10 + or later. On 3.9, `pip install hypertools` installs 0.8.2 without a message. +- **Step 7, conda-forge:** if the bot has not opened a bump pull request, + open one from a personal fork of the feedstock (version and sdist sha256; + compare `[project] dependencies` with the previous tag) and ask + `@conda-forge-admin` to rerender, as was done for 1.1.0 and 1.2.0. +- There are no leftovers of an earlier draft to delete. + +## The 1.2.0 release (released 2026-11-22) `pyproject.toml` and `CHANGELOG.md` declare **1.2.0** (GH #295: animated panel grids, `caption=`, fast-start mp4; panel grids with shared colors, one diff --git a/docs/animation.rst b/docs/animation.rst index 852bccfb..cb69554a 100644 --- a/docs/animation.rst +++ b/docs/animation.rst @@ -41,6 +41,70 @@ reveal on **both** backends: hyp.plot(data, '-', animate=True, order='serial', chemtrails=True) +A trail is drawn in its dataset's own format and color: a line's trail is the +faded line, a line-and-marker format's (``'-o'``, ``'o-'``, ``'.-'``, +``'--s'``) the faded line with faded markers on the observations, and a +markers-only format's its faded markers. + +.. versionadded:: 1.2.1 + +Four arguments style the reveal: + +.. code-block:: python + + hyp.plot(data, '-', animate=True, chemtrails=True, linewidth=1, + trail_alpha=0.5, # trails at 0.5 x alpha (default 0.3) + tail_linewidth=3, # the recent window, drawn thicker + head_marker='o', # a marker on the last revealed point + hold=2) # hold the last frame for 2 seconds + +``trail_alpha=`` is the opacity of the trails as a fraction of each dataset's +own ``alpha=`` (both backends). ``tail_linewidth=`` is the line width of the +tail, the recent window that ``tail_duration=`` sizes, while the trail keeps +``linewidth=``. ``head_marker=`` draws a marker at the reveal head only (a +matplotlib marker, ``True`` for ``'o'``, or a dict such as ``{'marker': 'D', +'size': 10, 'color': 'k'}``); its color and size follow the dataset unless +the dict sets them. The dict's keys are ``marker``, ``size``, ``color``, +``facecolor``, ``edgecolor``, ``edgewidth``, ``alpha``, ``fillstyle``, +``facecoloralt`` and ``zorder``; matplotlib's own names are taken as well +(``markersize``/``ms``, ``markerfacecolor``/``mfc``, +``markeredgecolor``/``mec``, ``markeredgewidth``/``mew``, +``markerfacecoloralt``/``mfcalt``, ``c``). ``color`` colors the whole +marker, ``facecolor`` fills it with another color (``'none'`` for a hollow +marker): + +.. code-block:: python + + hyp.plot(data, '-', animate=True, + head_marker={'marker': 'o', 'size': 12, + 'facecolor': 'white', 'edgecolor': 'k'}) + +There is one head marker per dataset. When a categorical ``hue=`` or +``cluster=`` colors a dataset in several pieces, the marker is on the +dataset's current point and takes the color of the category that point is +in. On the first frame of a serial reveal, before any point is revealed, the +first dataset's marker is on its first point, as the first frame of a +parallel reveal shows every dataset's. + +``hold=`` appends ``round(hold * frame_rate)`` frames +that draw the last frame again, so the pause is in a saved ``.mp4`` or +``.gif`` (a hold shorter than half a frame adds none, and a warning says +so); per-frame titles, captions and ``on_frame=`` callbacks see the last +frame's context during the hold. An ``.mp4`` stores every held frame. A +``.gif`` plays for the same time, but its writer (Pillow) stores a run of +identical frames as one frame with a longer duration, so it has fewer stored +frames than ``n_frames``. ``tail_linewidth=``, ``head_marker=`` and ``hold=`` +are matplotlib only: an animated plot under ``backend='plotly'`` raises +``NotImplementedError``. On a static plot (either backend) +``tail_linewidth=``, ``head_marker=`` and ``trail_alpha=`` are ignored with a +warning, and ``hold=`` raises ``ValueError``. ``tail_linewidth=`` also warns +when no dataset is drawn with a line (a markers-only format). All four may +also be given inside the ``animate={...}`` dict. + +With a continuous ``hue=`` the tail and the trail are colored observation by +observation, whatever the format: a line (``'-'``), markers (``'o'``), or +both (``'-o'``, the colored line with a colored marker on each observation). + Fading earlier datasets ------------------------ @@ -122,12 +186,144 @@ reserves room for every line above an animated 3-D plot, not just one. On the matplotlib backend the room above an animated plot is made for the tallest title the animation shows: a fixed title's own lines, the tallest entry of a per-segment list, and, for a callable or ``'{index...}'`` title, -the tallest of the first, middle and last frames' titles, so a title that -grows lines as the animation runs has its room from the start (a frame in -between that needs more lines than all three runs above it). The figure is +the tallest of every frame's titles, so a title that grows lines on any +frame has its room from the start (the callable is called once per frame +for this before the animation is returned). The figure is made taller by what the title needs, in 2-D and in 3-D, and nothing already drawn moves or shrinks. +Labels on the points +-------------------- + +``labels=`` works in an animation as it does in a static plot, and every +frame's labels are placed for that frame (matplotlib backend): + +.. code-block:: python + + hyp.plot(data, 'o', animate='spin', labels=names, + legend=['group'], title='Subjects', caption='One point each') + +* Each label is attached to its point where the frame shows it. As a 3-D + plot turns, the labels turn with their points. +* On every frame the labels are kept off each other, off the legend, the + colorbar, the titles, the suptitle and the caption, off the cube's own + axis labels, out of the next panel of a ``panels=`` grid, and inside the + canvas. +* The labels of points a frame does not show (not revealed yet, outside + the sliding window) are hidden. +* Labels do not hop about. Every label is given a plan for the whole + animation before a frame is drawn: it stays at one place by its point + for as long as that place is clear (the nearest such place; further + out, up to 130 points, where the plot is crowded). When another label + is about to arrive it glides to its next place over about a third of a + second, before the other gets there, and then stays for a second, so + it never goes out and straight back. A spin of whole turns is planned + round the loop, so its last frame leads into its first. +* With a dozen labels no two overlap on any frame. With more than the + canvas has room for (thirty on a default-size cube that turns once in + four seconds) a few still do for a moment: under one pair a frame, + where placing each frame on its own leaves five or six and makes the + labels hop. A larger figure, a slower turn or fewer labels clears + them. +* A frame is the same picture however it is reached: played in order, + shown out of order with ``draw_frame``, or saved to a file. + +The legend, the titles, the suptitle, the caption, the colorbar and the +size of the cube are laid out once, for the widest view of the whole +animation (the cube with its axis labels, at every frame's camera angle), +and do not move or change size from one frame to the next. The axis labels +of a 3-D plot turn with the cube and stay inside the canvas at every angle. + +Working the places out costs time when the plot is made, not when it +plays: about half a second for 20 labels over 60 frames, 1.5 seconds for +60 and 2.5 seconds for 200. The more labels, the fewer times each label's plan +is revised: above 80 labels a label that still lies on another is not +planned a second time, and above 300 the labels stay at their usual +places. An animation with more than 3600 labels x frames is planned at +evenly spaced frames (3600 over the number of labels, at least 40), and +its labels move evenly between them, so a long animation takes no longer +to plan than a short one and its plan is no larger. The plan is made +again when the figure is resized, a label's text or font is changed, or a +legend or text is added to the figure. A pickled or copied figure has no +animation to follow: its labels stay where the frame it was taken at had +them. On the plotly backend the labels are annotations +attached to their points: they follow the points as the scene turns, at +one fixed offset, and are shown on every frame. + +Labels on a stream +~~~~~~~~~~~~~~~~~~ + +A streaming plot (an iterator, a generator or a Hugging Face +``IterableDataset`` passed as the data, see the +:doc:`streaming data tutorial `) takes +``labels=`` too (new in 1.2.1, matplotlib). The number of samples is not +known in advance, so the labels are not one list with an entry per +observation. Pass either a callable or an iterable: + +.. code-block:: python + + # a callable: called once per sample with its position in the stream + # and the sample as the stream yielded it + hyp.plot(feed(), stream_init=500, stream_window=750, + labels=lambda i, sample: f't = {i}' if i % 100 == 0 else None) + + # an iterable (a list, or an iterator or generator, which may be + # endless), consumed in step with the samples + hyp.plot(feed(), stream_init=500, labels=['start', None, None, 'third']) + +* ``None`` (or NaN, or a blank string) draws no label. A list that is + shorter than the stream labels the first samples only. +* With dict samples, such as the rows of a Hugging Face stream, the + callable can read a text field that the numeric conversion ignores: + ``labels=lambda i, row: row['title']``. +* Every label is attached to its sample's drawn position on every frame. + With ``stream_window=`` a label is removed when its sample leaves the + window. The labels of all consumed samples are kept in + ``fig.stream_info['labels']``. +* The samples to come are unknown, so the labels cannot be planned for the + whole animation as above. They are placed once per update by the same + rule (off each other, off the title, legends and figure texts, inside the + canvas), starting from where the update before left them. A label keeps + its place while that place is clear. A new label takes a free place, and + the labels already shown stay where they are. A label that has to move + (the figure was resized or turned, or room came free for a label that had + none) glides to the nearest free place over about 0.4 seconds of frames, + rests there, and does not go back to the place it left for six glides + unless nothing else is free. +* The title, the axes and the display box are laid out once, from the + first ``stream_init`` samples, and do not move while the stream runs. +* The same stream in the same chunks saves the same frames. The placement + depends on the updates so far, never on a clock or on how often the + figure is drawn. +* Placing the labels of an update takes about 0.5 ms with 10 visible + labels, 1 ms with 50 and 3 ms with 200. At most 300 visible labels are + kept off each other (the oldest); the others hang at the usual place and + a warning says so once. Without ``stream_window=`` every label stays on + the figure, so memory grows with the number of labeled samples. + +A stream also takes ``legend=`` (with ``legend_kwargs=`` and +``legend_colors=``), ``caption=`` (with ``caption_kwargs=``) and +``suptitle=`` (with ``suptitle_kwargs=``), new in 1.2.1: + +.. code-block:: python + + hyp.plot(feed(), '-o', stream_init=500, legend=['sensor A'], + suptitle='Live recording', caption='Projected with PCA.') + +They are laid out once, when the first ``stream_init`` samples are drawn, +and stay where they are for the whole stream. The display box is frozen +from those samples, so the room made for the legend holds on every later +frame, and the legend key is drawn in the style of the streamed line. The +labels of a stream keep off all three. A stream's caption is one fixed +string: a callable (a per-frame caption) raises ``TypeError``, because the +number of frames of a stream is not known. With ``ax=``, ``caption=`` and +``suptitle=`` raise as they do on any plot drawn into a caller's axes, and +the legend is drawn in that axes. + +The arguments a stream does not implement (``head_marker=``, +``tail_linewidth=``, ``trail_alpha=`` among them) are still ignored with a +warning that names them. + Per-dataset styling ------------------- @@ -205,7 +401,14 @@ The context carries the frame index and total, the resolved ``style`` and ``segment_kind``. All of those are the same on either backend. What you *do* with the context is usually backend-specific, because -``ctx.figure``, ``ctx.axes`` and ``ctx.artists`` are backend-native. The +``ctx.figure``, ``ctx.axes`` and ``ctx.artists`` are backend-native. On +matplotlib ``ctx.artists`` holds one artist per dataset's reveal head, then +the trails. Two things are drawn by a second artist that is not in the list +and follows the listed one: the markers of a line-and-marker format +(``'-o'``) under a continuous ``hue=``, which are hidden when the listed +line is hidden and take its ``alpha``; and a ``head_marker=``, which is +hidden when its dataset's head artist is hidden. So +``ctx.artists[0].set_visible(False)`` hides the whole trace. The matplotlib form: .. code-block:: python @@ -842,9 +1045,9 @@ has no blank room there (an animated 3-D plot fills its canvas) the figure is made taller by the caption's height, so the caption never overlaps a panel, a legend or a colorbar and never leaves the canvas. A caption wider than the figure is wrapped to the figure's width, on every frame. Room is -made for the tallest of the first, middle and last frames' wrapped captions, -so a caption that grows as the animation runs has its room from the start -(a frame in between that needs more lines than all three runs below it). An +made for the tallest of every frame's wrapped captions, so a caption that +grows on any frame has its room from the start (a callable caption is +called once per frame for this before the animation is returned). An empty caption draws nothing and adds no room. On a static plot the caption is drawn once, a pattern or callable being resolved for the finished figure. @@ -857,6 +1060,33 @@ the panel that draws it (the first panel under a list-valued ``reduce=``). per-frame ``title=`` works on both backends) and ``ValueError`` with a caller-supplied ``ax=``. +.. versionadded:: 1.2.1 + +``caption_kwargs=`` styles and places the caption: ``size``, ``color``, +``weight``, ``style``, ``family``, ``alpha``, ``linespacing``, ``position`` +(``'bottom'``, the default, or ``'top'``) and ``loc`` (``'center'``, +``'left'`` or ``'right'``). The style is applied before the caption is +wrapped and its room measured, and a per-frame caption is measured on every +frame, so a caption of any size is never clipped. matplotlib decides what +each key accepts (a size may be a number, a numeric string or a size name, +and a key set to ``None`` keeps its default); a value it refuses, or a size +that is not positive and finite, raises ``ValueError`` naming the argument +and the key. + +``suptitle=`` is one fixed title for the whole figure, above everything it +holds. It is the figure-level title of a ``panels=`` grid, static or +animated, where ``title=`` names the panels; ``suptitle_kwargs=`` styles it +with the same keys (except ``position``). Its room is measured like the +caption's, so it clears the panel titles, the shared legend and colorbar, +and a caption placed at the top: + +.. code-block:: python + + hyp.plot([a, b, c, d], '-', panels=(2, 2), animate=True, + title=['a', 'b', 'c', 'd'], suptitle='Four walks, one clock', + caption=lambda ctx: f'frame {ctx.frame + 1} of {ctx.n_frames}', + caption_kwargs={'size': 13, 'color': 'gray', 'loc': 'right'}) + Companion panels ----------------- diff --git a/docs/prebuilt_gallery.json b/docs/prebuilt_gallery.json index 41dcc14e..bbebfe4a 100644 --- a/docs/prebuilt_gallery.json +++ b/docs/prebuilt_gallery.json @@ -1,5 +1,5 @@ { - "commit": "afb1e0d907b65adac1d63bf7357f3a73d8653008", - "source_commit": "9e6ababc5c70763a37c0a45290b668b0a4e554df", - "version": "1.2.0" + "commit": "2b70b5737f1d4601f1442dbfc9894a0a1c9e7a0c", + "source_commit": "27958d07057199d785cd917c1c0b08247a793aaa", + "version": "1.2.1" } diff --git a/docs/tutorials/market_sectors.ipynb b/docs/tutorials/market_sectors.ipynb index 679988b0..7ebc6a90 100644 --- a/docs/tutorials/market_sectors.ipynb +++ b/docs/tutorials/market_sectors.ipynb @@ -3,7 +3,7 @@ { "cell_type": "code", "execution_count": null, - "id": "a1a2f66b", + "id": "38957774", "metadata": { "tags": [ "hypertools-install" @@ -31,7 +31,7 @@ }, { "cell_type": "markdown", - "id": "0143207a", + "id": "d9898a19", "metadata": {}, "source": [ "# A quarter century of the market: six sectors, one space\n", @@ -97,7 +97,7 @@ }, { "cell_type": "markdown", - "id": "e56c84f4", + "id": "c7abaca9", "metadata": {}, "source": [ "## 1. Imports, a disk cache, and the universe\n", @@ -108,13 +108,13 @@ { "cell_type": "code", "execution_count": 1, - "id": "7c22a51a", + "id": "89453adf", "metadata": { "execution": { - "iopub.execute_input": "2026-10-08T17:13:14.085287Z", - "iopub.status.busy": "2026-10-08T17:13:14.085136Z", - "iopub.status.idle": "2026-10-08T17:13:17.444821Z", - "shell.execute_reply": "2026-10-08T17:13:17.444322Z" + "iopub.execute_input": "2026-11-24T16:52:05.998814Z", + "iopub.status.busy": "2026-11-24T16:52:05.998675Z", + "iopub.status.idle": "2026-11-24T16:52:17.023398Z", + "shell.execute_reply": "2026-11-24T16:52:17.021243Z" } }, "outputs": [], @@ -129,7 +129,6 @@ "import numpy as np\n", "import pandas as pd\n", "from matplotlib.colors import LinearSegmentedColormap, Normalize\n", - "from matplotlib.lines import Line2D\n", "\n", "import hypertools as hyp\n", "\n", @@ -168,7 +167,7 @@ }, { "cell_type": "markdown", - "id": "72420eda", + "id": "12ae1a94", "metadata": {}, "source": [ "## 2. Prices and share counts, with a synthetic fallback\n", @@ -179,13 +178,13 @@ { "cell_type": "code", "execution_count": 2, - "id": "742d6e96", + "id": "434030ee", "metadata": { "execution": { - "iopub.execute_input": "2026-10-08T17:13:17.446473Z", - "iopub.status.busy": "2026-10-08T17:13:17.446322Z", - "iopub.status.idle": "2026-10-08T17:13:17.453319Z", - "shell.execute_reply": "2026-10-08T17:13:17.452820Z" + "iopub.execute_input": "2026-11-24T16:52:17.027131Z", + "iopub.status.busy": "2026-11-24T16:52:17.026584Z", + "iopub.status.idle": "2026-11-24T16:52:17.038762Z", + "shell.execute_reply": "2026-11-24T16:52:17.037652Z" } }, "outputs": [], @@ -319,7 +318,7 @@ }, { "cell_type": "markdown", - "id": "04aee8b1", + "id": "fe182962", "metadata": {}, "source": [ "## 3. Growth curves per sector, market-cap weights, the basket's return\n", @@ -330,13 +329,13 @@ { "cell_type": "code", "execution_count": 3, - "id": "cf021a0f", + "id": "0f86f020", "metadata": { "execution": { - "iopub.execute_input": "2026-10-08T17:13:17.454325Z", - "iopub.status.busy": "2026-10-08T17:13:17.454266Z", - "iopub.status.idle": "2026-10-08T17:13:17.457742Z", - "shell.execute_reply": "2026-10-08T17:13:17.457398Z" + "iopub.execute_input": "2026-11-24T16:52:17.044547Z", + "iopub.status.busy": "2026-11-24T16:52:17.043443Z", + "iopub.status.idle": "2026-11-24T16:52:17.052864Z", + "shell.execute_reply": "2026-11-24T16:52:17.050251Z" } }, "outputs": [], @@ -393,7 +392,7 @@ }, { "cell_type": "markdown", - "id": "57db878c", + "id": "1a036517", "metadata": {}, "source": [ "## 4. Reduce per sector, hyperalign, draw seven paths\n", @@ -404,13 +403,13 @@ { "cell_type": "code", "execution_count": 4, - "id": "e30c4856", + "id": "55f1ca05", "metadata": { "execution": { - "iopub.execute_input": "2026-10-08T17:13:17.458582Z", - "iopub.status.busy": "2026-10-08T17:13:17.458527Z", - "iopub.status.idle": "2026-10-08T17:13:17.462317Z", - "shell.execute_reply": "2026-10-08T17:13:17.461981Z" + "iopub.execute_input": "2026-11-24T16:52:17.065202Z", + "iopub.status.busy": "2026-11-24T16:52:17.064755Z", + "iopub.status.idle": "2026-11-24T16:52:17.136095Z", + "shell.execute_reply": "2026-11-24T16:52:17.119630Z" } }, "outputs": [], @@ -445,13 +444,15 @@ " tail_duration=TAIL, duration=DURATION, frame_rate=FPS,\n", " rotations=ROTATIONS, colorbar=False,\n", " title=f'{months[0]:%B} {months[0].day}, {months[0].year}',\n", + " # the key is the library's own legend: one entry\n", + " # per sector color plus a gray one for the market\n", + " # path, in the top-left corner of the axes. The\n", + " # library keeps the turning cube clear of it.\n", + " legend_colors=list(zip(names, SECTOR_COLORS))\n", + " + [('Market (average across sectors)', '#666666')],\n", + " legend_kwargs={'loc': 'upper left', 'fontsize': 8},\n", " size=(8, 8), backend='matplotlib', show=False)\n", " ax = anim.figure.axes[0]\n", - " ax.legend(handles=[Line2D([], [], color=c, lw=2, label=s)\n", - " for s, c in zip(names, SECTOR_COLORS)]\n", - " + [Line2D([], [], color='#666666', lw=3.4,\n", - " label='Market (average across sectors)')],\n", - " loc='upper left', fontsize=8, frameon=False)\n", "\n", " def date_title(ctx):\n", " \"\"\"The title is the date under the head, tinted by the basket's own\n", @@ -468,7 +469,7 @@ }, { "cell_type": "markdown", - "id": "85060e6c", + "id": "3b62955d", "metadata": {}, "source": [ "## 5. Load the data and build the animation\n" @@ -477,13 +478,13 @@ { "cell_type": "code", "execution_count": 5, - "id": "ee426656", + "id": "95b19b8c", "metadata": { "execution": { - "iopub.execute_input": "2026-10-08T17:13:17.463211Z", - "iopub.status.busy": "2026-10-08T17:13:17.463154Z", - "iopub.status.idle": "2026-10-08T17:13:18.038190Z", - "shell.execute_reply": "2026-10-08T17:13:18.037689Z" + "iopub.execute_input": "2026-11-24T16:52:17.141157Z", + "iopub.status.busy": "2026-11-24T16:52:17.140511Z", + "iopub.status.idle": "2026-11-24T16:52:18.284624Z", + "shell.execute_reply": "2026-11-24T16:52:18.248582Z" } }, "outputs": [ @@ -491,7 +492,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "market data: 317 months x 27 stocks in 6 sectors, May 2000 - Sep 2026 (Yahoo Finance closes, SEC share counts)\n" + "market data: 318 months x 27 stocks in 6 sectors, May 2000 - Oct 2026 (Yahoo Finance closes, SEC share counts)\n" ] } ], @@ -508,7 +509,7 @@ }, { "cell_type": "markdown", - "id": "f22ada08", + "id": "bdf5151e", "metadata": {}, "source": [ "## 6. Save the animation\n" @@ -517,13 +518,13 @@ { "cell_type": "code", "execution_count": 6, - "id": "b566ef8e", + "id": "d93faf1a", "metadata": { "execution": { - "iopub.execute_input": "2026-10-08T17:13:18.039144Z", - "iopub.status.busy": "2026-10-08T17:13:18.039079Z", - "iopub.status.idle": "2026-10-08T17:17:45.157651Z", - "shell.execute_reply": "2026-10-08T17:17:45.157207Z" + "iopub.execute_input": "2026-11-24T16:52:18.299279Z", + "iopub.status.busy": "2026-11-24T16:52:18.298342Z", + "iopub.status.idle": "2026-11-24T17:06:45.631412Z", + "shell.execute_reply": "2026-11-24T17:06:45.630881Z" } }, "outputs": [ @@ -551,7 +552,7 @@ }, { "cell_type": "markdown", - "id": "815f8f27", + "id": "29ec0286", "metadata": {}, "source": [ "\n", diff --git a/docs/tutorials/market_sectors.mp4 b/docs/tutorials/market_sectors.mp4 index 14a08b05..6e18a0bb 100644 Binary files a/docs/tutorials/market_sectors.mp4 and b/docs/tutorials/market_sectors.mp4 differ diff --git a/docs/tutorials/weather_decades.ipynb b/docs/tutorials/weather_decades.ipynb index 47e4c320..6997459f 100644 --- a/docs/tutorials/weather_decades.ipynb +++ b/docs/tutorials/weather_decades.ipynb @@ -3,7 +3,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9c08067b", + "id": "63127a8f", "metadata": { "tags": [ "hypertools-install" @@ -31,7 +31,7 @@ }, { "cell_type": "markdown", - "id": "40dc9fca", + "id": "0e1516ac", "metadata": {}, "source": [ "# A century of weather: twenty cities as twenty features, one hot path\n", @@ -97,7 +97,7 @@ }, { "cell_type": "markdown", - "id": "2525f7c7", + "id": "1c4c6fe9", "metadata": {}, "source": [ "## 1. Imports and a disk cache\n", @@ -108,13 +108,13 @@ { "cell_type": "code", "execution_count": 1, - "id": "a4e1d0b8", + "id": "4854c29d", "metadata": { "execution": { - "iopub.execute_input": "2026-10-08T17:20:55.068559Z", - "iopub.status.busy": "2026-10-08T17:20:55.068414Z", - "iopub.status.idle": "2026-10-08T17:20:58.478508Z", - "shell.execute_reply": "2026-10-08T17:20:58.478078Z" + "iopub.execute_input": "2026-11-23T14:25:39.460496Z", + "iopub.status.busy": "2026-11-23T14:25:39.460408Z", + "iopub.status.idle": "2026-11-23T14:25:43.986897Z", + "shell.execute_reply": "2026-11-23T14:25:43.986223Z" } }, "outputs": [], @@ -151,7 +151,7 @@ }, { "cell_type": "markdown", - "id": "1acc9575", + "id": "26c48e81", "metadata": {}, "source": [ "## 2. Fetch the paper's archive and the coastlines, with fallbacks\n", @@ -162,13 +162,13 @@ { "cell_type": "code", "execution_count": 2, - "id": "2cd2b08c", + "id": "80754194", "metadata": { "execution": { - "iopub.execute_input": "2026-10-08T17:20:58.480039Z", - "iopub.status.busy": "2026-10-08T17:20:58.479904Z", - "iopub.status.idle": "2026-10-08T17:20:58.485992Z", - "shell.execute_reply": "2026-10-08T17:20:58.485627Z" + "iopub.execute_input": "2026-11-23T14:25:43.988429Z", + "iopub.status.busy": "2026-11-23T14:25:43.988224Z", + "iopub.status.idle": "2026-11-23T14:25:43.995654Z", + "shell.execute_reply": "2026-11-23T14:25:43.995056Z" } }, "outputs": [], @@ -291,7 +291,7 @@ }, { "cell_type": "markdown", - "id": "fe86efaf", + "id": "1704c486", "metadata": {}, "source": [ "## 3. One call, three panels\n", @@ -302,13 +302,13 @@ { "cell_type": "code", "execution_count": 3, - "id": "7e1f333e", + "id": "0525e195", "metadata": { "execution": { - "iopub.execute_input": "2026-10-08T17:20:58.486944Z", - "iopub.status.busy": "2026-10-08T17:20:58.486880Z", - "iopub.status.idle": "2026-10-08T17:20:58.492615Z", - "shell.execute_reply": "2026-10-08T17:20:58.492265Z" + "iopub.execute_input": "2026-11-23T14:25:43.996940Z", + "iopub.status.busy": "2026-11-23T14:25:43.996869Z", + "iopub.status.idle": "2026-11-23T14:25:44.003157Z", + "shell.execute_reply": "2026-11-23T14:25:44.002634Z" } }, "outputs": [], @@ -350,7 +350,11 @@ " # temperature through the same colormap (extremes saturate).\n", " norm = matplotlib.colors.Normalize(mean.min(), mean.max())\n", " cmap = plt.get_cmap('RdBu_r')\n", - " map_ax = fig.add_axes([0.615, 0.50, 0.38, 0.44])\n", + " # (the right edge stops at 0.985, not at the canvas edge: the time\n", + " # series below shares it, and its head marker is drawn unclipped,\n", + " # centered ON that edge at the last month, so it needs half a\n", + " # marker of canvas beyond it)\n", + " map_ax = fig.add_axes([0.615, 0.50, 0.37, 0.44])\n", " for ring in data.land:\n", " map_ax.add_patch(Polygon(ring, closed=True, facecolor='0.86',\n", " edgecolor='0.62', linewidth=0.4))\n", @@ -415,7 +419,7 @@ }, { "cell_type": "markdown", - "id": "4253a9f2", + "id": "588c8703", "metadata": {}, "source": [ "## 4. Load the data and build the animation\n" @@ -424,13 +428,13 @@ { "cell_type": "code", "execution_count": 4, - "id": "9bf479f6", + "id": "3fcdde54", "metadata": { "execution": { - "iopub.execute_input": "2026-10-08T17:20:58.493414Z", - "iopub.status.busy": "2026-10-08T17:20:58.493357Z", - "iopub.status.idle": "2026-10-08T17:20:58.804297Z", - "shell.execute_reply": "2026-10-08T17:20:58.803873Z" + "iopub.execute_input": "2026-11-23T14:25:44.004349Z", + "iopub.status.busy": "2026-11-23T14:25:44.004268Z", + "iopub.status.idle": "2026-11-23T14:25:44.427127Z", + "shell.execute_reply": "2026-11-23T14:25:44.426471Z" } }, "outputs": [ @@ -453,7 +457,7 @@ }, { "cell_type": "markdown", - "id": "5521af50", + "id": "dfb88ebf", "metadata": {}, "source": [ "## 5. Save the animation\n" @@ -462,13 +466,13 @@ { "cell_type": "code", "execution_count": 5, - "id": "c060858b", + "id": "083700d0", "metadata": { "execution": { - "iopub.execute_input": "2026-10-08T17:20:58.805633Z", - "iopub.status.busy": "2026-10-08T17:20:58.805567Z", - "iopub.status.idle": "2026-10-08T17:26:29.192813Z", - "shell.execute_reply": "2026-10-08T17:26:29.192426Z" + "iopub.execute_input": "2026-11-23T14:25:44.428512Z", + "iopub.status.busy": "2026-11-23T14:25:44.428443Z", + "iopub.status.idle": "2026-11-23T14:31:47.720859Z", + "shell.execute_reply": "2026-11-23T14:31:47.719502Z" } }, "outputs": [ @@ -496,7 +500,7 @@ }, { "cell_type": "markdown", - "id": "af774be0", + "id": "3fa69c22", "metadata": {}, "source": [ "\n", diff --git a/docs/tutorials/weather_decades.mp4 b/docs/tutorials/weather_decades.mp4 index af7cdb92..789c8422 100644 Binary files a/docs/tutorials/weather_decades.mp4 and b/docs/tutorials/weather_decades.mp4 differ diff --git a/examples/animate_market_sectors.py b/examples/animate_market_sectors.py index 6b928cec..c2e40911 100644 --- a/examples/animate_market_sectors.py +++ b/examples/animate_market_sectors.py @@ -76,7 +76,6 @@ import numpy as np import pandas as pd from matplotlib.colors import LinearSegmentedColormap, Normalize -from matplotlib.lines import Line2D import hypertools as hyp @@ -320,13 +319,15 @@ def construct_artifact(data): tail_duration=TAIL, duration=DURATION, frame_rate=FPS, rotations=ROTATIONS, colorbar=False, title=f'{months[0]:%B} {months[0].day}, {months[0].year}', + # the key is the library's own legend: one entry + # per sector color plus a gray one for the market + # path, in the top-left corner of the axes. The + # library keeps the turning cube clear of it. + legend_colors=list(zip(names, SECTOR_COLORS)) + + [('Market (average across sectors)', '#666666')], + legend_kwargs={'loc': 'upper left', 'fontsize': 8}, size=(8, 8), backend='matplotlib', show=False) ax = anim.figure.axes[0] - ax.legend(handles=[Line2D([], [], color=c, lw=2, label=s) - for s, c in zip(names, SECTOR_COLORS)] - + [Line2D([], [], color='#666666', lw=3.4, - label='Market (average across sectors)')], - loc='upper left', fontsize=8, frameon=False) def date_title(ctx): """The title is the date under the head, tinted by the basket's own diff --git a/examples/animate_weather_decades.py b/examples/animate_weather_decades.py index 924b4130..775c5cbc 100644 --- a/examples/animate_weather_decades.py +++ b/examples/animate_weather_decades.py @@ -249,7 +249,11 @@ def construct_artifact(data): # temperature through the same colormap (extremes saturate). norm = matplotlib.colors.Normalize(mean.min(), mean.max()) cmap = plt.get_cmap('RdBu_r') - map_ax = fig.add_axes([0.615, 0.50, 0.38, 0.44]) + # (the right edge stops at 0.985, not at the canvas edge: the time + # series below shares it, and its head marker is drawn unclipped, + # centered ON that edge at the last month, so it needs half a + # marker of canvas beyond it) + map_ax = fig.add_axes([0.615, 0.50, 0.37, 0.44]) for ring in data.land: map_ax.add_patch(Polygon(ring, closed=True, facecolor='0.86', edgecolor='0.62', linewidth=0.4)) diff --git a/examples/plot_datasets_tour.py b/examples/plot_datasets_tour.py index 541d5da0..94156fb8 100644 --- a/examples/plot_datasets_tour.py +++ b/examples/plot_datasets_tour.py @@ -19,8 +19,23 @@ # Code source: Contextual Dynamics Laboratory # License: MIT +import numpy as np + import hypertools as hyp + +def bechdel_numeric(df): + """The Bechdel table's numeric columns, with the dollar amounts on a + log scale. Budgets and grosses run from a few hundred dollars to three + billion: plotted as they are, a handful of blockbusters stretch the + axes and every other film is squeezed into one corner of the plot.""" + df = df.select_dtypes('number').dropna() + dollars = [name for name in df.columns + if 'budget' in name or 'gross' in name] + df[dollars] = np.log10(df[dollars]) + return df + + # Three of these four sources (seaborn, FiveThirtyEight, Kaggle) fetch over # the network at run time. So that a transient outage doesn't abort the whole # documentation-gallery build, each load is attempted independently and a @@ -34,7 +49,7 @@ ('seaborn: penguins', lambda: hyp.load('penguins'), lambda df: df.select_dtypes('number').dropna()), ('fivethirtyeight: bechdel', lambda: hyp.load('fivethirtyeight/bechdel'), - lambda df: df.select_dtypes('number').dropna()), + bechdel_numeric), ('kaggle: uciml/iris', lambda: hyp.load('kaggle/uciml/iris'), None), ] diff --git a/examples/plot_shapes_zoo.py b/examples/plot_shapes_zoo.py index 0934c9fd..395126cd 100644 --- a/examples/plot_shapes_zoo.py +++ b/examples/plot_shapes_zoo.py @@ -7,8 +7,10 @@ HyperTools ships with a "shapes zoo" of classic 3D point clouds (they download once and are then cached in `~/hypertools_data`). This example loads *every* shape in the zoo and displays each in its own panel, plotted -as small black dots (the ``,`` pixel marker), via one `hyp.plot` call with -``panels=``. +as small black dots, via one `hyp.plot` call with ``panels=``. The dense +clouds (tens of thousands of points) use the ``,`` pixel marker; the teapot, +which is the 301 control points of the Utah teapot (stored as 1,728 rows), +is drawn with the larger ``.`` marker so that it reads next to them. """ # Code source: Contextual Dynamics Laboratory @@ -19,8 +21,14 @@ # every point cloud in the shapes zoo shapes = ['bunny', 'cube', 'dragon', 'sphere', 'teapot', 'vase', 'biplane'] +clouds = [hyp.load(shape) for shape in shapes] + # small black dots: ',' is matplotlib's single-pixel marker, ideal for -# dense point clouds. panels=(2, 4) lays the seven shapes into a 2x4 grid +# dense point clouds. A sparse cloud all but vanishes at one pixel per +# point (the teapot has 1,728 rows, against 23,000 to 91,000 for the +# others), so a cloud of fewer than 5,000 points gets the '.' marker +# instead; markersize= sizes it and leaves the pixel marker alone. +# panels=(2, 4) lays the seven shapes into a 2x4 grid # (the eighth, spare cell is hidden automatically); panel_fit='independent' # fits each panel's own reduction separately, exactly as the equivalent # per-panel hyp.plot(shape, ax=ax) loop did, since these clouds differ @@ -29,7 +37,7 @@ # would write beside that one panel as axis labels; the empty labels keep # all seven panels alike. No size= is needed: the figure is sized by the # grid (3.2 in per panel each way, so 12.8 x 6.4 in here). -hyp.plot([hyp.load(shape) for shape in shapes], ',', color='k', - panels=(2, 4), panel_fit='independent', +hyp.plot(clouds, [',' if len(cloud) >= 5000 else '.' for cloud in clouds], + color='k', markersize=2.5, panels=(2, 4), panel_fit='independent', title=[shape.capitalize() for shape in shapes], xlabel='', ylabel='', zlabel='') diff --git a/hypertools/io/streaming.py b/hypertools/io/streaming.py index df7b39c5..3c83ccbb 100644 --- a/hypertools/io/streaming.py +++ b/hypertools/io/streaming.py @@ -254,11 +254,77 @@ def project(m): return model.transform(head_n), project, model +def _stream_label_source(labels): + """How a stream's samples get their labels: ``text(index, sample)`` + returning the label of the sample `index` (a string) or None for no + label, or None when `labels` asks for no labels at all. + + A stream's length is unknown, so `labels=` cannot be the one list + with an entry per observation that a static plot takes. It may be: + + - a callable ``labels(index, sample)``, called once per consumed + sample, in order, with the sample's position in the stream (from + 0) and the sample as the stream yielded it (so the label can be + read from a field of a dict sample that the numeric conversion + ignores); + - any iterable (a list, tuple, array or Series, or an iterator or + generator, which may be endless): consumed in step with the + samples, one entry per sample. When it runs out the later samples + have no label, so a list of 5 labels the first 5 samples. + + An entry (or a return value) that is None, NaN or blank draws no + label; anything else is drawn as ``str(entry)``.""" + if labels is None or labels is False: + return None + if isinstance(labels, (str, bytes)): + raise TypeError( + f'labels= for a streaming plot must be a callable ' + f'labels(index, sample), or an iterable with one entry per ' + f'sample (a list, an iterator, a generator), not the single ' + f'string {labels!r}. Wrap it in a list: labels=[{labels!r}] ' + 'labels the first sample.') + if callable(labels): + entry = labels + else: + try: + entries = iter(labels) + except TypeError: + raise TypeError( + 'labels= for a streaming plot must be a callable ' + 'labels(index, sample), or an iterable with one entry per ' + f'sample (a list, an iterator, a generator); got ' + f'{type(labels).__name__}.') from None + spent = [] + + def entry(index, sample): + """The next entry of the iterable (None once it has run out).""" + if spent: + return None + try: + return next(entries) + except StopIteration: + spent.append(True) + return None + + def text(index, sample): + """The label of the sample `index`, or None for no label.""" + value = entry(index, sample) + if value is None: + return None + if isinstance(value, (float, np.floating)) and np.isnan(value): + return None + value = str(value) + return value if value.strip() else None + + return text + + def plot_stream(stream, fmt='-', stream_init=10000, stream_chunk=100, stream_max=None, stream_window=None, ndims=3, reduce='IncrementalPCA', normalize=None, align=None, cluster=None, n_clusters=None, save_path=None, show=True, - frame_rate=30, **plot_kwargs): + frame_rate=30, labels=None, label_alpha=None, + **plot_kwargs): """Plot streaming data: fit models on the first ``stream_init`` samples, then project and draw each subsequent chunk of ``stream_chunk`` samples dynamically. Called by hyp.plot() when it detects a streaming input; @@ -298,6 +364,39 @@ def plot_stream(stream, fmt='-', stream_init=10000, stream_chunk=100, drawn as raw polylines (one vertex per sample) from the first frame on, without the interpolation/smoothing applied to static plots. + ``labels`` (see `_stream_label_source` for the forms it takes) labels + samples as they arrive. A label is attached to its sample's drawn + position (the clamped one for a sample outside the display box) and, + with ``stream_window``, removed when its sample leaves the window. + The labels are placed once per update by + `hypertools.plot.matplotlib_backend.StreamLabels`: causally (from + the updates so far), never from a clock or the number of draws, so + the same stream in the same chunks gives the same frames. The labels + drawn for every consumed sample are kept under + ``stream_info['labels']`` (None when no ``labels`` were given). + + A ``labels`` callable or iterator that raises (any ``Exception``) + for a sample ends the stream like a source error or a sample that + cannot be read, at any point: a ``RuntimeWarning`` ("streaming + stopped early") is emitted, the exception is stored unchanged under + ``stream_info['error']``, ``'truncated'`` is True, and the figure + holds every sample BEFORE the one that failed, each with its own + label (the sample that failed is not kept, and no later sample is + pulled). That holds in the middle of a chunk (the chunk's earlier + samples are drawn as a last, shorter update) and inside the first + ``stream_init`` samples (the models are fitted on the samples + before it). Only a failure on the very first sample raises out of + the call, with the original exception: there is nothing to keep. A + label is asked for only after its sample has been read, so label k + always belongs to sample k, also when the source itself dies in the + middle of a chunk. + + ``legend``, ``caption`` and ``suptitle`` (with ``legend_kwargs``, + ``legend_colors``, ``caption_kwargs`` and ``suptitle_kwargs``) are + passed on to the static plot of the head with the other + ``plot_kwargs``: they are laid out once, there, and never touched + again, which is enough because the display box is frozen. + Streamed samples need >= 2 features to span a trajectory: a single-channel stream raises ``ValueError`` (unless it ends within the head, in which case it renders like a static 1-D plot). @@ -355,6 +454,8 @@ def plot_stream(stream, fmt='-', stream_init=10000, stream_chunk=100, if save_path is not None: # fail fast on unwritable formats, BEFORE any samples are consumed save_path, save_ext = _validate_stream_save_path(save_path) + # (and a `labels=` of a kind a stream cannot use) + label_text = _stream_label_source(labels) it = iter(stream) # the head is capped by stream_max too, so the documented sample cap @@ -390,6 +491,22 @@ def plot_stream(stream, fmt='-', stream_init=10000, stream_chunk=100, if head_error is None: head_error = e head_rows = head_rows[:len(head_vecs)] + # the head samples' labels, one sample at a time: a `labels=` + # callable or iterator that raises for a head sample salvages the + # samples before it too, exactly like a bad sample (and raises out + # of the call when it fails on the very first one: nothing to keep) + texts = None + if label_text is not None: + texts = [] + try: + for i, r in enumerate(head_rows): + texts.append(label_text(i, r)) + except Exception as e: + if not texts: + raise + head_error = e + head_rows = head_rows[:len(texts)] + head_vecs = head_vecs[:len(texts)] head = np.vstack(head_vecs) if head_error is None and head.shape[1] < 2 \ @@ -421,9 +538,29 @@ def plot_stream(stream, fmt='-', stream_init=10000, stream_chunk=100, # plotly preference (Colab/Kaggle auto-detection, or # set_interactive_backend('plotly')) cannot turn this into a plotly # figure (fresh-Colab feature tour, 2026-09-11). + own_ax = plot_kwargs.get('ax') + lines_before = set(own_ax.lines) if own_ax is not None else set() fig = hyp_plot(head_red, fmt, reduce=None, normalize=None, ndims=ndims, show=False, backend='matplotlib', **plot_kwargs) - artist = next(ln for ln in fig.axes[0].lines if len(ln.get_data()[0])) + drawn = [ln for ln in (own_ax if own_ax is not None + else fig.axes[0]).lines + if ln not in lines_before and len(ln.get_data()[0])] + artist = drawn[0] + if head_red.shape[1] >= 2: + # a line-and-marker format ('-o') draws the head twice: the + # (interpolated) line, with its markers switched off + # (``markevery=[]``), and a markers-only artist at the + # observations. Only the first is updated as samples arrive, so + # the samples that streamed in had no marker at all, and the + # head's markers stayed where they were for the whole stream, + # after `stream_window` had scrolled them away as well (found + # while adding stream labels, 1.2.1). The streamed polyline has + # one vertex per sample, so it carries the markers itself. + for extra in drawn[1:]: + if extra.get_linestyle() in ('None', 'none', '', ' ') \ + and extra.get_marker() == artist.get_marker(): + extra.remove() + artist.set_markevery(None) # the axis limits and the data->box transform are FROZEN from the head: # hyp.plot centered the head (column means) and scaled it into the @@ -451,6 +588,32 @@ def to_box(pts): accum = [head_red] n_seen = len(head_rows) + # labels (`labels=`): one annotation per labeled sample, at the + # sample's drawn position, placed once per update by the one + # placement rule of every hypertools label. A 1-D stream that ended + # within the head is a static picture with nothing to update. + tracker = None + if texts is not None and head_red.shape[1] >= 2: + from ..plot.matplotlib_backend import StreamLabels + tracker = StreamLabels( + artist.axes, frame_rate=frame_rate, + label_alpha=0.5 if label_alpha is None else label_alpha) + + def _label(first, new_texts, points): + # the labels of the samples first, first + 1, ... + for k, (one, point) in enumerate(zip(new_texts, to_box(points))): + if one is not None: + tracker.add(first + k, one, point) + + _label(0, texts, head_red) + elif texts is not None and any(t is not None for t in texts): + warnings.warn( + 'labels= is not drawn for a single-feature stream that ended ' + 'within the first stream_init samples (it is drawn as a static ' + '1-D plot); materialize the stream (np.array(list(stream))) and ' + 'pass labels= to a static hyp.plot instead.', UserWarning, + stacklevel=3) + interactive = show and matplotlib.get_backend().lower() not in ( 'agg', 'pdf', 'svg', 'ps') # choose the frame-grabbing writer by extension, mirroring the @@ -497,6 +660,11 @@ def _redraw(): artist.set_data_3d(full[:, 0], full[:, 1], full[:, 2]) else: artist.set_data(full[:, 0], full[:, 1]) + if tracker is not None: + # ONE step of the labels per emitted frame (never per draw): + # the labels of samples that left the window go, the others + # are placed for this frame + tracker.step(n_seen - len(shown)) if writer is not None: writer.grab_frame() if interactive: @@ -553,12 +721,41 @@ def _consume(rows): nonlocal n_seen, clamped, post_head if not rows: return - chunk = np.vstack([row_to_vector(r) for r in rows]) + # one sample at a time: a sample that cannot be read, or whose + # label cannot be had (a `labels=` callable or iterator that + # raises), ends the stream AFTER the chunk's samples before it + # are kept and drawn. (The chunk was converted and labeled in + # one go, so one failure in its middle lost the good samples + # before it; review of the 1.2.1 stream labels.) A label is + # asked for only once its sample has been read, so label k + # always belongs to sample k. + failure = None + vecs = [] + new_texts = [] if label_text is not None else None + for k, r in enumerate(rows): + try: + vec = row_to_vector(r) + one = None if label_text is None \ + else label_text(n_seen + k, r) + except Exception as e: + failure = e + break + vecs.append(vec) + if new_texts is not None: + new_texts.append(one) + if not vecs: + raise failure + rows = rows[:len(vecs)] + chunk = np.vstack(vecs) projected = project(chunk) - # append raw only after projection succeeds, so 'data' and - # 'xform_data' always describe the same samples + # append raw only after projection succeeds, so 'data', + # 'xform_data' and 'labels' always describe the same samples raw.append(chunk) accum.append(projected) + if new_texts is not None: + texts.extend(new_texts) + if tracker is not None: + _label(n_seen, new_texts, projected) n_seen += len(rows) clamped += _n_clamped(projected) post_head += len(projected) @@ -567,6 +764,8 @@ def _consume(rows): # shorter streams _warn_if_clamped(_CLAMP_WARN_MIN_STREAMING) _redraw() + if failure is not None: + raise failure try: # `while head_error is None` (never mutated inside the loop) gates @@ -655,7 +854,13 @@ def _consume(rows): # box surface with no warning at all (1.1 visual review, L13b) _warn_if_clamped(_CLAMP_WARN_MIN_AT_END) + if tracker is not None: + # a label still on its way is put where it was going, so the + # returned figure is at rest + tracker.finish() + fig.stream_info = { + 'labels': texts, 'data': [np.vstack(raw)], 'xform_data': [np.vstack(accum)], 'n_samples': n_seen, diff --git a/hypertools/plot/backend.py b/hypertools/plot/backend.py index 54a2b882..0769866c 100644 --- a/hypertools/plot/backend.py +++ b/hypertools/plot/backend.py @@ -1432,7 +1432,9 @@ def plot_wrapper(*args, **kwargs): try: from ..predict.time import warn_once_per_call - with backend_context(tmp_backend), warn_once_per_call(): + from .matplotlib_backend import labels_held_while_plotting + with backend_context(tmp_backend), warn_once_per_call(), \ + labels_held_while_plotting(): if needs_interactive_display: _issue_backend_warning() diff --git a/hypertools/plot/hyper_animation.py b/hypertools/plot/hyper_animation.py index 1bca738e..56dfc9b0 100644 --- a/hypertools/plot/hyper_animation.py +++ b/hypertools/plot/hyper_animation.py @@ -101,7 +101,9 @@ def n_frames(self): `max(1, round(frame_rate * duration))` for parallel/serial/spin, and `sum(segment_frame_counts(...))` for a morph -- so this is exact rather than an estimate. Reading it is the supported alternative to - matplotlib's private `_save_count`. + matplotlib's private `_save_count`. The frames a ``hold=`` repeats + at the end are counted: ``round(hold * frame_rate)`` more, each + drawing the last frame again. """ return int(self[1]._save_count) @@ -134,6 +136,10 @@ def draw_frame(self, frame): f'frame {frame} is out of range; this animation has ' f'{self.n_frames} frames, so valid indices are 0 and ' f'{self.n_frames - 1}') + # the frames a `hold=` appends repeat the LAST content frame + content = getattr(self[1], '_hyp_content_frames', None) + if content is not None: + frame = min(frame, int(content) - 1) self[1]._func(frame, *self[1]._args) return self diff --git a/hypertools/plot/matplotlib_backend.py b/hypertools/plot/matplotlib_backend.py index aa650f0a..8bf52081 100644 --- a/hypertools/plot/matplotlib_backend.py +++ b/hypertools/plot/matplotlib_backend.py @@ -7,9 +7,11 @@ else here is private helpers. This module was renamed from ``draw.py`` in HyperTools 1.0 (``draw.py`` remains as a compatibility shim). """ +import contextlib import functools import itertools import warnings +import weakref import matplotlib.artist import matplotlib.colors as mcolors @@ -79,6 +81,2192 @@ def _label_callout_kwargs(label_alpha, arrowstyle='-', facecolor='white'): ) +#: where an observation label sits relative to its point, in points: up +#: and to the left, as hypertools has always drawn it +LABEL_OFFSET_PT = 20.0 + +#: the places a label can take when its box is covered by another +#: label's (`declutter_labels`): the four corners around its point and +#: the four sides, at the usual distance and at two further out +_LABEL_REACHES_PT = (LABEL_OFFSET_PT, 2.25 * LABEL_OFFSET_PT, + 3.5 * LABEL_OFFSET_PT) +_LABEL_CORNERS = ((-1, 1), (1, 1), (-1, -1), (1, -1)) +_LABEL_SIDES = ((0, 1), (0, -1), (-1, 0), (1, 0)) + +#: the place every label starts from: up and to the left of its point +_LABEL_HOME = (_LABEL_CORNERS[0], LABEL_OFFSET_PT) + +#: the clear space, in points, a label is given around its box when it is +#: moved to a new place. A label that is not moved keeps its place until +#: its box actually meets another's, so a label never sits on the border +#: between two places (it would switch on every frame of an animation). +_LABEL_CLEARANCE_PT = 3.0 + +#: a label that cannot be put clear of the others moves only to a place +#: that covers less than this share of what it covers where it is +_LABEL_MOVE_GAIN = 0.5 + +#: what covering a legend, a colorbar, a title or a figure text costs a +#: place, against covering the same area of another label +_LABEL_OBSTACLE_WEIGHT = 4.0 + +#: how many times the labels are gone through on one draw (each time only +#: the labels still covered move) +_LABEL_PASSES = 12 + +#: above this many visible labels they are left where they are: that many +#: boxes cover the plot whichever way each one points +_LABEL_DECLUTTER_MAX = 300 + + +def _label_box(anchor, size, corner, reach_px, pad_px): + """The display box (x0, y0, x1, y1), its round frame included, of a + label of text `size` attached to the point `anchor` on the `corner` + side (``(-1, 1)`` is up and to the left, ``(0, 1)`` straight up) at + `reach_px`.""" + (px, py), (w, h), (sx, sy) = anchor, size, corner + x0 = px + sx * reach_px - (w if sx < 0 else 0.5 * w if sx == 0 else 0.0) + y0 = py + sy * reach_px - (h if sy < 0 else 0.5 * h if sy == 0 else 0.0) + return (x0 - pad_px, y0 - pad_px, x0 + w + pad_px, y0 + h + pad_px) + + +def _covered_area(box, others): + """The area of `box` (x0, y0, x1, y1) that the boxes `others` (an + ``(n, 4)`` array) cover, summed over them. `box` may also be an + ``(m, 4)`` array of boxes: the result is then one area per box.""" + box = np.asarray(box, dtype=float) + if not len(others): + return 0.0 if box.ndim == 1 else np.zeros(len(box)) + if box.ndim == 1: + wide = (np.minimum(box[2], others[:, 2]) + - np.maximum(box[0], others[:, 0])) + tall = (np.minimum(box[3], others[:, 3]) + - np.maximum(box[1], others[:, 1])) + area = np.clip(wide, 0, None) * np.clip(tall, 0, None) + return float(np.nansum(area)) + wide = (np.minimum(box[:, None, 2], others[None, :, 2]) + - np.maximum(box[:, None, 0], others[None, :, 0])) + tall = (np.minimum(box[:, None, 3], others[None, :, 3]) + - np.maximum(box[:, None, 1], others[None, :, 1])) + return np.nansum( + np.clip(wide, 0, None) * np.clip(tall, 0, None), axis=1) + + +#: the resolution every label is measured at (`_label_size_pt`), and the +#: renderer that measures: hypertools' own figures are made at 100 dpi, +#: so this is what the screen and a default `savefig` draw +_LABEL_METRICS_DPI = 100.0 +_LABEL_METRICS_RENDERER = [] + + +def _label_size_pt(label): + """The width and height of `label`'s text, in points, whatever is + drawing it. + + Measured with matplotlib's own layout of the text (line breaks, line + spacing, mathtext) on ONE renderer at ONE resolution + (`_LABEL_METRICS_DPI`) instead of the renderer of the draw: Agg fits + glyphs to the pixel grid, so the same text is a slightly different + size at every dpi (and PDF and SVG measure it a third way), and a + placement made from those sizes was a different arrangement on the + screen, in a 300 dpi PNG and in a PDF. At the default 100 dpi the + size is exactly the one drawn; a text is a little larger there than + at a higher resolution or in a vector file, so boxes that are clear + of each other here are clear there.""" + import matplotlib.text as mtext + # everything the extent of the drawn text depends on: a label turned + # on its side (`set_rotation(90)`) or switched to plain text + # (`set_parse_math(False)`) after it was first measured kept its old + # size, so labels that now covered each other were left where they + # were (1.2.1 review round 3). A wrapped text is laid out against + # the figure it is in, so its size is measured every time. (The + # alignment is not part of it: it moves the text, which is how a + # label is put at its place, and leaves its size alone.) + key = (label.get_text(), hash(label.get_fontproperties()), + label._linespacing, label.get_usetex(), label.get_parse_math(), + label.get_rotation(), label.get_rotation_mode(), + label.get_transform_rotates_text()) + if label.get_wrap(): + key = None + known = getattr(label, '_hyp_size_pt', None) + if key is not None and known is not None and known[0] == key: + return known[1] + if not _LABEL_METRICS_RENDERER: + from matplotlib.backends.backend_agg import RendererAgg + _LABEL_METRICS_RENDERER.append( + RendererAgg(1, 1, _LABEL_METRICS_DPI)) + own_renderer, shown = label._renderer, label.get_visible() + try: + # (a hidden text has no extent; visibility is put back below + # without marking the figure as changed) + label._visible = True + # (`dpi=`: matplotlib 3.11 lays a text out at its FIGURE's + # resolution whatever renderer it is given, so without it the + # size was that of the save in progress, another at every dpi, + # and the arrangement with it; 3.10 took the renderer's) + box = mtext.Text.get_window_extent( + label, _LABEL_METRICS_RENDERER[0], dpi=_LABEL_METRICS_DPI) + to_pt = 72.0 / _LABEL_METRICS_DPI + size = (float(box.width) * to_pt, float(box.height) * to_pt) + finally: + label._visible = shown + label._renderer = own_renderer + label._hyp_size_pt = (key, size) + return size + + +def _label_user_placed(label): + """Whether `label` is no longer where hypertools put it: moved by the + reader (2-D labels can be dragged) or by the caller's own code. It is + theirs from then on.""" + if getattr(label, '_hyp_user_placed', False): + return True + ours = getattr(label, '_hyp_offset', None) + if ours is None: + return False + x, y = label.xyann + if abs(x - ours[0]) > 1e-6 or abs(y - ours[1]) > 1e-6: + label._hyp_user_placed = True + return True + return False + + +#: how many `plot()` calls are running (`labels_held_while_plotting`) +_PLOTTING = [0] + + +@contextlib.contextmanager +def labels_held_while_plotting(): + """For the time of one `plot()` call: the labels an axes was just + given stay at their usual places until the call has finished its + figure (`reset_label_places` at the end of `plot()` releases them). + + `plot()` draws the figure several times while it lays it out, and + each of those draws used to arrange the labels for a layout that was + about to change, only for the arrangement to be undone at the end: + with 300 labels a quarter of the call's time (1.2.1 review round 2). + Held, the layout is also measured with the labels where 1.2.0 had + them. Outside a `plot()` call nothing is ever held, so a figure that + for any reason left `plot()` unreleased is still arranged when it is + drawn.""" + _PLOTTING[0] += 1 + try: + yield + finally: + _PLOTTING[0] -= 1 + + +def _label_entries(ax): + """The ``(annotation, x, y[, z])`` entries of every label hypertools + has drawn into `ax` and that is still there.""" + return [entry for entry in + (getattr(ax, '_hyp_labels_and_points', None) or []) + if entry[0].axes is ax] + + +def axis_text_boxes_px(ax, renderer=None): + """The boxes ``(x0, y0, x1, y1)``, in pixels, of every axis label + and tick label the 3-D axes `ax` draws at its current view: an + ``(n, 4)`` array (empty for a 2-D axes, whose axis texts lie outside + the plot, and for a cube that draws none). + + matplotlib decides where these texts go while it draws the axis + (which edge of the cube a label hangs from changes as the cube + turns). During a draw of the figure (`renderer` given) the axes has + just drawn them, so they are read where they are; otherwise the + three axes alone are drawn onto the figure's renderer first, about + a hundredth of what drawing the figure costs, which is what lets + EVERY frame's view of an animation be measured.""" + if not hasattr(ax, 'get_proj') or not getattr(ax, '_axis3don', True): + return np.zeros((0, 4)) + texts = [] + for axis3d in ax._axis_map.values(): + texts.extend( + text for text in [axis3d.label] + [ + tick.label1 for tick in axis3d.get_major_ticks()] + if text.get_visible() and text.get_text().strip()) + if not texts: + return np.zeros((0, 4)) + if renderer is None: + renderer = ax.get_figure(root=True)._get_renderer() + ax.apply_aspect() + # (what `Axes3D.draw` sets up before it draws its axes) + ax.M = ax.get_proj() + ax.invM = np.linalg.inv(ax.M) + for axis3d in ax._axis_map.values(): + axis3d.draw(renderer) + boxes = [text.get_window_extent(renderer).extents for text in texts] + return np.array([box for box in boxes if np.all(np.isfinite(box))], + dtype=float).reshape(-1, 4) + + +def _whole_points(boxes_px, origin, to_pt): + """Pixel boxes as boxes in points from `origin`, widened to whole + points.""" + boxes = (np.asarray(boxes_px, dtype=float).reshape(-1, 4) + - (origin[0], origin[1], origin[0], origin[1])) * to_pt + boxes[:, :2] = np.floor(boxes[:, :2]) + boxes[:, 2:] = np.ceil(boxes[:, 2:]) + return boxes + + +def _label_obstacles_pt(ax, renderer, origin, to_pt, axis_text=True): + """The boxes, in points from the canvas's bottom-left corner, of + everything in the figure of `ax` that an observation label must not + be put on: every legend (the axes' own and the figure's, such as the + one shared legend of a `panels=` grid), every colorbar with its tick + labels, every panel's title, and every figure text (`suptitle=`, + `caption=`, a caller's own ``fig.text``). An ``(n, 4)`` array. + + 1.2.1 review round 5 added two things. Every OTHER axes of the + figure (the next panel of a grid, a companion panel): a label that + reached into the next panel was painted over by that panel's + background, cut off at its edge. And, with `axis_text`, the axis + labels and tick labels of a 3-D axes' own cube + (`axis_text_boxes_px`), which hang where the labels of points near + the cube's edges want to go. + + 1.2.1 review round 4: the labels were only kept off each other, so a + label moved out of another label's way could land on the legend + (which the labels of 1.2.0, all at one fixed offset the layout had + made room for, never did) or on a title. + + Each box is measured where the figure shows it now (no draw is made: + a legend and a text know their extent from the figure's layout) and + then widened to whole points, so the small differences between how + one renderer and another measures the same text almost never change + which places are free.""" + fig = ax.get_figure(root=True) + if renderer is None: + renderer = fig._get_renderer() + found = [] + + def _add(artist, tight=False): + if artist is None or not artist.get_visible(): + return + try: + box = (artist.get_tightbbox(renderer) if tight + else artist.get_window_extent(renderer)) + except Exception: # noqa: BLE001 - an artist that cannot be measured is no obstacle + return + if box is None or not np.all(np.isfinite(box.extents)) \ + or box.width <= 0 or box.height <= 0: + return + found.append(box.extents) + + for legend in fig.legends: + _add(legend) + for text in fig.texts: + if text.get_text().strip(): + _add(text) + for other in fig.axes: + if not other.get_visible(): + continue + _add(other.get_legend()) + for title in (other.title, getattr(other, '_left_title', None), + getattr(other, '_right_title', None)): + if title is not None and title.get_text().strip(): + _add(title) + if other is not ax and hasattr(other, '_colorbar'): + _add(other, tight=True) + elif other is not ax: + _add(other) + if axis_text: + found.extend(axis_text_boxes_px(ax, renderer)) + if not found: + return np.zeros((0, 4)) + return _whole_points(found, origin, to_pt) + + +def _label_geometry(ax, labels): + """What the labels `labels` of `ax` are placed from, all in POINTS + from the bottom-left corner of the canvas the figure was made for: + ``(origin, to_pt, canvas, anchors)``. `origin` is that corner in + display pixels, `to_pt` the points in a pixel, `canvas` the box + ``(0, 0, width, height)`` and `anchors` the ``(n, 2)`` positions of + the labels' points as the axes shows them now.""" + fig = ax.get_figure(root=True) + to_pt = 72.0 / fig.dpi + # the canvas the figure was made for: the unit square of the figure + # (a `bbox_inches='tight'` save moves the origin and crops, and the + # labels must not be arranged for the crop) + (left, bottom), (right, top) = fig.transFigure.transform( + [(0.0, 0.0), (1.0, 1.0)]) + canvas = (0.0, 0.0, round((right - left) * to_pt, 4), + round((top - bottom) * to_pt, 4)) + if not labels: + return (left, bottom), to_pt, canvas, np.zeros((0, 2)) + anchors = np.round( + (ax.transData.transform(np.array([label.xy for label in labels], + dtype=float)) + - (left, bottom)) * to_pt, 4) + return (left, bottom), to_pt, canvas, anchors + + +def _label_pads_pt(labels): + """How far each label's round frame reaches beyond its text, in + points.""" + return np.array([ + (getattr(frame.get_boxstyle(), 'pad', 0.0) if frame else 0.0) + * label.get_size() + for label, frame in ((label, label.get_bbox_patch()) + for label in labels)], dtype=float) + + +def _settle_axes_for_labels(ax): + """With no draw going on, bring `ax` to the state a draw would give + it (pending autoscaling, the box an aspect ratio leaves), so its + data transform is the one the picture is drawn with.""" + ax.get_xlim(), ax.get_ylim() + locator = ax.get_axes_locator() + ax.apply_aspect(locator(ax, None) if locator else None) + + +def _project_label_anchors(ax, entries): + """Point every visible 3-D label of `entries` at its point where the + camera and the box zoom of `ax` put it NOW (a projection kept from an + earlier layout or zoom left the arrow pointing at nothing).""" + if not hasattr(ax, 'get_proj'): + return + from mpl_toolkits.mplot3d import proj3d + proj = ax.get_proj() + for entry in entries: + if len(entry) == 4 and entry[0].get_visible(): + x2, y2, _ = proj3d.proj_transform( + entry[1], entry[2], entry[3], proj) + entry[0].xy = (x2, y2) + + +#: every place a label can take, nearest first, and each place's reach +_LABEL_CANDIDATES = tuple((corner, reach) for reach in _LABEL_REACHES_PT + for corner in _LABEL_CORNERS + _LABEL_SIDES) + + +def _arrange_labels(places, left, anchors, sizes, pads, canvas, obstacles, + strict=False, held=None, barred=None, fresh=None): + """THE placement rule of observation labels, for one view: given + where each label hangs now (`places`, a list of ``(corner, reach)``) + and the place each one last left (`left`), move the labels that are + covered and leave the others. Both lists are changed in place. + Returns whether the labels came to rest. + + `anchors`, `sizes` and `pads` are ``(n, 2)``, ``(n, 2)`` and ``(n,)`` + arrays in points (`_label_geometry`, `_label_size_pt`, + `_label_pads_pt`), `canvas` the canvas box and `obstacles` the + ``(m, 4)`` boxes no label may be put on (`_label_obstacles_pt`). + + A label stays where it is unless an earlier label's box is on its + own, it lies on an obstacle, or a place it was moved to has left the + canvas. A label that must move takes, of the places around its point + (`_LABEL_CANDIDATES`), the one that covers least; of equals the one + at the shortest distance from its point, then not the place it last + left, then the one its box travels least to reach. With no clear + place it moves only to one that at least halves what it covers + (`_LABEL_MOVE_GAIN`). + + `declutter_labels` calls it for a static figure, from the places + the labels hang at. `solve_label_tracks` calls it to place a single + frame of an animation as a still would be placed, with `strict`: + a label at its usual place that reaches off the canvas moves too + (in a static figure the layout has made room for the usual places, + and such a label stays where it has always been). + + A STREAM's labels (`StreamLabels`) are placed by it once per update, + from the places the update before left them at, with two more rules + that only a picture with a past needs. `held` (one flag per label) + names the labels that are not looked at this time: a label still on + its way to a place, or resting at one it has just reached. `barred` + (one flag per label) says that the place the label last left + (`left`) is too recent to go back to: it is taken only when no other + place is clear. `fresh` (one flag per label) names the labels that + have not been drawn yet: such a label takes its usual place only + with the clear space a moved label is given (`_LABEL_CLEARANCE_PT`) + round it, since nothing is lost by starting it somewhere else (a + label that is already shown stays until its box is actually met, so + that it does not move for nothing).""" + count = len(places) + gap = _LABEL_CLEARANCE_PT + candidates = _LABEL_CANDIDATES + reaches = np.array([reach for _corner, reach in candidates]) + finite = np.all(np.isfinite(anchors), axis=1) + boxes = np.full((count, 4), np.nan) + for k in range(count): + if finite[k]: + corner, reach = places[k] + boxes[k] = _label_box(anchors[k], sizes[k], corner, reach, + pads[k]) + + def _off_canvas(box): + return (box[0] < canvas[0] or box[1] < canvas[1] + or box[2] > canvas[2] or box[3] > canvas[3]) + + def _area(box): + return (box[2] - box[0]) * (box[3] - box[1]) + + def _may_stay(k, here, on_obstacle): + if fresh is not None and fresh[k]: + roomy = here + (-gap, -gap, gap, gap) + if _covered_area(roomy, boxes[:k]) > 0.0 \ + or _covered_area(roomy, obstacles) > 0.0: + return False + return (_covered_area(here, boxes[:k]) <= 0.0 + and on_obstacle <= 0.0 + and ((places[k] == _LABEL_HOME and not strict) + or not _off_canvas(here))) + + def _all_at_rest(): + """Whether no label has a reason to move (every label looked at + in one go: most views of an animation leave every label where + it is).""" + with np.errstate(invalid='ignore'): + wide = (np.minimum(boxes[:, None, 2], boxes[None, :, 2]) + - np.maximum(boxes[:, None, 0], boxes[None, :, 0])) + tall = (np.minimum(boxes[:, None, 3], boxes[None, :, 3]) + - np.maximum(boxes[:, None, 1], boxes[None, :, 1])) + meet = (wide > 0) & (tall > 0) + if np.tril(meet, -1).any(): + return False + if len(obstacles) and np.any( + _covered_area(boxes, obstacles) > 0.0): + return False + off = ((boxes[:, 0] < canvas[0]) | (boxes[:, 1] < canvas[1]) + | (boxes[:, 2] > canvas[2]) | (boxes[:, 3] > canvas[3])) + if not strict: + off &= np.array([place != _LABEL_HOME for place in places]) + return not off.any() + + if not (fresh is not None and any(fresh)) and _all_at_rest(): + return True + + #: per label, the boxes of its candidate places with their clearance + #: (worked out when the label first has to move) + rooms = {} + + # (a label that moves frees the place it leaves and takes another, so + # the labels are gone through until none of them moves. A label only + # ever moves for a label given before it, so this ends.) + settled = False + #: how many moves have been made, and per label that count when it + #: was last looked at and left where it is: nothing has changed for + #: it since, so looking again would find the same + moves, stayed_at = 0, {} + for _ in range(_LABEL_PASSES): + moved = False + for k in range(count): + if not finite[k] or stayed_at.get(k) == moves \ + or (held is not None and held[k]): + continue + anchor, size, pad = anchors[k], sizes[k], pads[k] + here = boxes[k].copy() + place = places[k] + # it stays unless an earlier label's box is on its own, it is + # on a legend, a colorbar or a title (`obstacles`), or a + # place it was moved to has since left the canvas (in its + # usual place a static figure's label at the canvas edge + # stays where it has always been) + on_obstacle = _covered_area(here, obstacles) + if _may_stay(k, here, on_obstacle): + stayed_at[k] = moves + continue + if k not in rooms: + roomy = np.array([ + _label_box(anchor, size, corner, reach, pad + gap) + for corner, reach in candidates]) + rooms[k] = (roomy, ( + (roomy[:, 0] < canvas[0]) | (roomy[:, 1] < canvas[1]) + | (roomy[:, 2] > canvas[2]) | (roomy[:, 3] > canvas[3])) + * (roomy[:, 2] - roomy[:, 0]) + * (roomy[:, 3] - roomy[:, 1])) + roomy, off_cost = rooms[k] + # (every label but this one: its own row is blanked for the + # sums, which skip NaN) + boxes[k] = np.nan + # a place off the canvas, or on a legend, a colorbar or a + # title, only as a last resort: it costs the label's whole + # box on top of what it covers there, so a label that lies on + # another label does not get out of its way onto a title + # (where every label hangs at first, the layout has made + # room for it) + cost_here = _covered_area(here, boxes) + ( + _area(here) if _off_canvas(here) else 0.0) + ( + _LABEL_OBSTACLE_WEIGHT * on_obstacle + _area(here) + if on_obstacle > 0.0 else 0.0) + on_obstacles = _covered_area(roomy, obstacles) + costs = (_covered_area(roomy, boxes) + off_cost + + _LABEL_OBSTACLE_WEIGHT * on_obstacles + + (on_obstacles > 0.0) * (roomy[:, 2] - roomy[:, 0]) + * (roomy[:, 3] - roomy[:, 1])) + boxes[k] = here + # a short arrow before a long one, and at that distance the + # smallest change: the place the box travels least to reach + change = np.hypot( + 0.5 * (roomy[:, 0] + roomy[:, 2]) - 0.5 * (here[0] + here[2]), + 0.5 * (roomy[:, 1] + roomy[:, 3]) - 0.5 * (here[1] + here[3])) + # (the place it last left comes after the others at that + # distance: a label pushed out of one place and then out of + # the next does not hop straight back) + back = np.array([one == left[k] for one in candidates]) + open_places = np.array([one != place for one in candidates]) + # the best place: least covered, then nearest reach, then + # not the place just left, then the smallest change (the + # first of equals, in the order of `candidates`) + # (a stream's label that left a place a moment ago: any + # other place as clear comes first, however far out) + shut = back if barred is not None and barred[k] \ + else np.zeros(len(candidates), dtype=bool) + order = np.lexsort((change, back, reaches, shut, costs)) + best = int(order[open_places[order]][0]) + cost = float(costs[best]) + if cost > 0.0 and cost >= _LABEL_MOVE_GAIN * cost_here: + stayed_at[k] = moves + continue + corner, reach = candidates[best] + left[k] = place + places[k] = (corner, reach) + boxes[k] = _label_box(anchor, size, corner, reach, pad) + moved = True + moves += 1 + if not moved: + settled = True + break + return settled + + +def declutter_labels(ax, renderer=None): + """Keep the observation labels of `ax` (`labels=`) off each other. + + Every label starts up and to the left of its point, so the labels of + two points that are close on screen were drawn on top of each other + (GH #297: "Subject 1" over "Subject 2" in `examples/plot_labels.py`). + + The labels are kept off the figure's furniture as well: its + legends, colorbars, titles, suptitle and caption + (`_label_obstacles_pt`; 1.2.1 review round 4). A label lying on one + of them moves like a label lying on an earlier label, a place that + covers one of them is taken only as a last resort (it costs the + label's whole box and `_LABEL_OBSTACLE_WEIGHT` times what it covers + there, as a place off the canvas costs the whole box), and this + also holds for an axes with a single label. + + The placement (`_arrange_labels`) is STABLE: a label stays where it + is for as long as its box is clear of the labels given before it, so + a label that covers nothing is never touched and a figure whose + labels were clear of each other is drawn exactly as before. Only a + label whose box is covered by an earlier label's moves (or one that + was moved and has since left the canvas), and it moves as little as + it can: of the places around its point (four corners and four sides, + at three distances) that are clear of every other label and on the + canvas, it takes one at the shortest distance from its point, and of + those the one nearest to where it is; with no clear place, a place + that at least halves what it covers, or else it stays. A moved label + is given `_LABEL_CLEARANCE_PT` of room and does not go back when its + old place becomes free, so as a 3-D plot is turned by hand a label + changes place only when the points themselves have moved onto each + other. + + What a draw does therefore depends on where the labels were, which + suits a figure the reader turns by hand and nothing else. So the + state is pinned wherever a picture must be reproducible: + `reset_label_places` puts the labels back at the start when `plot()` + has finished a STATIC figure, so the same call always saves the same + picture; and an ANIMATED plot's labels follow a table worked out for + the whole animation, frame 0 to the last frame in order, by the same + rule (`solve_label_tracks`): frame `i` shows row `i` of it, so a + frame is the same picture whatever was drawn before it, and every + frame's labels are placed for that frame's own view. + + Everything is worked out in POINTS, from the figure itself and not + from the renderer of the draw (1.2.1 review round 2): the anchors + and the canvas are the figure's own geometry divided by its dpi, and + a label's size is `_label_size_pt`. The same figure is therefore + arranged the same way on the screen, in a PNG at any dpi, in a PDF + and in an SVG; only a change of the figure itself (its size, its + layout, the camera, the labels) can change the arrangement. For the + same reason a draw of a figure in which nothing has moved since the + last one does not place anything again (the last problem and its + answer are kept on the axes), and the labels are gone through until + none of them moves, so a second draw has nothing left to do. + + It runs at draw time (`_LabelDeclutter`), which is the one path for a + static figure, a figure the reader rotates, and a frame of an + animation. The anchor of a 3-D label is projected here as well, with + the camera and the box zoom of this very draw. + """ + entries = _label_entries(ax) + if not entries: + return + if renderer is None: + _settle_axes_for_labels(ax) + _project_label_anchors(ax, entries) + if label_tracks(ax) is not None: + # an animation's labels: the row of its table for the frame the + # axes shows (`solve_label_tracks`) + _apply_label_tracks(ax) + return + if renderer is not None and _PLOTTING[0] and getattr( + ax, '_hyp_labels_held', False): + # `plot()` is still laying the figure out + # (`labels_held_while_plotting`) + return + # (a hidden label keeps its place and is no obstacle while hidden: a + # 3-D plot's labels are hidden while the reader drags it round, and + # they come back where they were unless their points have met) + # (and a label an animation's plan placed stays where the plan had + # it when the animation is gone: a figure read back from a pickle, + # a copy of the figure) + labels = [entry[0] for entry in entries + if entry[0].get_visible() and not _label_user_placed(entry[0]) + and not _label_planned(entry[0])] + if len(labels) > _LABEL_DECLUTTER_MAX: + for label in labels: + _send_label_home(label) + return + if not labels: + return + origin, to_pt, canvas, anchors = _label_geometry(ax, labels) + sizes = np.array([_label_size_pt(label) for label in labels]) + pads = _label_pads_pt(labels) + # what no label may be put on: legends, colorbars, titles, the + # figure's suptitle and caption (1.2.1 review round 4) + obstacles = _label_obstacles_pt(ax, renderer, origin, to_pt) + if len(labels) < 2 and not len(obstacles): + return + # the same problem as on the last draw: nothing to work out again + problem = (tuple(map(id, labels)), anchors.tobytes(), sizes.tobytes(), + pads.tobytes(), canvas, obstacles.tobytes()) + start = tuple((_label_place(label), + getattr(label, '_hyp_place_left', None)) + for label in labels) + known = getattr(ax, '_hyp_label_answer', None) + if known is not None and known['problem'] == problem: + if start == known['end'] and known['settled']: + return + if start == known['start']: + for label, (place, left_place) in zip(labels, known['end']): + _set_label_place(label, *place) + label._hyp_place_left = left_place + return + places = [place for place, _left in start] + left = [left_place for _place, left_place in start] + settled = _arrange_labels(places, left, anchors, sizes, pads, canvas, + obstacles) + for label, was, place, left_place in zip(labels, start, places, left): + if place != was[0]: + label._hyp_place_left = left_place + _set_label_place(label, *place) + ax._hyp_label_answer = { + 'problem': problem, 'start': start, 'settled': settled, + 'end': tuple((_label_place(label), + getattr(label, '_hyp_place_left', None)) + for label in labels)} + + +def _label_place(label): + """Where `label` hangs: ``(corner, reach in points)``.""" + return getattr(label, '_hyp_place', _LABEL_HOME) + + +def _label_planned(label): + """Whether `label` is where an animation's plan put it + (`_set_label_offset`): anywhere between two named places, so it has + no place of its own for a static figure's rule to start from.""" + return getattr(label, '_hyp_place', _LABEL_HOME) is None + + +def _send_label_home(label): + """Put `label` back where every label starts, as if never moved.""" + label._hyp_place_left = None + _set_label_place(label, *_LABEL_HOME) + + +def _set_label_place(label, corner, reach_pt): + """Hang `label` on the `corner` side of its point, `reach_pt` away.""" + if _label_place(label) == (corner, reach_pt) and hasattr( + label, '_hyp_place'): + return + sx, sy = corner + label.set_position((sx * reach_pt, sy * reach_pt)) + label.set_ha('right' if sx < 0 else 'left' if sx > 0 else 'center') + label.set_va('bottom' if sy > 0 else 'top' if sy < 0 else 'center') + label._hyp_offset = (sx * reach_pt, sy * reach_pt) + label._hyp_place = (corner, reach_pt) + + +def reset_label_places(target): + """Put the observation labels of `target` (an axes, or a figure: all + of its axes) back up and to the left of their points, where + `declutter_labels` starts from on the next draw. A label the reader + or the caller moved is left alone, and so are an animation's labels, + which follow their table (`solve_label_tracks`).""" + axes = [target] if hasattr(target, 'transData') else list(target.axes) + for ax in axes: + if getattr(ax, '_hyp_labels_held', False): + # the figure is finished: its next draw arranges the labels + ax._hyp_labels_held = False + ax.stale = True + if label_tracks(ax) is not None: + continue + for entry in _label_entries(ax): + if not _label_user_placed(entry[0]) \ + and not _label_planned(entry[0]): + _send_label_home(entry[0]) + + +#: the ``(label, x, y[, z])`` entries of the most recently annotated +#: plot (`_publish_labels`); each label is a weak proxy, usable while +#: its figure lives +labels_and_points = [] + + +def _publish_labels(entries): + """Show `entries`, one call's ``(label, x, y[, z])`` list, as the + module's `labels_and_points`, without keeping the labels alive.""" + global labels_and_points + labels_and_points = [(weakref.proxy(entry[0]),) + tuple(entry[1:]) + for entry in entries] + + +class _LabelState: + """What an animated axes' labels follow: `frames`, how to show any + frame (`track_labels`; the frame function is held WEAKLY: it + belongs to the animation, and refers to the axes); `tracks`, the + table worked out from it (`solve_label_tracks`); `frame`, the frame + the axes shows; `solving`, set while the table is being worked out; + and, for `_apply_label_tracks`, how many frames have been shown + (`shows`), at which of them the table was last worked out again + because the figure had changed (`solved_at`), on how many frames + in a row it has changed (`streak`), and whether a change is still + waiting to be planned for (`pending`).""" + + def __init__(self): + self.frames = self.tracks = None + self.frame, self.solving = 0, False + self.shows, self.solved_at, self.pending = 0, -10, False + self.streak = 0 + + +#: per animated axes, its `_LabelState`. Kept here and not on the axes: +#: a figure is pickled and copied without it (a figure read back from a +#: pickle has no animation to follow; its labels stay where the pickled +#: frame had them, `_label_planned`). Nothing in a state refers to its +#: axes strongly (the labels and the frame function are weak +#: references), so a closed figure and its table are freed. +_LABEL_STATES = weakref.WeakKeyDictionary() + + +def _label_state(ax): + """The `_LabelState` of `ax` (a new, empty one if it has none).""" + state = _LABEL_STATES.get(ax) + if state is None: + state = _LABEL_STATES[ax] = _LabelState() + return state + + +def label_tracks(ax): + """The table the labels of the animated axes `ax` follow + (`solve_label_tracks`), or None for an axes whose labels are placed + when it is drawn (every static figure).""" + state = _LABEL_STATES.get(ax) + return None if state is None else state.tracks + + +def tracks_labels(ax): + """Whether `ax` holds an animation's labels (`track_labels`).""" + state = _LABEL_STATES.get(ax) + return state is not None and state.frames is not None + + +def forget_label_tracks(ax): + """Drop the table of `ax` and what it was made from: its labels are + placed when it is drawn from now on.""" + _LABEL_STATES.pop(ax, None) + + +#: how long a label of an animation takes to go from one place to the +#: next, in seconds (`_ease_label_tracks`), and the fewest and the most +#: frames that may take +_LABEL_EASE_SECONDS = 0.35 +_LABEL_EASE_FRAMES = (5, 15) + +#: the places a label of an ANIMATION can take: the eight directions of +#: a static figure's label and, further out than the usual distance, the +#: eight between them, at more distances (an animation's label is placed +#: for many views at once, and the blank canvas round the cube is where +#: a label can stay through all of them) +_LABEL_TRACK_REACHES_PT = (LABEL_OFFSET_PT, 2.25 * LABEL_OFFSET_PT, + 3.5 * LABEL_OFFSET_PT, 5.0 * LABEL_OFFSET_PT, + 6.5 * LABEL_OFFSET_PT) +_LABEL_TRACK_BETWEEN = tuple( + (round(float(np.cos(turn)), 6), round(float(np.sin(turn)), 6)) + for turn in np.deg2rad(22.5 + 45.0 * np.arange(8))) +_LABEL_TRACK_CANDIDATES = tuple( + (corner, reach) for reach in _LABEL_TRACK_REACHES_PT + for corner in _LABEL_CORNERS + _LABEL_SIDES + + (_LABEL_TRACK_BETWEEN if reach > LABEL_OFFSET_PT else ())) + +#: what a frame at a place costs an animation's label +#: (`_plan_label_places`), in the units of `_LABEL_TRACK_SWITCH`, one +#: change of place: lying off the canvas or on static content, lying on +#: another label (each plus the covered share of the box), and, per +#: second, hanging one usual distance further out than usual +_LABEL_TRACK_OFF = 1e7 +_LABEL_TRACK_COVERED = 1e3 +_LABEL_TRACK_FAR_PER_SECOND = 0.4 +_LABEL_TRACK_SWITCH = 3.0 +#: and what each usual distance a change of place carries the label over +#: adds to it +_LABEL_TRACK_MOVE = 0.5 +#: the longest way, in points, one change of place may carry a label +_LABEL_TRACK_MOVE_MAX_PT = 240.0 +#: per second, what pointing straight into the cloud of labeled points +#: costs a label (its leader line then crosses the cloud and the other +#: labels' lines); pointing straight out of it costs nothing +_LABEL_TRACK_INWARD_PER_SECOND = 1.0 + +#: for how many glides' worth of frames a label of an animation stays at +#: a place it has moved to before it may move again: one glide to get +#: there, and then two of standing still, so no label goes out and +#: straight back +_LABEL_REST_EASES = 3 + +#: the clear space, in points, a label of an animation is given round its +#: box at a place it rests at (less than a static figure's +#: `_LABEL_CLEARANCE_PT`: a planned label cannot switch back and forth on +#: the border between two places, and room is scarcer over many views) +_LABEL_TRACK_CLEARANCE_PT = 1.0 + +#: how many times a label of an animation is planned again because a +#: glide of its plan crossed another label +_LABEL_TRACK_REPLANS = 4 + +#: how many times the labels that are not clear on every frame, and the +#: labels they lie on, are planned again among all the others +_LABEL_TRACK_ROUNDS = 3 + +#: how many labels x frames of an animation are planned frame by frame. +#: A longer animation is planned at evenly spaced frames, that many +#: over its labels and at least `_LABEL_TRACK_KEYS_MIN`, and its labels +#: move evenly from one planned frame to the next: the plan then takes +#: no longer, and its table is no larger (28 bytes a label and planned +#: frame: about 0.1 MB at the budget, 0.4 MB for 300 labels), however +#: long the animation is +_LABEL_TRACK_BUDGET = 3600 +_LABEL_TRACK_KEYS_MIN = 40 + + +def _label_center_offsets(place_index, sizes, candidates=None): + """Where the MIDDLE of each label's text is, in points from its + point, at the places `place_index` (indices into `candidates`, by + default a static figure's `_LABEL_CANDIDATES`; any shape ending in + the labels' axis) for labels of the text sizes `sizes` ``(n, 2)``.""" + candidates = _LABEL_CANDIDATES if candidates is None else candidates + corners = np.array([corner for corner, _reach in candidates], + dtype=float) + reaches = np.array([reach for _corner, reach in candidates]) + return corners[place_index] * (reaches[place_index][..., None] + + 0.5 * sizes) + + +def _boxes_meet(boxes, others): + """Per box of `boxes` ``(..., 4)``: how many boxes of `others` + (``(m, 4)``, or ``(..., m, 4)`` with a set of boxes for each leading + index of `boxes`) it overlaps, plus the share of its own area they cover + (0.0 for a box that is clear; NaN boxes meet nothing).""" + boxes = np.asarray(boxes, dtype=float) + if not np.shape(others)[-2]: + return np.zeros(boxes.shape[:-1]) + with np.errstate(invalid='ignore', divide='ignore'): + wide = (np.minimum(boxes[..., None, 2], others[..., 2]) + - np.maximum(boxes[..., None, 0], others[..., 0])) + tall = (np.minimum(boxes[..., None, 3], others[..., 3]) + - np.maximum(boxes[..., None, 1], others[..., 1])) + hit = (wide > 0) & (tall > 0) + area = np.where(hit, wide * tall, 0.0).sum(axis=-1) + own = ((boxes[..., 2] - boxes[..., 0]) + * (boxes[..., 3] - boxes[..., 1])) + return hit.sum(axis=-1) + np.where(own > 0, area / own, 0.0) + + +def _cheapest_places(cost, approach, move, rest, bars=None, start=None, + end=None): + """The cheapest way through the frames for one label: per frame the + index of the place it hangs at, minimizing the sum of `cost` + ``(frames, places)`` over the frames plus, for every change of + place, ``move[from, to]`` and ``approach[frame, to]`` (what gliding + into the place so as to be there at `frame` costs), with at least + `rest` frames spent at a place before the next change. `bars`, per + frame None or a ``(places, places)`` array, is added to `move` for a + change that arrives on that frame. `start` and `end` fix the first + and the last frame's place. Exact (dynamic programming over the + place and the frames spent there).""" + n_frames, n_places = cost.shape + rest = max(int(rest), 1) + value = np.full((n_places, rest + 1), np.inf) + if start is None: + value[:, rest] = 0.0 # (free to move from the start) + else: + value[start, 0] = 0.0 + value += cost[0][:, None] + came_from = np.zeros((n_frames, n_places), dtype=int) + stayed_long = np.zeros((n_frames, n_places), dtype=bool) + columns = np.arange(n_places) + # (a place far dearer to leave than the cheapest cannot be the one + # a change of place starts from: only the others are looked at) + spread = float(np.ptp(move[np.isfinite(move)])) \ + if np.isfinite(move).any() else 0.0 + for frame in range(1, n_frames): + ready = value[:, rest] + barred = bars is not None and bars[frame] is not None + within = spread + (float(bars[frame].max()) if barred else 0.0) + lowest = ready.min() + if np.isfinite(lowest): + few = np.flatnonzero(ready <= lowest + within + 1e-9) + else: + few = columns[:1] + through = ready[few, None] + move[few] + if barred: + through = through + bars[frame][few] + best = np.argmin(through, axis=0) + through = through[best, columns] + source = few[best] + new = np.full_like(value, np.inf) + new[:, 1:rest] = value[:, 0:rest - 1] + stayed_long[frame] = value[:, rest] <= value[:, rest - 1] + new[:, rest] = np.minimum(value[:, rest], value[:, rest - 1]) + new[:, 0] = through + approach[frame] + came_from[frame] = source + value = new + cost[frame][:, None] + if end is None: + place, age = np.unravel_index(np.argmin(value), value.shape) + else: + place, age = end, int(np.argmin(value[end])) + places = np.zeros(n_frames, dtype=int) + for frame in range(n_frames - 1, -1, -1): + places[frame] = place + if frame == 0: + break + if age == 0: + place, age = came_from[frame][place], rest + elif age == rest: + age = rest if stayed_long[frame][place] else rest - 1 + else: + age -= 1 + return places + + +def _plan_label_places(hard, soft, move, taps, rest, loops, bars=None, + passing=None): + """The places one label of an animation hangs at over one stretch of + frames it is shown for: `hard` ``(frames, places)`` is what lying off + the canvas, on static content or on a label placed before costs at + each place on each frame, `soft` ``(places,)`` what hanging far out + costs per frame, ``move[from, to]`` what a change of place costs. + The cheapest plan (`_cheapest_places`) in which the label spends + at least `rest` frames at a place it moved to, and in which a place + is also clear while the label glides into it (a glide takes `taps` + frames). + + For an animation that loops (`loops`) the plan is made round the + loop: first through three rounds of it, to find the longest stay of + the middle round; then once more starting and ending in the middle + of that stay, so the last frame leads into the first with no change + of place. + + `passing` ``(frames, places)`` is what a place costs on a frame the + label is still on its way to it (by default `hard`; + `solve_label_tracks` counts the other labels there and not static + content, which the label is not on until it arrives). + + `bars`, per frame None or a ``(places, places)`` array, is added to + what a change of place that arrives on that frame costs + (`solve_label_tracks` bars a change whose glide was found to cross + another label).""" + n_frames = len(hard) + cost = hard + soft + rest = max(1, min(int(rest), n_frames // 3)) + if n_frames < 2: + return np.argmin(cost, axis=1) + bars = [None] * n_frames if bars is None else list(bars) + passing = hard if passing is None else passing + + def _approach(table, wrap): + """Per frame and place: the hard cost of the place over the + `taps` frames before (the label is on its way there).""" + total = np.zeros_like(table) + for back in range(1, taps): + moved = np.roll(table, back, axis=0) + if not wrap: + moved[:back] = 0.0 + total += moved + return total + + if not loops: + return _cheapest_places(cost, _approach(passing, False), move, rest, + bars) + thrice = _cheapest_places( + np.tile(cost, (3, 1)), _approach(np.tile(passing, (3, 1)), True), + move, rest, bars * 3) + middle = thrice[n_frames:2 * n_frames] + changes = np.flatnonzero(middle != np.roll(middle, 1)) + if not len(changes): + return middle + # the longest stay of the round, and the frame in the middle of it + lengths = np.diff(np.concatenate([changes, [changes[0] + n_frames]])) + longest = int(np.argmax(lengths)) + turn = int(changes[longest] + lengths[longest] // 2) % n_frames + place = int(middle[turn]) + plan = _cheapest_places( + np.roll(cost, -turn, axis=0), + np.roll(_approach(passing, True), -turn, axis=0), move, rest, + bars[turn:] + bars[:turn], start=place, end=place) + return np.roll(plan, turn) + + +def _ease_label_tracks(targets, shown, taps, periodic): + """Turn the places an animation's labels take frame by frame + (`targets`, ``(frames, labels, 2)`` offsets that change in steps) + into the offsets they are drawn at: every step becomes a glide over + the `taps` frames BEFORE the frame the label is at its new place + (the frames to come are known, so the label is out of the way when + the other arrives), always toward the new place (a weighted mean of + the places around each frame, with weights that are never negative, + so one step never overshoots or turns back). + + Each stretch of frames a label is shown for is eased on its own: a + label that appears is at its place from its first frame. In an + animation that loops without a seam (`periodic`) a label shown on + every frame is eased round the loop, last frame into first.""" + from scipy.ndimage import convolve1d + weights = np.hanning(taps + 2)[1:-1] + weights = weights / weights.sum() + # (`origin`: the glide is over at the frame the label had to move at) + half = taps // 2 + eased = np.array(targets, dtype=float) + always = shown.all(axis=0) + if always.any(): + eased[:, always] = convolve1d( + targets[:, always], weights, axis=0, origin=half, + mode='wrap' if periodic else 'nearest') + for k in np.flatnonzero(~always & shown.any(axis=0)): + edges = np.flatnonzero(np.diff(np.concatenate( + [[False], shown[:, k], [False]]).astype(int))) + for first, end in zip(edges[::2], edges[1::2]): + if end - first > half: + eased[first:end, k] = convolve1d( + targets[first:end, k], weights, axis=0, origin=half, + mode='nearest') + eased[~shown] = np.nan + return eased + + +def _labels_loop(anchors, shown): + """Whether an animation's last frame leads back into its first + without a seam, as far as its labels can tell: the same labels are + shown on both, and their points are no further apart between the two + than between other neighboring frames (a spin of whole turns; not a + reveal, whose last frame shows everything and whose first shows + one point).""" + if len(anchors) < 3 or not np.array_equal(shown[0], shown[-1]): + return False + if not shown[0].any(): + return True + with np.errstate(invalid='ignore'): + steps = np.hypot(*np.moveaxis(np.diff(anchors, axis=0), -1, 0)) + seam = np.hypot(*np.moveaxis(anchors[0] - anchors[-1], -1, 0)) + steps = np.where(shown[1:] & shown[:-1], steps, np.nan) + if np.all(np.isnan(steps)): + return False + usual = np.nanmax(steps) + return bool(np.nanmax(np.where(shown[0], seam, np.nan)) + <= 1.5 * usual + 1e-6) + + +def solve_label_tracks(ax, _independent=False): + """Work out where every observation label of the ANIMATED axes `ax` + is drawn on every frame, and keep the answer as a table (one row per + frame) that the frames then show (`_apply_label_tracks`). + + The rule (owner decision 2026-11-23): on every frame a label is + attached to its point where that frame shows it and has correct + positioning (off the other labels and off legends, colorbars, + titles, suptitle and caption, on the canvas); it may shift from + frame to frame but must not wobble back and forth. + + Every frame is known before any is drawn, so the labels are not + placed frame after frame: each label is given a PLAN for the whole + animation. The labels are gone through in the order they were given + (as on a static figure, an earlier label never gives way to a later + one). For each, every place round its point (`_LABEL_TRACK_CANDIDATES`, + measured with the geometry of a static figure's label: `_label_geometry`, + `_label_size_pt`, `_label_obstacles_pt`) is priced on every frame: + off the canvas or on static content (the cube's own turning axis + labels included) costs most, lying on a label planned before, as + that label is DRAWN on that frame, next, and hanging further from + the point a little. The label takes the cheapest path through the + frames (`_plan_label_places`) in which it rests + `_LABEL_REST_EASES` glides at a place before it moves again, so it + stays at one place for as long as there is one that is clear, moves + BEFORE another label arrives, and never goes out and straight back. + Changes of place are then turned into glides (`_ease_label_tracks`); + a change whose glide would cross another label is barred on the + frames it would, and the label planned again (up to + `_LABEL_TRACK_REPLANS` times with 30 labels, more with fewer, fewer + with more). Labels still not clear on some frame, and the labels + they lie on, are then planned again among ALL the others + (`_LABEL_TRACK_ROUNDS` times at most, up to 40 labels; once up to + 80; not above), and a plan is kept only if it leaves the label + clear on more frames. The labels of the figure's other animated + axes that were planned before count as labels to keep off (a grid + of panels). Of places that are as clear a label prefers the nearer, + and the one that points out of the cloud of labeled points, so its + leader line does not cross the cloud. + Where a glide would carry a label over static content the label + jumps instead (``'forced'`` in the table marks those frames). A + label that comes into view (a sliding window, a reveal) is planned + for the frames it is shown on; an animation that loops without a + seam (`_labels_loop`) is planned round the loop. + + The table belongs to the animation and not to a draw: it is worked + out from the figure's geometry by running the frame function for + every frame (`track_labels` supplies it; nothing is rendered), so + frame `i` is the same picture whichever frames were drawn before + it, in a saved file, and in a second identical call. It is worked + out again when the figure it was made for has changed (its size, + the axes' box, the labels the axes holds). + + With `_independent` every frame is instead placed on its own by the + rule of a static figure (`_arrange_labels`, every label starting + from its usual place) and nothing is eased: what each frame would + get as a still, kept for comparison (tests, and the numbers in the + changelog).""" + state = _label_state(ax) + spec = state.frames + if spec is None or state.solving: + return None + n_frames, show_frame, interval_ms = spec + show_frame = show_frame() + if show_frame is None: + # (the animation is gone: the table it left is kept as it is) + return state.tracks + total = n_frames + entries = _label_entries(ax) + labels = [entry[0] for entry in entries + if not _label_user_placed(entry[0])] + current = state.frame + count = len(labels) + # more labels than are ever arranged (`_LABEL_DECLUTTER_MAX`): they + # stay at their usual places, and no frame is looked at + crowded = count > _LABEL_DECLUTTER_MAX + # the frames that are planned: all of them, or, in an animation with + # more labels x frames than `_LABEL_TRACK_BUDGET`, that many evenly + # spaced ones (the labels move evenly between two of them), so the + # time the plan takes and the size of the table have a bound + keys = np.arange(total) + if crowded: + keys = keys[:1] + elif not _independent and count * total > _LABEL_TRACK_BUDGET: + wanted = min(total, max(_LABEL_TRACK_KEYS_MIN, + _LABEL_TRACK_BUDGET // max(count, 1))) + keys = np.unique(np.round( + np.linspace(0, total - 1, wanted)).astype(int)) + n_frames = len(keys) + state.solving = True + try: + anchors = np.full((n_frames, count, 2), np.nan) + shown = np.zeros((n_frames, count), dtype=bool) + turning = [] + for row, frame in enumerate(keys if not crowded else ()): + show_frame(int(frame)) + _settle_axes_for_labels(ax) + _project_label_anchors(ax, entries) + origin, to_pt, canvas, anchors[row] = _label_geometry( + ax, labels) + shown[row] = [label.get_visible() for label in labels] + # (the cube's own axis labels turn with it) + turning.append(_whole_points( + axis_text_boxes_px(ax), origin, to_pt)) + show_frame(min(current, total - 1)) + _settle_axes_for_labels(ax) + _project_label_anchors(ax, entries) + origin, to_pt, canvas, _now = _label_geometry(ax, labels) + signature = _label_tracks_signature(ax) + sizes = np.array([_label_size_pt(label) for label in labels], + dtype=float).reshape(count, 2) + pads = _label_pads_pt(labels) + obstacles = _label_obstacles_pt(ax, None, origin, to_pt, + axis_text=False) + finally: + state.solving = False + shown &= np.all(np.isfinite(anchors), axis=2) + try: + fps = 1000.0 / float(interval_ms) + except (TypeError, ValueError, ZeroDivisionError): + fps = 15.0 + # (planned frames a second) + fps *= n_frames / float(total) + if crowded: + shown[:] = True + taps = int(np.clip(round(_LABEL_EASE_SECONDS * fps), + *_LABEL_EASE_FRAMES)) + taps = max(1, min(taps, n_frames // 2)) | 1 # odd + periodic = not _independent and _labels_loop(anchors, shown) + candidates = _LABEL_CANDIDATES if _independent \ + else _LABEL_TRACK_CANDIDATES + home = candidates.index(_LABEL_HOME) + place_index = np.full((n_frames, count), home, dtype=int) + forced = np.zeros((n_frames, count), dtype=bool) + offsets = np.full((n_frames, count, 2), np.nan) + half_boxes = 0.5 * sizes + pads[:, None] + if _independent or crowded: + for frame in range(n_frames if not crowded else 0): + here = np.flatnonzero(shown[frame]) + still = np.vstack([obstacles, turning[frame]]) + if len(here) >= 2 or (len(here) and len(still)): + now = [_LABEL_HOME] * len(here) + _arrange_labels(now, [None] * len(here), + anchors[frame, here], sizes[here], + pads[here], canvas, still, strict=True) + place_index[frame, here] = [ + candidates.index(place) for place in now] + offsets = np.where( + shown[..., None], + _label_center_offsets(place_index, sizes, candidates), np.nan) + turning = turning or [np.zeros((0, 4))] + else: + reaches = np.array([reach for _corner, reach in candidates]) + aims = np.array([corner for corner, _reach in candidates], + dtype=float) + aims /= np.hypot(aims[:, 0], aims[:, 1])[:, None] + # the middle of the labeled points on each frame: a label that + # points away from it has its leader line outside the cloud + with np.errstate(invalid='ignore'): + hub = np.nanmean(np.where(shown[..., None], anchors, np.nan), + axis=1) if count else np.zeros((n_frames, 2)) + far = ((reaches - LABEL_OFFSET_PT) / LABEL_OFFSET_PT + * _LABEL_TRACK_FAR_PER_SECOND / fps + + 1e-9 * np.arange(len(candidates))) + #: per frame, the boxes of the cube's own axis labels (NaN rows + #: fill the frames that show fewer) + turns = np.full((n_frames, max(1, max(len(boxes) + for boxes in turning)), 4), + np.nan) + for frame, boxes in enumerate(turning): + turns[frame, :len(boxes)] = boxes + # the more labels, the fewer times each is planned again (the + # time `plot()` takes to return grows with both) + replans = int(np.clip(_LABEL_TRACK_REPLANS * 30 // max(count, 1), + 1, 3 * _LABEL_TRACK_REPLANS)) + rounds = _LABEL_TRACK_ROUNDS if count <= 40 else ( + 1 if count <= 80 else 0) + #: per frame, each label's box as it is drawn (NaN: not planned + #: yet, or not shown) + drawn = np.full((n_frames, count, 4), np.nan) + # (and, after them, the labels of the figure's other animated + # axes that are planned already: a panel's labels reach into + # the gaps of a grid, where the next panel's do too) + for other in ax.figure.axes: + theirs = None if other is ax else label_tracks(other) + if theirs is not None and theirs.get('boxes') is not None \ + and np.array_equal(theirs['frames'], keys): + drawn = np.concatenate([drawn, theirs['boxes']], axis=1) + + def _crossed(k, where, frames): + """Per frame of `frames`: whether label `k`, its middle + `where` (one row per frame of `frames`) from its point, + lies on another label, on static content or over the canvas + edge.""" + middle = anchors[frames, k] + where + boxes = np.column_stack([middle - half_boxes[k], + middle + half_boxes[k]]) + others = np.delete(drawn[frames], k, axis=1) + bad = (boxes[:, 0] < canvas[0]) | (boxes[:, 1] < canvas[1]) \ + | (boxes[:, 2] > canvas[2]) | (boxes[:, 3] > canvas[3]) + bad |= _boxes_meet(boxes, obstacles) > 0 + bad |= _boxes_meet(boxes, others) > 0 + bad |= _boxes_meet(boxes, turns[frames]) > 0 + return bad + + # how far along a glide is on each frame before the one it ends on + step = np.zeros((4 * taps, 1, 1)) + step[2 * taps:] = 1.0 + along = step if taps < 3 else _ease_label_tracks( + step, np.ones((4 * taps, 1), dtype=bool), taps, False) + along = [(int(at) - 2 * taps, float(along[at, 0, 0])) + for at in range(4 * taps) + if 1e-3 < along[at, 0, 0] < 1.0 - 1e-3] + + def _bar(k, middles, source, target, bars, move): + """Bar label `k` from the change of place `source` to + `target` on every frame a glide between the two that ends + there would cross something (`bars`, for + `_plan_label_places`).""" + crossed = np.zeros(n_frames, dtype=bool) + ends = np.arange(n_frames) + for back, share in along: + frames = ends + back + if periodic: + frames, at = frames % n_frames, ends + else: + inside = (frames >= 0) & (frames < n_frames) + frames, at = frames[inside], ends[inside] + seen = shown[frames, k] + frames, at = frames[seen], at[seen] + if len(frames): + where = ((1.0 - share) * middles[source] + + share * middles[target]) + crossed[at] |= _crossed( + k, np.broadcast_to(where, (len(frames), 2)), frames) + for at in np.flatnonzero(crossed): + if bars[at] is None: + bars[at] = np.zeros_like(move) + bars[at][source, target] = _LABEL_TRACK_COVERED + + def _plan(k): + """Plan label `k` among the labels in `drawn`: its place on + every frame, its middle on every frame (eased), the frames + it jumps on, and on how many frames it is not clear.""" + middles = _label_center_offsets( + np.arange(len(candidates)), sizes[k][None], candidates) + # (a place is clear with `_LABEL_TRACK_CLEARANCE_PT` to spare) + reach = half_boxes[k] + _LABEL_TRACK_CLEARANCE_PT + centers = anchors[:, k][:, None, :] + middles[None] + rooms = np.concatenate([centers - reach, centers + reach], + axis=2) + # (of static content and the canvas edge, with a static + # figure's `_LABEL_CLEARANCE_PT`) + reach = half_boxes[k] + _LABEL_CLEARANCE_PT + wide = np.concatenate([centers - reach, centers + reach], + axis=2) + with np.errstate(invalid='ignore'): + off = ((wide[..., 0] < canvas[0]) + | (wide[..., 1] < canvas[1]) + | (wide[..., 2] > canvas[2]) + | (wide[..., 3] > canvas[3])) + hard = _LABEL_TRACK_OFF * ( + off + np.ceil(_boxes_meet(wide, obstacles))) + hard += _LABEL_TRACK_OFF * np.ceil( + _boxes_meet(wide, turns[:, None])) + near = np.flatnonzero(np.isfinite(drawn[..., 0]).any(axis=0) + & (np.arange(drawn.shape[1]) != k)) + covered = np.zeros_like(hard) + if len(near): + covered = _LABEL_TRACK_COVERED * _boxes_meet( + rooms, drawn[:, None, near, :]) + covered = np.where(shown[:, k][:, None], covered, 0.0) + hard = np.where(shown[:, k][:, None], hard, 0.0) + covered + # (pointing into the cloud: the leader line crosses it) + away = anchors[:, k] - hub + length = np.hypot(away[:, 0], away[:, 1]) + with np.errstate(invalid='ignore', divide='ignore'): + away = np.where(length[:, None] > 1.0, + away / length[:, None], 0.0) + soft = far + (0.5 * _LABEL_TRACK_INWARD_PER_SECOND / fps + * (1.0 - np.nan_to_num(away) @ aims.T)) + # (a long way to a new place costs more than a short one) + # (and a label does not sweep across the whole plot in one + # glide: no change of place is longer than + # `_LABEL_TRACK_MOVE_MAX_PT`) + way = np.hypot(*np.moveaxis( + middles[:, None, :] - middles[None, :, :], -1, 0)) + move = (_LABEL_TRACK_SWITCH + + _LABEL_TRACK_MOVE * way / LABEL_OFFSET_PT) + move[way > _LABEL_TRACK_MOVE_MAX_PT] = np.inf + np.fill_diagonal(move, np.inf) + if shown[:, k].all(): + stretches = [(0, n_frames, periodic)] + else: + edges = np.flatnonzero(np.diff(np.concatenate( + [[False], shown[:, k], [False]]).astype(int))) + stretches = [(first, end, False) + for first, end in zip(edges[::2], edges[1::2])] + def _route(rest): + """The label's plan with at least `rest` frames at each + place: places, middles, jumps, the number of frames it + is not clear on.""" + places = np.full(n_frames, home, dtype=int) + bars = [None] * n_frames + for _attempt in range(replans + 1): + for first, end, loops in stretches: + places[first:end] = _plan_label_places( + hard[first:end], soft[first:end], move, taps, + rest, loops, bars[first:end], + covered[first:end]) + targets = middles[places][:, None, :] + eased = targets if taps < 3 else _ease_label_tracks( + targets, shown[:, [k]], taps, periodic) + # a glide that crosses another label, static content + # or the canvas edge: that change of place is barred + # on the frames it would, and the label is planned + # again + gliding = np.flatnonzero(shown[:, k] & ( + np.abs(eased - targets).max(axis=(1, 2)) > 0.5)) + crossing = gliding[_crossed(k, eased[gliding, 0], + gliding)] \ + if len(gliding) else gliding + changes = set() + for frame in crossing: + # (the glide ends at the next change of place) + for later in range(frame, frame + taps + 1): + at = later % n_frames if periodic else later + if at >= n_frames: + break + if places[at] != places[at - 1]: + changes.add((int(places[at - 1]), + int(places[at]))) + break + if not changes or _attempt == replans: + break + for source, target in sorted(changes): + _bar(k, middles, source, target, bars, move) + # a glide that would still carry the label over a + # legend, a title, an axis label or the canvas edge, + # all of which both its ends are clear of: the label + # jumps instead + def _out(where): + middle = anchors[:, k] + where[:, 0] + boxes = np.column_stack([middle - half_boxes[k], + middle + half_boxes[k]]) + with np.errstate(invalid='ignore'): + return ((boxes[:, 0] < canvas[0]) + | (boxes[:, 1] < canvas[1]) + | (boxes[:, 2] > canvas[2]) + | (boxes[:, 3] > canvas[3]) + | (_boxes_meet(boxes, obstacles) > 0) + | (_boxes_meet(boxes, turns) > 0)) + + jumps = np.zeros(n_frames, dtype=bool) + bad = _out(eased) & ~_out(targets) & shown[:, k] + for frame in np.flatnonzero(bad): + by = np.arange(frame - taps, frame + taps + 1) + by = (by % n_frames if periodic + else by[(by >= 0) & (by < n_frames)]) + jumps[by] = True + jumps &= shown[:, k] + if jumps.any(): + # (the jump is made as early as the place the label + # leaves is no longer clear of them and the place + # it goes to is) + for at in np.flatnonzero( + jumps & (places != np.roll(places, 1))): + if at == 0 and not periodic: + continue + source, target = places[at - 1], places[at] + leaves = _out(np.broadcast_to( + middles[source], (n_frames, 1, 2))) + lands = _out(np.broadcast_to( + middles[target], (n_frames, 1, 2))) + for back in range(1, taps + 1): + frame = at - back + if frame < 0 and not periodic: + break + frame %= n_frames + if (places[frame] != source or not shown[frame, k] + or not leaves[frame] or lands[frame]): + break + places[frame] = target + targets = middles[places][:, None, :] + eased[jumps] = targets[jumps] + where = np.where(shown[:, k][:, None], eased[:, 0], np.nan) + visible = np.flatnonzero(shown[:, k]) + unclear = int(_crossed(k, where[visible], visible).sum()) \ + if len(visible) else 0 + return places, where, jumps, unclear + + return _route(_LABEL_REST_EASES * taps + 1) + + def _keep(k, plan): + place_index[:, k], offsets[:, k], forced[:, k] = plan[:3] + middle = anchors[:, k] + offsets[:, k] + drawn[:, k] = np.column_stack([middle - half_boxes[k], + middle + half_boxes[k]]) + + unclear = np.zeros(count, dtype=int) + for k in range(count): + if shown[:, k].any(): + plan = _plan(k) + _keep(k, plan) + unclear[k] = plan[3] + # a label that is still not clear on some frame, and the labels + # it lies on, are planned again among ALL the others (the first + # time round a label only knew of the labels before it), for as + # long as that leaves fewer frames with a label on another + for _round in range(rounds): + again = np.zeros(count, dtype=bool) + for k in np.flatnonzero(unclear): + frames = np.flatnonzero(shown[:, k]) + bad = frames[_crossed(k, offsets[frames, k], frames)] + with np.errstate(invalid='ignore'): + met = ( + (np.minimum(drawn[bad, k, None, 2], drawn[bad, :, 2]) + > np.maximum(drawn[bad, k, None, 0], + drawn[bad, :, 0])) + & (np.minimum(drawn[bad, k, None, 3], + drawn[bad, :, 3]) + > np.maximum(drawn[bad, k, None, 1], + drawn[bad, :, 1]))) + again |= met.any(axis=0)[:count] + again[k] = True + better = False + for k in np.flatnonzero(again): + before = (place_index[:, k].copy(), offsets[:, k].copy(), + forced[:, k].copy()) + frames = np.flatnonzero(shown[:, k]) + was = int(_crossed(k, offsets[frames, k], frames).sum()) + plan = _plan(k) + if plan[3] < was: + _keep(k, plan) + better = True + else: + _keep(k, before) + for k in np.flatnonzero(shown.any(axis=0)): + frames = np.flatnonzero(shown[:, k]) + unclear[k] = _crossed(k, offsets[frames, k], frames).sum() + if not better or not unclear.any(): + break + # (each label's box on each frame, for the figure's other axes) + middle = anchors + offsets + label_boxes = None if _independent or crowded else np.concatenate( + [middle - half_boxes, middle + half_boxes], + axis=2).astype(np.float32) + # (kept small: 28 bytes a label and planned frame) + state.tracks = { + 'labels': [weakref.ref(label) for label in labels], + 'offsets': offsets.astype(np.float32), + 'places': place_index.astype(np.int16), 'shown': shown, + 'forced': forced, 'signature': signature, 'periodic': periodic, + 'ease_frames': taps, 'candidates': candidates, + 'boxes': label_boxes, 'frames': keys, 'n_frames': total} + _apply_label_tracks(ax) + return state.tracks + + +def _label_tracks_signature(ax): + """What an animation's label table was made for: the canvas in + points, the box of the axes in it, the labels the axes holds, the + size of each label's text and of its frame, and everything the + labels are kept off (`_label_obstacles_pt`: legends, titles, figure + texts, the other axes). A figure given another size, an axes given + more labels, a label given a longer text or a larger font, a text + added to the figure: each needs the table worked out again.""" + fig = ax.get_figure(root=True) + labels = [entry[0] for entry in _label_entries(ax) + if not _label_user_placed(entry[0])] + origin, to_pt, _canvas, _anchors = _label_geometry(ax, []) + return (tuple(np.round(fig.get_size_inches() * 72.0, 3)), + tuple(np.round(ax.get_position().bounds, 6)), + tuple(id(label) for label in labels), + tuple(_label_size_pt(label) for label in labels), + _label_pads_pt(labels).tobytes(), + _label_obstacles_pt(ax, None, origin, to_pt, + axis_text=False).tobytes()) + + +def _apply_label_tracks(ax, frame=None): + """Put the labels of the animated axes `ax` where its table has them + on `frame` (the frame the axes shows, when not given). Called by the + frame function of every animation style (`_sync_anim_labels`), where + a table made for a figure that has since changed + (`_label_tracks_signature`) is worked out again first, and at draw + time (`declutter_labels`). + + A figure that changes on EVERY frame (an `on_frame=` callback that + rewrites a figure text) is not planned again on every frame: the + table is worked out again at the first two changes in a row, and + once more when the figure has stopped changing. + + Between two planned frames (an animation over + `_LABEL_TRACK_BUDGET`) a label is the matching way between its + offsets on the two.""" + state = _label_state(ax) + tracks = state.tracks + if frame is not None: + state.frame = int(frame) + if state.solving: + return + state.shows += 1 + if state.frames is not None and tracks is None: + solve_label_tracks(ax) + return + if state.frames is not None: + signature = _label_tracks_signature(ax) + changed = tracks['signature'] != signature + recent = state.shows - state.solved_at <= 1 + if changed: + state.streak = state.streak + 1 if recent else 1 + state.solved_at = state.shows + if changed and state.streak > 2: + # (changing frame after frame: wait until it stops) + tracks['signature'] = signature + state.pending = True + elif changed or (state.pending and not recent): + state.pending = False + solve_label_tracks(ax) + return + if tracks is None: + return + offsets, keys = tracks['offsets'], tracks['frames'] + at = min(max(state.frame, 0), tracks['n_frames'] - 1) + if len(keys) == tracks['n_frames']: + row = offsets[at] + else: + low = int(np.searchsorted(keys, at, side='right')) - 1 + high = min(low + 1, len(keys) - 1) + share = ((at - keys[low]) / float(keys[high] - keys[low]) + if high > low else 0.0) + before, after = offsets[low], offsets[high] + row = np.where(np.isnan(before), after, + np.where(np.isnan(after), before, + (1.0 - share) * before + share * after)) + for ref, (dx, dy) in zip(tracks['labels'], row): + label = ref() + if label is None or label.axes is not ax \ + or not np.isfinite(dx) or _label_user_placed(label): + continue + _set_label_offset(label, float(dx), float(dy)) + + +def _set_label_offset(label, dx, dy): + """Draw `label` with the middle of its text (`dx`, `dy`) points from + its point: how an animation's table puts a label anywhere on the + way from one place to the next.""" + if getattr(label, '_hyp_offset', None) == (dx, dy) and getattr( + label, '_hyp_place', None) is None: + return + label.set_position((dx, dy)) + label.set_ha('center') + label.set_va('center') + label._hyp_offset = (dx, dy) + # (no named place: `_set_label_place` sets one afresh if this label + # is ever arranged as a static figure's) + label._hyp_place = None + label._hyp_place_left = None + + +def track_labels(ax, n_frames, show_frame, interval_ms=None): + """Have the labels of the ANIMATED axes `ax` follow a table worked + out for the whole animation (`solve_label_tracks`), now and whenever + the figure changes: `show_frame(i)` runs the animation's frame + function for frame `i` of `n_frames` (the updater alone: nothing is + rendered and no `on_frame=` callback is called), and `interval_ms` + is the time between two frames. + + `show_frame` is kept by a WEAK reference (it refers to the + animation, which refers to the figure: a strong one would keep + every closed figure alive): the caller keeps it alive for as long + as the animation lives, a function as an attribute of the + animation, a bound method through its object.""" + if not _label_entries(ax): + return None + state = _label_state(ax) + weak = (weakref.WeakMethod(show_frame) + if hasattr(show_frame, '__self__') else weakref.ref(show_frame)) + state.frames = (int(n_frames), weak, interval_ms) + state.tracks = None + return solve_label_tracks(ax) + + +class _LabelDeclutter(matplotlib.artist.Artist): + """Invisible child of an axes that carries observation labels: it is + drawn before them (lowest zorder) and puts them clear of each other + for the draw that follows (`declutter_labels`). Being part of the + draw, it sees the figure as it is then: after any layout, at any + size, at the camera angle of the frame being drawn.""" + + def __init__(self): + super().__init__() + self.set_zorder(-1e6) + self.set_in_layout(False) + + def draw(self, renderer): + """Place the axes' labels for this draw; draws nothing itself.""" + if self.axes is not None and self.get_visible(): + declutter_labels(self.axes, renderer) + self.stale = False + + +def _watch_labels(ax, labels_and_points): + """Record the labels one call has drawn into `ax` and give the axes + its `_LabelDeclutter` (one per axes). + + The axes keeps the labels of EVERY call that drew into it, so two + `hyp.plot(..., labels=, ax=ax)` calls are kept off each other like + the labels of one call (1.2.1 review round 2: the second call's list + replaced the first's, whose labels were then never moved). What an + `ax.clear()` removed is forgotten: the labels, the declutter artist + itself (the old one is no longer a child of the axes, so a new one + is added) and, when none of an animation's labels are left, the + table the animation's labels followed (`solve_label_tracks`).""" + alive = set(ax.texts) + kept = [entry for entry in + (getattr(ax, '_hyp_labels_and_points', None) or []) + if entry[0] in alive] + if not kept: + forget_label_tracks(ax) + ax._hyp_labels_and_points = kept + [ + entry for entry in labels_and_points if entry[0] in alive] + ax._hyp_label_answer = None + ax._hyp_labels_held = True + watcher = getattr(ax, '_hyp_label_declutter', None) + if watcher is None or watcher not in ax.get_children(): + ax._hyp_label_declutter = ax.add_artist(_LabelDeclutter()) + + +#: how long a label of a STREAM takes to go from one place to the next, +#: in seconds (`StreamLabels`), and the fewest updates that may take +_STREAM_LABEL_EASE_SECONDS = 0.4 +_STREAM_LABEL_EASE_MIN = 3 + +#: for how many glides' worth of updates a stream's label does not go +#: back to the place it last left, unless no other place is clear +_STREAM_LABEL_NO_RETURN_EASES = 6 + +#: how many of a stream's visible labels are kept off each other (the +#: oldest ones); the labels beyond them hang at the usual place, as a +#: static figure's do above `_LABEL_DECLUTTER_MAX` +_STREAM_LABEL_MAX = _LABEL_DECLUTTER_MAX + + +class _StreamLabel: + """One label of a stream: its annotation, the index of its sample, + its point (in the coordinates the axes draws), what it is placed + from (`size`, `pad`, `anchor`, all in points), where it hangs + (`place`), the place it last left and on which update (`left`, + `left_at`), where the middle of its text is drawn (`shown`, points + from its point), the glide it is on (``(from, to, update)`` or + None), until which update it is not moved again (`held_until`), and + whether it has been placed at all yet (`entered`).""" + + __slots__ = ('label', 'index', 'point', 'size', 'pad', 'anchor', + 'place', 'left', 'left_at', 'shown', 'glide', + 'held_until', 'entered') + + +def _place_center_offset(place, size): + """Where the middle of a label's text of `size` is, in points from + its point, at `place` (``(corner, reach)``).""" + (sx, sy), reach = place + return (round(sx * (reach + 0.5 * size[0]), 4), + round(sy * (reach + 0.5 * size[1]), 4)) + + +class StreamLabels: + """The labels of a STREAMING plot (`hypertools.io.streaming`): one + per labeled sample, added when its sample arrives and removed when + the sample leaves the displayed window. + + An animation's labels are planned for the whole animation before a + frame is drawn (`solve_label_tracks`). A stream has no whole: the + samples to come are unknown. So a stream's labels are placed + CAUSALLY, once per update (`step`, called by the stream loop for + every frame it emits and never by a draw), by the placement rule of + every other label (`_arrange_labels`, with the obstacles of + `_label_obstacles_pt`: off the other labels, the titles, legends + and figure texts, inside the canvas), from the places the update + before left them at: + + - a label keeps its place for as long as it is clear; + - a new label is the last in the order, so it is the one that takes + another place when its usual place is taken, and the labels that + are already there stay where they are; it is first drawn AT that + place; + - a label that must move (the figure was resized, the view turned, + or room has come free for a label that had none) glides there + over `_STREAM_LABEL_EASE_SECONDS` of updates, is not moved again + until it has rested there (`_LABEL_REST_EASES`), and does not go + back to the place it left for `_STREAM_LABEL_NO_RETURN_EASES` + glides unless no other place is clear. + + What an update shows therefore depends on the updates before it and + on nothing else (no clock, no count of draws): the same stream in + the same chunks gives the same frames. + + The work of an update is bounded: sizes are measured once per + label, the points' positions and the static obstacles once per + geometry of the figure (its size, the axes' box, limits and + camera), and the labels are arranged only on an update that added + or removed one, changed that geometry, or ended a label's rest. + At most `_STREAM_LABEL_MAX` visible labels are arranged (the + oldest); the others hang at the usual place, and a warning says so + once.""" + + def __init__(self, ax, frame_rate=30, label_alpha=0.5): + self.ax = ax + self.is3d = hasattr(ax, 'get_proj') + self.label_alpha = label_alpha + try: + rate = float(frame_rate) + except (TypeError, ValueError): + rate = 30.0 + if not np.isfinite(rate) or rate <= 0: + rate = 30.0 + self.ease = max(_STREAM_LABEL_EASE_MIN, + int(round(_STREAM_LABEL_EASE_SECONDS * rate))) + self.rest = self.ease * _LABEL_REST_EASES + self.no_return = self.ease * _STREAM_LABEL_NO_RETURN_EASES + self.records, self.fresh, self.moving = [], [], [] + self.frame, self.dirty, self.look_again = 0, False, np.inf + self.signature = None + self.canvas = (0.0, 0.0, 0.0, 0.0) + self.obstacles = np.zeros((0, 4)) + self.warned = False + # the axes' own list of labels and its draw-time watcher (which + # points a 3-D label at its point for the camera of each draw); + # a static figure's labels already in the axes keep their state + held = getattr(ax, '_hyp_labels_held', False) + answer = getattr(ax, '_hyp_label_answer', None) + _watch_labels(ax, []) + ax._hyp_labels_held, ax._hyp_label_answer = held, answer + _connect_label_events(ax.get_figure(root=True), ax) + + def __len__(self): + return len(self.records) + + def add(self, index, text, point): + """Label the sample `index`, drawn at `point` (2 or 3 values in + the axes' coordinates), with `text`. It is placed by the next + `step`.""" + ax = self.ax + point = tuple(float(v) for v in point) + label = ax.annotate( + text, xy=point[:2], + xytext=(-LABEL_OFFSET_PT, LABEL_OFFSET_PT), + textcoords="offset points", ha="right", va="bottom", + **_label_callout_kwargs(self.label_alpha)) + label._hyp_offset = (-LABEL_OFFSET_PT, LABEL_OFFSET_PT) + label._hyp_point_idx = label._hyp_global_idx = int(index) + label._hyp_run_idx = None + label._hyp_stream = True + record = _StreamLabel() + record.label, record.index, record.point = label, int(index), point + record.size = _label_size_pt(label) + record.pad = float(_label_pads_pt([label])[0]) + record.anchor = (np.nan, np.nan) + record.place, record.left, record.left_at = _LABEL_HOME, None, 0 + record.shown = _place_center_offset(_LABEL_HOME, record.size) + record.glide, record.held_until, record.entered = None, 0, False + _set_label_offset(label, *record.shown) + self.records.append(record) + self.fresh.append(record) + ax._hyp_labels_and_points.append((label,) + point) + self.dirty = True + return label + + def _signature(self): + """Everything the positions of the points on the canvas and the + static content round them depend on.""" + ax = self.ax + fig = ax.get_figure(root=True) + view = (ax.get_proj().tobytes() if self.is3d + else (tuple(ax.get_xlim()), tuple(ax.get_ylim()))) + return (tuple(fig.get_size_inches()), float(fig.dpi), + tuple(ax.get_position().bounds), view, + ax.title.get_text(), len(fig.texts), len(fig.legends), + len(fig.axes), ax.get_legend() is not None, + len(ax.texts) - len(self.records)) + + def _measure(self, records, everything): + """Where the points of `records` are on the canvas now and, with + `everything`, what no label may be put on.""" + ax = self.ax + labels = [record.label for record in records] + if self.is3d and records: + points = np.array([record.point for record in records]) + x2, y2, _ = proj3d.proj_transform( + points[:, 0], points[:, 1], points[:, 2], ax.get_proj()) + for label, x, y in zip(labels, np.atleast_1d(x2), + np.atleast_1d(y2)): + label.xy = (float(x), float(y)) + origin, to_pt, canvas, anchors = _label_geometry(ax, labels) + for record, anchor in zip(records, anchors): + record.anchor = (float(anchor[0]), float(anchor[1])) + if not everything: + return + self.canvas = canvas + obstacles = [_label_obstacles_pt(ax, None, origin, to_pt)] + # the labels of a static plot drawn into the same axes before + others = [entry[0] for entry in _label_entries(ax) + if not getattr(entry[0], '_hyp_stream', False) + and entry[0].get_visible()] + if others: + _o, _t, _c, at = _label_geometry(ax, others) + pads = _label_pads_pt(others) + for label, (px, py), pad in zip(others, at, pads): + size, place = _label_size_pt(label), _label_place(label) + if place is not None: + box = _label_box((px, py), size, place[0], place[1], pad) + else: + dx, dy = label._hyp_offset + box = (px + dx - 0.5 * size[0] - pad, + py + dy - 0.5 * size[1] - pad, + px + dx + 0.5 * size[0] + pad, + py + dy + 0.5 * size[1] + pad) + if np.all(np.isfinite(box)): + obstacles.append(np.array([box], dtype=float)) + self.obstacles = np.vstack(obstacles) + + def _arrange(self): + """Place the labels for this update, from where the last one + left them (`_arrange_labels`).""" + frame = self.frame + if len(self.records) > _STREAM_LABEL_MAX and not self.warned: + self.warned = True + warnings.warn( + f"the stream shows more than {_STREAM_LABEL_MAX} labels at " + f"once: only the {_STREAM_LABEL_MAX} oldest of them are kept " + "off each other, and the others hang at the usual place by " + "their points. Pass stream_window= to show only the most " + "recent samples, or label fewer samples (labels= entries " + "that are None draw no label).", UserWarning, + stacklevel=external_stacklevel()) + records = self.records[:_STREAM_LABEL_MAX] + places = [record.place for record in records] + left = [record.left for record in records] + was = list(places) + held = [record.held_until > frame for record in records] + barred = [record.left is not None + and frame - record.left_at < self.no_return + for record in records] + anchors = np.array([record.anchor for record in records], + dtype=float).reshape(-1, 2) + sizes = np.array([record.size for record in records], + dtype=float).reshape(-1, 2) + pads = np.array([record.pad for record in records], dtype=float) + _arrange_labels(places, left, anchors, sizes, pads, self.canvas, + self.obstacles, strict=True, held=held, + barred=barred, + fresh=[not record.entered for record in records]) + # a label that found no clear place (more labels than there is + # room for) is not looked at again on every update: it waits + # one glide's worth of updates, which bounds the work of a + # crowded stream + if len(records) > 1: + corners = np.array([place[0] for place in places], dtype=float) + reaches = np.array([place[1] for place in places])[:, None] + middle = anchors + corners * (reaches + 0.5 * sizes) + half = 0.5 * sizes + pads[:, None] + with np.errstate(invalid='ignore'): + meet = np.all( + np.abs(middle[:, None, :] - middle[None, :, :]) + < half[:, None, :] + half[None, :, :], axis=2) + for k in np.flatnonzero(np.tril(meet, -1).any(axis=1)): + records[k].held_until = max(records[k].held_until, + frame + self.ease) + for record, before, place in zip(records, was, places): + if place != before: + record.place = place + target = _place_center_offset(place, record.size) + if record.entered: + record.left, record.left_at = before, frame + record.held_until = frame + self.rest + if record.glide is None: + self.moving.append(record) + record.glide = (record.shown, target, frame) + else: + # a new label is first drawn AT its place + record.shown = target + _set_label_offset(record.label, *target) + record.entered = True + self.dirty = False + waits = [record.held_until for record in records + if record.held_until > frame] + self.look_again = min(waits) if waits else np.inf + + def _glide(self, finish=False): + """Move every label that is on its way one update further (or, + with `finish`, all the way).""" + still = [] + for record in self.moving: + start, target, since = record.glide + share = 1.0 if finish else (self.frame - since) / float(self.ease) + if share >= 1.0: + record.shown, record.glide = target, None + else: + eased = share * share * (3.0 - 2.0 * share) + record.shown = ( + round(start[0] + (target[0] - start[0]) * eased, 4), + round(start[1] + (target[1] - start[1]) * eased, 4)) + still.append(record) + if record.label.axes is self.ax \ + and not _label_user_placed(record.label): + _set_label_offset(record.label, *record.shown) + self.moving = still + + def step(self, first_index=0): + """One update of the stream: drop the labels of samples before + `first_index` (they have left the displayed window), place the + labels that are shown, and move the gliding ones on. Call it + once for every frame the stream emits, before the frame is + drawn.""" + ax = self.ax + self.frame += 1 + if any(record.index < first_index or record.label.axes is not ax + for record in self.records): + gone = [record for record in self.records + if record.index < first_index + or record.label.axes is not ax] + dead = {id(record.label) for record in gone} + for record in gone: + if record.label.axes is ax: + record.label.remove() + ax._hyp_labels_and_points = [ + entry for entry in + (getattr(ax, '_hyp_labels_and_points', None) or []) + if id(entry[0]) not in dead] + self.records = [record for record in self.records + if id(record.label) not in dead] + self.fresh = [record for record in self.fresh + if id(record.label) not in dead] + self.moving = [record for record in self.moving + if id(record.label) not in dead] + self.dirty = True + if not self.records: + self.fresh = [] + return + _settle_axes_for_labels(ax) + signature = self._signature() + if signature != self.signature: + self.signature = signature + self._measure(self.records, everything=True) + self.dirty = True + elif self.fresh: + self._measure(self.fresh, everything=False) + self.fresh = [] + if self.dirty or self.frame >= self.look_again: + self._arrange() + self._glide() + + def finish(self): + """The stream has stopped: every label that was on its way is + put where it was going, so the figure that is returned is at + rest.""" + self._glide(finish=True) + + +def _connect_label_events(fig, ax): + """Hide the labels of `ax` while a mouse button is down and put them + back, at their points, when it is let go (a 3-D axes is rotated in + between, and its labels are placed in the projected plane). + + ONE pair of callbacks per axes, however many `plot()` calls label + it, and they read the labels the axes holds NOW (`_label_entries`). + Each call used to connect a pair of its own that kept that call's + labels: a second labeled plot into the same axes repositioned every + earlier call's labels again, and after an ``ax.clear()`` the first + call's callbacks, still connected, reached for the removed labels + (whose ``axes`` is None) and raised ``AttributeError`` out of every + button release, leaving the new labels hidden (1.2.1 review round + 3).""" + # (which axes this canvas already serves is kept on the canvas: a + # figure given another canvas has none of the callbacks, and nothing + # is left on the axes or the figure that would have to be pickled) + canvas = fig.canvas + served = getattr(canvas, '_hyp_label_axes', None) + if served is None: + served = canvas._hyp_label_axes = weakref.WeakSet() + if ax in served: + return + served.add(ax) + + def hide_labels(event): + """Button press: hide every label the axes holds now (a 3-D + axes is about to be turned, and its labels are placed in the + projected plane).""" + for entry in _label_entries(ax): + entry[0]._visible = False + + def update_position(event): + """Button release: put every label the axes holds now back at + its point (projected with the camera the drag left, on a 3-D + axes), show it again and redraw the canvas.""" + entries = _label_entries(ax) + if not entries: + return + # `ax.get_proj()` / `proj3d.proj_transform` only exist on 3D + # (Axes3D) axes -- a 2D `Axes` lacks `get_proj`. `annotate_plot` + # stores 4-tuples (label, x, y, z) for 3D vs. 3-tuples + # (label, x, y) for 2D, so branch the same way here. + is_3d = hasattr(ax, "get_proj") + if is_3d: + proj = ax.get_proj() + # repositioning the annotations needs a renderer; after plt.close() + # (matplotlib >= 3.11 resets the canvas) or on a headless base canvas + # there may be none -- update the coordinates but skip the + # renderer-dependent reposition rather than crash on a missing attr. + renderer = getattr(fig.canvas, "renderer", None) + if renderer is None and hasattr(fig.canvas, "get_renderer"): + try: + renderer = fig.canvas.get_renderer() + except Exception: + renderer = None + for entry in entries: + if is_3d: + label, x, y, z = entry + x2, y2, _ = proj3d.proj_transform(x, y, z, proj) + else: + label, x2, y2 = entry + label.xy = x2, y2 + if renderer is not None: + label.update_positions(renderer) + label._visible = True + fig.canvas.draw() + + canvas.mpl_connect("button_press_event", hide_labels) + canvas.mpl_connect("button_release_event", update_position) + + +class _TraceFollowers(matplotlib.artist.Artist): + """Invisible child of an animated axes that keeps the SECOND artists + of a trace with the first (`follow_artist`), at draw time, before + anything else of the axes is drawn.""" + + def __init__(self): + super().__init__() + self.set_zorder(-1e6) + self.set_in_layout(False) + self.followers = [] + + def draw(self, renderer): + """Bring every follower in line with its leader; draws nothing.""" + for follower, with_alpha in self.followers: + leader = getattr(follower, '_hyp_leader', None) + if leader is None: + continue + if not leader.get_visible(): + if follower.get_visible(): + follower.set_visible(False) + follower._hyp_hidden_with_leader = True + elif getattr(follower, '_hyp_hidden_with_leader', False): + # (only what was hidden HERE is shown again: a follower + # hidden by anything else stays hidden) + follower.set_visible(True) + follower._hyp_hidden_with_leader = False + if with_alpha and follower.get_alpha() != leader.get_alpha(): + follower.set_alpha(leader.get_alpha()) + self.stale = False + + +def follow_artist(ax, follower, leader, alpha=False): + """Have `follower` share the fate of `leader`, the artist of the same + trace that `FrameContext.artists` hands to callbacks: it is drawn + only when `leader` is visible, and with ``alpha=True`` at `leader`'s + opacity. + + One trace can be two artists: a `head_marker=` beside its line, and, + with a continuous `hue=`, the markers of a line-and-marker format + beside the colored line. A callback (``on_frame=``) holds only the + first, so hiding or fading it left the second on screen (1.2.1 + review round 2). A follower that is hidden for a reason of its own + (no points yet, or hidden by the caller) stays hidden: only a + follower that was hidden WITH its leader is shown again with it. + Calling this again gives `follower` a new leader.""" + follower._hyp_leader = leader + watcher = getattr(ax, '_hyp_trace_followers', None) + if watcher is None or watcher not in ax.get_children(): + watcher = ax._hyp_trace_followers = ax.add_artist(_TraceFollowers()) + if not any(one is follower for one, _alpha in watcher.followers): + watcher.followers.append((follower, alpha)) + + def _apply_title(ax, text, font=None, title_kwargs=None, family=None): """Set `ax`'s title, honoring the resolved `font=` and `title_kwargs=` (GH #285). @@ -350,31 +2538,131 @@ def get_window_extent(self, renderer=None): return Bbox.union(boxes) if boxes else Bbox.null() -def _legend_proxy_handles(entries, fmt=None): +def _plot_with_fmt(ax, coords, fmt, **kwargs): + """``ax.plot(*coords, fmt, **kwargs)``, without matplotlib's warning + that a property "is redundantly defined by the ... keyword argument + and the fmt string". + + An animation drew its head and trail lines with the format string + positional AND the dataset's `linestyle=`/`marker=`/`color=` as + keywords, so every animated call that gave both (``'-'`` with + ``linestyle=['-', '--']``) warned once per dataset, though the static + plot of the same call is silent (1.2.1 gallery review follow-up; the + static path has split the format itself since 1.0). When a keyword + names a property the format string also sets, the format is split + here and its parts passed as keywords under the caller's, which is + what matplotlib does after warning: the keyword wins. + """ + if fmt is None: + return ax.plot(*coords, **kwargs) + if (isinstance(fmt, str) and _process_plot_format is not None + and any(key in kwargs + for key in ('linestyle', 'marker', 'color'))): + try: + linestyle, marker, color = _process_plot_format(fmt) + except Exception: # noqa: BLE001 - matplotlib reports a bad fmt + return ax.plot(*coords, fmt, **kwargs) + style = {'linestyle': linestyle, 'marker': marker} + if color is not None: + style['color'] = color + style.update(kwargs) + return ax.plot(*coords, **style) + return ax.plot(*coords, fmt, **kwargs) + + +#: the per-dataset line properties a legend key takes from the dataset it +#: stands for (`legend_entry_styles`, `_legend_proxy_handles`) +LEGEND_KEY_STYLE_KEYS = ('linewidth', 'linestyle', 'marker', 'markersize', + 'alpha') + + +def legend_entry_styles(entries, fmts, kwargs_list): + """The line styling of each explicit legend entry's key, or None. + + `legend_colors=[(label, color), ...]` defines the legend outright, and + its keys used to be one fixed swatch (a 2-point solid line) whatever + was drawn: the heavy line of a ``linewidth=[1.1, ..., 3.4]`` call had + the same thin key as the others (1.2.1 gallery review; 1.1.0 and 1.2.0 + too). When there is exactly one entry per drawn dataset, in order, + entry ``i`` stands for dataset ``i`` and its key takes that dataset's + own `fmt` and its given line width, line style, marker, marker size + and alpha. `fmts` is one format string per drawn dataset (or None), + `kwargs_list` the per-dataset style dicts. Returns one dict per entry + (``'fmt'`` plus the `LEGEND_KEY_STYLE_KEYS` that were given), or None + when the entries do not pair up with the datasets and every key stays + the plain swatch. + """ + if entries is None or kwargs_list is None \ + or len(entries) != len(kwargs_list): + return None + styles = [] + for i, kw in enumerate(kwargs_list): + kw = kw if isinstance(kw, dict) else {} + style = {key: kw[key] for key in LEGEND_KEY_STYLE_KEYS + if kw.get(key) is not None} + if fmts is not None and i < len(fmts) and isinstance(fmts[i], str): + style['fmt'] = fmts[i] + styles.append(style) + return styles + + +def _legend_key_style(fmt, given=None): + """`Line2D` properties of one explicit legend entry's key. + + Without `given` (an entry no single dataset stands behind) the key is + the plain swatch: a 2-point solid line, or an 8-point marker when the + plot's `fmt` draws markers only. With `given` (one dict of + `legend_entry_styles`) it is the dataset's own look: the line style + and marker of its format string, then every property that was given + for it; a property nobody gave keeps the swatch's value. + """ + linestyle, marker = '-', None + fmt = (given or {}).get('fmt', fmt) + if isinstance(fmt, str) and _process_plot_format is not None: + try: + linestyle, marker, _ = _process_plot_format(fmt) + except Exception: # noqa: BLE001 - an unparseable fmt keeps the line + linestyle, marker = '-', None + has_line = linestyle not in (None, 'None') + has_marker = marker not in (None, 'None') + if has_marker and not has_line: + style = {'linestyle': 'None', 'marker': marker, 'markersize': 8} + else: + style = {'linestyle': '-', 'linewidth': 2, 'marker': None} + if given is None: + return style + if has_line: + style['linestyle'] = linestyle + if has_marker: + # an 'o-' dataset is drawn as a line with markers + style['marker'] = marker + style.update({key: given[key] for key in LEGEND_KEY_STYLE_KEYS + if given.get(key) is not None}) + return style + + +def _legend_proxy_handles(entries, fmt=None, styles=None): """`Line2D` proxy handles for explicit legend entries (GH #285). `entries` is a list of ``(label, color)`` pairs -- from a matrix/ mixture `hue=`'s palette columns, or from an explicit `legend_colors=[(label, color), ...]`. Each is drawn as a short line swatch, or as a marker swatch when the plot's own `fmt` draws markers - only, so the key looks like the artists it names. + only, so the key looks like the artists it names. `styles` + (`legend_entry_styles`): one dict per entry when each entry stands + for one drawn dataset, whose line styling its key then takes. """ from matplotlib.lines import Line2D - style = {'linestyle': '-', 'linewidth': 2, 'marker': None} first_fmt = fmt[0] if isinstance(fmt, (list, tuple)) and fmt else fmt - if isinstance(first_fmt, str) and _process_plot_format is not None: - try: - linestyle, marker, _ = _process_plot_format(first_fmt) - except Exception: # noqa: BLE001 - an unparseable fmt keeps the line - linestyle, marker = '-', None - if linestyle in (None, 'None') and marker not in (None, 'None'): - style = {'linestyle': 'None', 'marker': marker, 'markersize': 8} - return [Line2D([], [], color=color, label=label, **style) - for label, color in entries] + if styles is None or len(styles) != len(entries): + styles = [None] * len(entries) + return [Line2D([], [], color=color, label=label, + **_legend_key_style(first_fmt, given)) + for (label, color), given in zip(entries, styles)] def legend_call_kwargs(is_3d=False, zlabel=None, font=None, - legend_kwargs=None): + legend_kwargs=None, ax=None): """The `ax.legend(...)` keyword arguments hypertools draws a legend with. Factored out of `_draw` (GH #285) so `plot()` can REBUILD the legend @@ -383,6 +2671,14 @@ def legend_call_kwargs(is_3d=False, zlabel=None, font=None, inside `_draw`, before those artists exist, and a rebuild that guessed at the placement would move the legend on exactly the figures that gained an entry. + + `ax` is the axes the legend is for. A 2-D hypertools axes fills the + canvas and the frame the reader sees is a square drawn INSIDE it + (`frame_2d`), so a caller's ``loc='upper left'`` put the legend in + the corner of the invisible axes: across the drawn frame's border, + its keys left of the frame (1.2.1 review round 4; 1.2.0 too). With + `ax` given, a named ``loc`` is read against the drawn frame, as it + is read against the axes' frame in matplotlib. """ # a 3-D zlabel is drawn in the axes' right margin -- exactly where # the legend is anchored -- so shift the legend further right when @@ -404,6 +2700,13 @@ def legend_call_kwargs(is_3d=False, zlabel=None, font=None, # anchor (1.1 release review, feature-tour 9.6) call.pop('bbox_to_anchor', None) call.pop('borderaxespad', None) + frame = getattr(ax, '_hyp_frame_box', None) + if (frame is not None and not is_3d + and isinstance(legend_kwargs['loc'], (str, int)) + and 'bbox_transform' not in legend_kwargs): + # the frame the reader sees, in data coordinates + call['bbox_to_anchor'] = frame + call['bbox_transform'] = ax.transData call.update(legend_kwargs) # matplotlib ignores `fontsize=` whenever `prop=` is given, so with # a `font=` the user's size silently lost; fold it into the @@ -728,6 +3031,26 @@ def _anim_box_zoom(zoom): # for the backend divergences a shared callee closed. +def held_frame_sequence(n_frames, hold_frames=0): + """What `FuncAnimation` is given as ``frames=`` for an animation of + `n_frames` content frames whose last frame is held for `hold_frames` + more (``hold=``, GH #299): the int `n_frames` itself without a hold + (exactly what was always passed), else the list ``[0, ..., n-1, n-1, + ..., n-1]``.""" + n_frames, hold_frames = int(n_frames), int(hold_frames or 0) + if hold_frames <= 0: + return n_frames + return list(range(n_frames)) + [n_frames - 1] * hold_frames + + +def content_frame_count(line_ani): + """How many DISTINCT frames an animation draws: its frame count less + the frames a ``hold=`` repeats at the end (GH #299). Frame indices + handed to a frame function must stay below this.""" + count = getattr(line_ani, '_hyp_content_frames', None) + return int(line_ani._save_count if count is None else count) + + class PanelAnimationStub: """One panel's share of an animated `panels=` grid (GH #295). @@ -920,6 +3243,7 @@ def _draw( title_kwargs=None, legend_kwargs=None, legend_entries=None, + legend_entry_styles=None, legend_colors=None, axis_scale='unit', xlim=None, @@ -927,10 +3251,26 @@ def _draw( x_date=False, legend_order=None, panel_cell=False, + head_marker=None, + tail_linewidth=None, + trail_alpha=0.3, + hold_frames=0, ): """ Draws the plot + `head_marker` / `tail_linewidth` / `trail_alpha` / `hold_frames` + (GH #299), animations only. `head_marker`: None, or one resolved spec + per drawn dataset (a dict of `Line2D` marker properties with at least + ``'marker'``, or None for a dataset without one) -- a marker drawn at + the last vertex of that dataset's head line on every frame + (`_place_head_marker`). `tail_linewidth`: the line width of the head + line (the recent window), while the trail keeps the dataset's + ``linewidth``. `trail_alpha`: the factor a trail's alpha is the + dataset's alpha times (0.3, the historical constant). `hold_frames`: + how many times the LAST frame is repeated at the end of the animation + (`_new_animation`). + `legend_order` (1.1 release review): the legend labels in the order their entries should be listed, or None for drawn-artist order. The categorical LINE path draws one artist per contiguous run, so its @@ -1010,8 +3350,9 @@ def _draw( # panel on a shared clock. _cell_ax = ax if (panel_cell and ax is not None) else None # ...and a factor on the animated 3-D box zoom, which the grid lowers - # (through the stub) until the rotating cube stays inside its cell; it - # is 1.0, i.e. no change, for every ordinary animated plot. + # (through the stub) until the rotating cube stays inside its cell. A + # single animated plot starts at 1.0 and is lowered only if its cube + # would reach the canvas edge or a legend (`plot._keep_cube_clear`). _cell_zoom_scale = [1.0] # chemtrails/precog/bullettime (GH #127): normalize to one bool per @@ -1308,14 +3649,13 @@ def plot3D(data, fig, ax): (raw[:, 0], raw[:, 1], raw[:, 2]), i) return fig, ax, data + _call_labels = [] + def _own_labels(): """The ``(annotation, x, y[, z])`` entries `annotate_plot` recorded - for THIS call's axes (falling back to the module global, which holds - the most recently annotated plot's).""" - own = getattr(ax, '_hyp_labels_and_points', None) - if own is not None: - return own - return globals().get('labels_and_points') or [] + for THIS call (the axes itself holds the labels of every call that + drew into it, `_watch_labels`).""" + return _call_labels[0] if _call_labels else [] def annotate_plot(data, labels, lengths=None): """Create labels in 3d chart @@ -1330,13 +3670,16 @@ def annotate_plot(data, labels, lengths=None): None """ - global labels_and_points + # this call's labels. `_own_labels` reads this; the axes gets + # them added to its own list below (`_watch_labels`). The module + # global `labels_and_points` still shows the LAST annotated + # plot's ``(label, x, y[, z])`` entries, as it always has, but + # through weak references (`_publish_labels`): holding the + # labels themselves kept the last labeled figure alive after it + # was closed (1.2.1 review round 5). labels_and_points = [] - # ...and on the axes itself: the module global holds only the LAST - # annotated plot's labels, so every earlier cell of a panel grid - # lost its own (an animated grid then updated the last panel's - # labels only; GH #295). `_own_labels` reads this. - ax._hyp_labels_and_points = labels_and_points + _publish_labels(labels_and_points) + _call_labels[:] = [labels_and_points] if lengths is not None: within = [j for L in lengths for j in range(int(L))] @@ -1382,13 +3725,14 @@ def annotate_plot(data, labels, lengths=None): label = ax.annotate( labels[idx], xy=(x2, y2), - xytext=(-20, 20), + xytext=(-LABEL_OFFSET_PT, LABEL_OFFSET_PT), textcoords="offset points", ha="right", va="bottom", **_label_callout_kwargs(label_alpha), **_label_font_kwargs, ) + label._hyp_offset = (-LABEL_OFFSET_PT, LABEL_OFFSET_PT) label._hyp_point_idx = within[idx] label._hyp_global_idx = idx label._hyp_run_idx = (run_of[idx] if run_of is not None @@ -1399,57 +3743,24 @@ def annotate_plot(data, labels, lengths=None): label = ax.annotate( labels[idx], xy=(x2, y2), - xytext=(-20, 20), + xytext=(-LABEL_OFFSET_PT, LABEL_OFFSET_PT), textcoords="offset points", ha="right", va="bottom", **_label_callout_kwargs(label_alpha), **_label_font_kwargs, ) + label._hyp_offset = (-LABEL_OFFSET_PT, LABEL_OFFSET_PT) label.draggable() label._hyp_point_idx = within[idx] label._hyp_global_idx = idx label._hyp_run_idx = (run_of[idx] if run_of is not None else None) labels_and_points.append((label, x[0], x[1])) - fig.canvas.draw() - - def update_position(e): - """Update label positions in chart (2D or 3D) - Args: - e (mouse event) - event handle to update on - Returns: - None - """ - - # `ax.get_proj()` / `proj3d.proj_transform` only exist on 3D - # (Axes3D) axes -- a 2D `Axes` lacks `get_proj`. `annotate_plot` - # stores 4-tuples (label, x, y, z) for 3D vs. 3-tuples - # (label, x, y) for 2D (mirroring its own - # `data[0].shape[-1] > 2` branch), so branch the same way here. - is_3d = hasattr(ax, "get_proj") - if is_3d: - proj = ax.get_proj() - # repositioning the annotations needs a renderer; after plt.close() - # (matplotlib >= 3.11 resets the canvas) or on a headless base canvas - # there may be none -- update the coordinates but skip the - # renderer-dependent reposition rather than crash on a missing attr. - renderer = getattr(fig.canvas, "renderer", None) - if renderer is None and hasattr(fig.canvas, "get_renderer"): - try: - renderer = fig.canvas.get_renderer() - except Exception: - renderer = None - for entry in _own_labels(): - if is_3d: - label, x, y, z = entry - x2, y2, _ = proj3d.proj_transform(x, y, z, proj) - else: - label, x2, y2 = entry - label.xy = x2, y2 - if renderer is not None: - label.update_positions(renderer) - label._visible = True + # labels that would cover each other are moved apart on every + # draw (GH #297), static, rotated by hand or animated alike + _watch_labels(ax, labels_and_points) + _publish_labels(labels_and_points) fig.canvas.draw() def _sync_anim_labels(num, window_frames, all_visible=False, revealed=None, @@ -1476,9 +3787,8 @@ def _sync_anim_labels(num, window_frames, all_visible=False, revealed=None, correspond to the original labeled points, so labels are hidden for the duration of the morph. """ - # `labels_and_points` is a module global set only when annotate_plot ran - # (i.e. this plot has labels); it may also still hold a PREVIOUS plot's - # labels, so guard for existence and restrict to THIS axes' labels. + # this call's labels (none if `annotate_plot` did not run), and + # of them only THIS axes' labels laps = [e for e in _own_labels() if getattr(e[0], 'axes', None) is ax] if not laps: @@ -1516,19 +3826,12 @@ def _sync_anim_labels(num, window_frames, all_visible=False, revealed=None, x2, y2, _ = proj3d.proj_transform(entry[1], entry[2], entry[3], proj) label.xy = (x2, y2) - if renderer is not None: - label.update_positions(renderer) - - def hide_labels(e): - """Hides labels on button press - Args: - e (mouse event) - event handle to update on - Returns: - None - """ - - for label in _own_labels(): - label[0]._visible = False + # (the draw of the frame works out where the label's text and + # arrow go from that; doing it here as well cost a millisecond + # a label on every frame) + # ...and each label where the animation's table has it on this + # frame (`solve_label_tracks`) + _apply_label_tracks(ax, num) def add_labels(x, labels, explore=False): """Add labels to graph if available @@ -1561,8 +3864,7 @@ def add_labels(x, labels, explore=False): if any(isinstance(el, (list, tuple)) for el in labels): labels = list(itertools.chain(*labels)) annotate_plot(X, labels, lengths=lengths) - fig.canvas.mpl_connect("button_press_event", hide_labels) - fig.canvas.mpl_connect("button_release_event", update_position) + _connect_label_events(fig, ax) ##EXPLORE MODE## def distance(point, event): @@ -1792,9 +4094,13 @@ def frame_2d(ax): """ if axis_scale != 'data': plot_square(ax, scale=UNIT_FRAME_SCALE, **frame_kwargs) + # where a legend placed by name goes (`legend_call_kwargs`) + ax._hyp_frame_box = (-UNIT_FRAME_SCALE, -UNIT_FRAME_SCALE, + 2 * UNIT_FRAME_SCALE, 2 * UNIT_FRAME_SCALE) ax.set_xlim(-UNIT_FRAME_LIMIT, UNIT_FRAME_LIMIT) ax.set_ylim(-UNIT_FRAME_LIMIT, UNIT_FRAME_LIMIT) return + ax._hyp_frame_box = None if xlim is not None: ax.set_xlim(*xlim) if ylim is not None: @@ -1874,6 +4180,8 @@ def update_lines_parallel( # in the same loop that slices the artists, so what the context # reports and what the frame draws cannot drift apart. head_bounds = [] + _holders = (None if _windows is None else _head_holders( + [win.reached for win in _windows])) for i, (line, data, trail) in enumerate(itertools.zip_longest( lines, data_lines, trail_lines)): @@ -1916,6 +4224,8 @@ def update_lines_parallel( draw_window = _aa_window(i, start, end, artist=line) # drawn curve line.set_data(draw_window[:, 0:2].T) line.set_3d_properties(draw_window[:, 2]) + _place_head_marker(line, draw_window, + _holders is None or _holders[i]) windows.append(window) window_spcs.append(_window_surface_point_colors( surface_point_colors, i, start, end)) @@ -2060,6 +4370,7 @@ def update_lines_serial( total_points = sum(lengths) revealed = total_points * num / max(1, total_frames - 1) _counts = serial_reveal_counts(lengths, num, total_frames) + _holders = _serial_head_holders(_counts, lengths) windows = [] window_spcs = [] @@ -2111,9 +4422,22 @@ def update_lines_serial( head = _aa_window(i, *head_bounds, artist=line) trail_seg = (data[:0] if trail_bounds is None else _aa_window(i, *trail_bounds, artist=trail)) + if trail is not None and trail_bounds is None: + # no trail on this frame: say so on the artist as well, or + # a renderer that redraws it from its recorded rows + # (`plot._apply_multicolor_animation`) keeps showing the + # trail of the frame drawn before + trail._hyp_row_window = (0, 0) _head_windows.append(tuple(int(b) for b in head_bounds)) line.set_data(head[:, 0:2].T) line.set_3d_properties(head[:, 2]) + # (frame 0 of a serial reveal has drawn nothing yet: the + # head marker waits at the first dataset's first point, as a + # parallel reveal's frame 0 shows it there) + _place_head_marker( + line, head if len(head) or not _holders[i] else data[:1], + _holders[i]) + _set_serial_linewidth(line, trail_bounds is not None) if trail is not None: trail.set_data(trail_seg[:, 0:2].T) trail.set_3d_properties(trail_seg[:, 2]) @@ -2261,19 +4585,158 @@ def update_morph(num, morph_state, cube_scale, azimuths, zoom=1, elev=10): segment_kind='hold' if seg_idx % 2 == 0 else 'transition') return (artist,) + def _own_color(kw, idx, head): + """`kw` (a trail's plot kwargs) with the color of the dataset's + head line, unless `kw` or the dataset's format string names one. + Left to the axes' color cycle a trail took the next color after + the head lines', which is its dataset's only when EVERY dataset + has a trail: ``chemtrails=[False, True]`` drew dataset 1's trail + in dataset 0's color (found with GH #299).""" + if "color" in kw or "c" in kw: + return kw + fmt_color = None + if isinstance(_fmt_at(idx), str) and _process_plot_format is not None: + try: + fmt_color = _process_plot_format(_fmt_at(idx))[2] + except Exception: # noqa: BLE001 - matplotlib reports it itself + fmt_color = None + if fmt_color is None: + kw["color"] = head.get_color() + return kw + + def _head_linewidths(linewidths, style=None): + """The line width of each dataset's HEAD line (the recent window): + `tail_linewidth` when given (GH #299), else the dataset's own. A + `style` with no reveal ('spin' draws every dataset in full, 'morph' + its own cloud) has no tail, so the lines keep their own width + there, as the warning `plot()` gives for it says.""" + if tail_linewidth is None or style in ("spin", "morph"): + return list(linewidths) + return [tail_linewidth] * len(linewidths) + + def _remember_linewidths(lines, linewidths, head_linewidths): + for line, base, head in zip(lines, linewidths, head_linewidths): + line._hyp_linewidths = (base, head) + + def _set_serial_linewidth(line, revealing): + """A serial reveal draws a finished dataset with its head line, in + full: `tail_linewidth` applies to that line only while it is the + comet head of the dataset being revealed (GH #299).""" + widths = getattr(line, '_hyp_linewidths', None) + if widths is not None and widths[0] != widths[1]: + line.set_linewidth(widths[1] if revealing else widths[0]) + + def _add_head_markers(ax, lines, head_linewidths, has_head): + """Create each dataset's `head_marker=` artist (GH #299): ONE + marker, placed at the last vertex of the dataset's head line on + every frame (`_place_head_marker`). Its color, alpha and size + follow the dataset unless the spec styles them: the head line's + color, the dataset's ``alpha=``, and the dataset's ``markersize=`` + (matplotlib's default marker size without one) -- but never less + than 2.5 times the head line's width, so the marker shows on a + thick tail. Never a legend entry.""" + if head_marker is None or not has_head: + return + for idx, (line, spec) in enumerate(zip(lines, head_marker)): + if spec is None: + continue + dataset_kw = (kwargs_list[idx] + if isinstance(kwargs_list[idx], dict) else {}) + props = dict(spec) + pinned = 'color' in props + props.setdefault('color', line.get_color()) + if dataset_kw.get('alpha') is not None: + props.setdefault('alpha', dataset_kw['alpha']) + props.setdefault('markersize', max( + float(dataset_kw.get('markersize') + or plt.rcParams['lines.markersize']), + 2.5 * float(head_linewidths[idx]))) + props.setdefault('zorder', line.get_zorder() + 1) + empty = ([], [], []) if hasattr(ax, 'get_proj') else ([], []) + (artist,) = ax.plot(*empty, linestyle='None', **props) + artist.set_label('_nolegend_') + artist.set_clip_on(False) + artist.set_in_layout(False) + artist._hyp_trace_index = idx + artist._hyp_trace_role = 'head_marker' + artist._hyp_color_pinned = pinned + line._hyp_head_marker = artist + # hidden with its line (a callback holds the line alone) + follow_artist(ax, artist, line) + + def _head_holders(reached): + """Which drawn runs carry their dataset's `head_marker=` on this + frame, given which of them the reveal has `reached`: ONE per + input dataset, the run its current point is in. + + `hue=` categories and `cluster=` cut a dataset into runs, each + its own line with its own marker artist; every run the reveal had + passed kept its marker at its last point, so a dataset in two + categories ended with two head markers, one stuck where the first + category stops (1.2.1 review round 4). The marker of the run that + holds the head is drawn, in that run's (the category's) color.""" + reached = [bool(flag) for flag in reached] + if ownership is None or ownership.n_runs != len(reached): + return reached + holds = [False] * len(reached) + for dataset in range(ownership.n_datasets): + runs = [r for r in ownership.runs_of(dataset) if reached[r]] + if runs: + holds[max(runs, key=lambda r: ownership.run_span(r)[0])] = True + return holds + + def _serial_head_holders(counts, lengths): + """`_head_holders` for a serial reveal, where a run is reached + once one of its rows is revealed. Before anything is (frame 0), + the first dataset that has rows holds its marker, at its first + point: frame 0 was an empty frame while a parallel reveal's + frame 0 already showed the head (1.2.1 review round 4).""" + reached = [count > 0 for count in counts] + if not any(reached): + first = next((i for i, n in enumerate(lengths) if n > 0), None) + return [i == first for i in range(len(reached))] + return _head_holders(reached) + + def _place_head_marker(line, points, holds=True): + """Move `line`'s `head_marker=` artist (if it has one) to the last + of the `points` the line was just given; no points, no marker. + Nor when the line is not the run that `holds` its dataset's head + (`_head_holders`).""" + artist = getattr(line, '_hyp_head_marker', None) + if artist is None: + return + last = np.asarray(points)[-1:] if holds else np.asarray(points)[:0] + artist.set_data(last[:, 0], last[:, 1]) + if last.shape[1] >= 3 and hasattr(artist, 'set_3d_properties'): + artist.set_3d_properties(last[:, 2]) + def _new_animation(fig, func, n_frames, fargs): """The animation object for frame function `func`: the `FuncAnimation` an ordinary animated plot returns, or -- for one cell of an animated panel grid (`panel_cell=True`) -- a `PanelAnimationStub` carrying the same function, arguments, frame - count and interval for the grid's single animation to drive.""" + count and interval for the grid's single animation to drive. + + `hold_frames` (``hold=``, GH #299) repeats the last frame at the + end: the frame SEQUENCE becomes ``0..n-1`` followed by ``n-1`` + that many times (`held_frame_sequence`), so the frame function -- + and every wrapper `plot()` puts around it later -- is simply + called with the last index again and nothing downstream has to + know about the hold. A panel cell never holds: its grid does.""" if _cell_ax is not None: return PanelAnimationStub(func, fargs, n_frames, 1000 / frame_rate, zoom_scale=_cell_zoom_scale) - return HyperFuncAnimation( - fig, func, n_frames, fargs=fargs, - interval=1000 / frame_rate, blit=False, repeat=False) + line_ani = HyperFuncAnimation( + fig, func, held_frame_sequence(n_frames, hold_frames), + fargs=fargs, interval=1000 / frame_rate, blit=False, + repeat=False) + line_ani._hyp_content_frames = int(n_frames) + # the factor every 3-D frame function multiplies its box zoom by: + # `plot._keep_cube_clear` lowers it when the turning cube would + # reach the canvas edge or a legend (GH #297) + line_ani._hyp_zoom_scale = _cell_zoom_scale + return line_ani def dispatch_animate(x, ani_params): """Dispatch to `animate_plot3D` or `animate_plot2D` based on `x[0]`'s column count. @@ -2370,11 +4833,7 @@ def animate_plot3D( # at some rotation angles, clipping cube corners and data ax.set_position([0.0, 0.0, 1.0, 1.0]) - # create lines. Trail artists are created whenever ANY dataset draws - # lines (previously is_line(fmt) required ALL datasets to be lines, - # which left `trail` undefined -- and the FuncAnimation call below - # crashed -- when fmts were mixed, e.g. after a single-point dataset's - # line fmt is converted to '.', or for marker-only animations). + # create lines. # # GH #127: chemtrails/precog/bullettime are now per-dataset lists # (broadcast/validated in `_draw` above), so a dataset only gets its @@ -2421,66 +4880,54 @@ def _wants_trail(idx): # collided when MultiIndex expansion assigned a per-trace alpha (faint # leaf traces vs. opaque group-mean traces), raising "got multiple # values for keyword argument 'alpha'". - def _trail_kwargs(kw): + def _trail_kwargs(kw, idx): kw = dict(kw) if isinstance(kw, dict) else {} - kw["alpha"] = 0.3 * kw.pop("alpha", 1.0) - return kw - - trail = [] - if fmt is not None: - lines = [ - ax.plot( - dat[0:1, 0], - dat[0:1, 1], - dat[0:1, 2], - fmt[idx], - linewidth=linewidths[idx], - **kwargs_list[idx] - )[0] - for idx, dat in enumerate(x) - ] - if any(is_line(f) for f in fmt): - trail = [ - ax.plot( - dat[0:1, 0], - dat[0:1, 1], - dat[0:1, 2], - fmt[idx], - linewidth=linewidths[idx], - **_trail_kwargs(kwargs_list[idx]) - )[0] if _wants_trail(idx) else None - for idx, dat in enumerate(x) - ] - else: - lines = [ - ax.plot( - dat[0:1, 0], - dat[0:1, 1], - dat[0:1, 2], + kw["alpha"] = trail_alpha * kw.pop("alpha", 1.0) + return _own_color(kw, idx, lines[idx]) + + head_linewidths = _head_linewidths(linewidths, style) + + # GH #299: a trail artist is created for EVERY dataset that asks for + # one, whatever its format. It used to be gated on `is_line` -- "is + # this a PURE line format" -- so a line+marker format ('-o', 'o-', + # '.-', '--s') silently got no chemtrails/precog/bullettime trail at + # all, and a markers-only dataset got its trail of faded markers + # only when some OTHER dataset of the call happened to be a pure + # line. The trail is drawn in the dataset's own format, exactly as + # its head is: a line+marker trail carries faded markers at the + # observations (`_mark_observations`), a markers-only trail is its + # faded markers -- what the plotly backend has always drawn. + def _fmt_of(idx): + return fmt[idx] if fmt is not None else None + + lines = [ + _plot_with_fmt( + ax, (dat[0:1, 0], dat[0:1, 1], dat[0:1, 2]), _fmt_of(idx), + linewidth=head_linewidths[idx], **kwargs_list[idx])[0] + for idx, dat in enumerate(x) + ] + trail = [ + _plot_with_fmt( + ax, (dat[0:1, 0], dat[0:1, 1], dat[0:1, 2]), _fmt_of(idx), linewidth=linewidths[idx], - **kwargs_list[idx] - )[0] - for idx, dat in enumerate(x) - ] - if is_line(fmt): - trail = [ - ax.plot( - dat[0:1, 0], - dat[0:1, 1], - dat[0:1, 2], - linewidth=linewidths[idx], - **_trail_kwargs(kwargs_list[idx]) - )[0] if _wants_trail(idx) else None - for idx, dat in enumerate(x) - ] - # trails are faint context, not legend-worthy: only the in-focus - # `lines` should carry legend entries. Otherwise every label appears - # twice -- once for the moving window, once for its tail. The legend is - # built once from `lines` (all datasets, created upfront), so it shows - # the static union of in-focus items and never changes across frames. - for _trail_line in trail: + **_trail_kwargs(kwargs_list[idx], idx))[0] + if _wants_trail(idx) else None + for idx, dat in enumerate(x) + ] + _remember_linewidths(lines, linewidths, head_linewidths) + # head_marker= (GH #299): created AFTER the trails, so the head + # lines and then the trails stay the axes' first line artists + # (`plot._apply_multicolor_animation` finds them by position) + _add_head_markers(ax, lines, head_linewidths, + style not in ("spin", "morph")) + for _idx, _trail_line in enumerate(trail): if _trail_line is not None: _trail_line.set_label('_nolegend_') + # which dataset the trail belongs to: with a per-dataset + # flag list not every dataset has one, so its place among + # the trails does not say + _trail_line._hyp_trace_index = _idx + _trail_line._hyp_trace_role = 'trail' # axes-box slicing fix (see `plot_cube`): unclip every data/trail # line artist -- Axes3D's shrunk-square viewport (`ax.get_position()` @@ -2854,6 +5301,8 @@ def update_lines_parallel_2d( num, total_frames, ownership, [d.shape[0] for d in data_lines], tail_duration) head_bounds = [] # GH #285 + _holders = (None if _windows is None else _head_holders( + [win.reached for win in _windows])) for i, (line, data, trail) in enumerate(itertools.zip_longest( lines, data_lines, trail_lines)): # same F05-001/F05-008/F04-003/F05-012 slicing fixes as the 3-D @@ -2885,6 +5334,8 @@ def update_lines_parallel_2d( window = _aa_window(i, start, end, artist=line) line.set_data(window[:, 0], window[:, 1]) + _place_head_marker(line, window, + _holders is None or _holders[i]) _sync_anim_labels(num, tail_duration, windows=head_bounds) if frame_hooks is not None: @@ -2915,6 +5366,7 @@ def update_lines_serial_2d(num, data_lines, lines, trail_lines, total_points = sum(lengths) revealed = total_points * num / max(1, total_frames - 1) _counts = serial_reveal_counts(lengths, num, total_frames) + _holders = _serial_head_holders(_counts, lengths) _head_windows = [] # GH #285 for i, (line, data, trail) in enumerate(itertools.zip_longest( @@ -2949,8 +5401,21 @@ def update_lines_serial_2d(num, data_lines, lines, trail_lines, head = _aa_window(i, *head_bounds, artist=line) trail_seg = (data[:0] if trail_bounds is None else _aa_window(i, *trail_bounds, artist=trail)) + if trail is not None and trail_bounds is None: + # no trail on this frame: say so on the artist as well, or + # a renderer that redraws it from its recorded rows + # (`plot._apply_multicolor_animation`) keeps showing the + # trail of the frame drawn before + trail._hyp_row_window = (0, 0) _head_windows.append(tuple(int(b) for b in head_bounds)) line.set_data(head[:, 0], head[:, 1]) + # (frame 0 of a serial reveal has drawn nothing yet: the + # head marker waits at the first dataset's first point, as a + # parallel reveal's frame 0 shows it there) + _place_head_marker( + line, head if len(head) or not _holders[i] else data[:1], + _holders[i]) + _set_serial_linewidth(line, trail_bounds is not None) if trail is not None: trail.set_data(trail_seg[:, 0], trail_seg[:, 1]) @@ -3093,57 +5558,46 @@ def _wants_trail(idx): # dataset kwargs already carry, so a per-trace alpha from MultiIndex # expansion does not collide with a bare `alpha=0.3` ("got multiple # values for keyword argument 'alpha'"). - def _trail_kwargs(kw): + def _trail_kwargs(kw, idx): kw = dict(kw) if isinstance(kw, dict) else {} - kw["alpha"] = 0.3 * kw.pop("alpha", 1.0) - return kw + kw["alpha"] = trail_alpha * kw.pop("alpha", 1.0) + return _own_color(kw, idx, lines[idx]) - trail = [] - if fmt is not None: - lines = [ - ax.plot( - dat[0:1, 0], - dat[0:1, 1], - fmt[idx], - linewidth=linewidths[idx], - **kwargs_list[idx] - )[0] - for idx, dat in enumerate(x) - ] - if any(is_line(f) for f in fmt): - trail = [ - ax.plot( - dat[0:1, 0], - dat[0:1, 1], - fmt[idx], - linewidth=linewidths[idx], - **_trail_kwargs(kwargs_list[idx]) - )[0] if _wants_trail(idx) else None - for idx, dat in enumerate(x) - ] - else: - lines = [ - ax.plot( - dat[0:1, 0], - dat[0:1, 1], + head_linewidths = _head_linewidths(linewidths, style) + + # every flagged dataset gets its trail, whatever its format (GH #299: + # see animate_plot3D) + def _fmt_of(idx): + return fmt[idx] if fmt is not None else None + + lines = [ + _plot_with_fmt( + ax, (dat[0:1, 0], dat[0:1, 1]), _fmt_of(idx), + linewidth=head_linewidths[idx], **kwargs_list[idx])[0] + for idx, dat in enumerate(x) + ] + trail = [ + _plot_with_fmt( + ax, (dat[0:1, 0], dat[0:1, 1]), _fmt_of(idx), linewidth=linewidths[idx], - **kwargs_list[idx] - )[0] - for idx, dat in enumerate(x) - ] - if is_line(fmt): - trail = [ - ax.plot( - dat[0:1, 0], - dat[0:1, 1], - linewidth=linewidths[idx], - **_trail_kwargs(kwargs_list[idx]) - )[0] if _wants_trail(idx) else None - for idx, dat in enumerate(x) - ] - for _trail_line in trail: + **_trail_kwargs(kwargs_list[idx], idx))[0] + if _wants_trail(idx) else None + for idx, dat in enumerate(x) + ] + _remember_linewidths(lines, linewidths, head_linewidths) + # head_marker= (GH #299): created AFTER the trails, so the head + # lines and then the trails stay the axes' first line artists + # (`plot._apply_multicolor_animation` finds them by position) + _add_head_markers(ax, lines, head_linewidths, + style not in ("spin", "morph")) + for _idx, _trail_line in enumerate(trail): if _trail_line is not None: _trail_line.set_label('_nolegend_') + # which dataset the trail belongs to: with a per-dataset + # flag list not every dataset has one, so its place among + # the trails does not say + _trail_line._hyp_trace_index = _idx + _trail_line._hyp_trace_role = 'trail' # animate='morph': single traveling point-cloud artist, exactly # mirroring `animate_plot3D`'s morph setup but in 2-D. @@ -3515,13 +5969,14 @@ def _trail_kwargs(kw): if legend is not None or legend_entries is not None: _legend_call = legend_call_kwargs( is_3d=hasattr(ax, "get_proj"), zlabel=zlabel, font=font, - legend_kwargs=legend_kwargs) + legend_kwargs=legend_kwargs, ax=ax) if legend_entries is not None: # explicit entries (matrix/mixture hue palette swatches, or # `legend_colors=[(label, color), ...]`): proxy handles, since # no drawn artist carries these labels. show_legend_keys(ax.legend( - handles=_legend_proxy_handles(legend_entries, fmt), + handles=_legend_proxy_handles(legend_entries, fmt, + legend_entry_styles), **_legend_call)) else: if legend_order: diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index 9bf1289f..f23f0686 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -14,6 +14,8 @@ import sys import warnings import matplotlib.pyplot as plt +from matplotlib.collections import PathCollection +from mpl_toolkits.mplot3d.art3d import Path3DCollection import numpy as np import pandas as pd # `np` also arrives via the star import below; naming it explicitly is @@ -35,7 +37,9 @@ _looks_like_dataset_palettes) from ..reduce.reduce import reduce as reducer from ..tools.format_data import format_data -from .matplotlib_backend import _draw, _apply_title, show_legend_keys +from .matplotlib_backend import (_draw, _apply_title, show_legend_keys, + content_frame_count, held_frame_sequence, + legend_entry_styles) from .backend import manage_backend from .plotly_backend import resolve_backend from .animation_context import FrameContext, FrameHooks @@ -1290,6 +1294,44 @@ def _regroup_categorical_lines(xform, hue, labels, cat_color, cat_label): run_category_names, seg_lengths, run_bridged) +def _trail_flag_per_run(value, name, seg_dataset, n_runs, n_datasets, + by_category): + """A per-dataset `chemtrails=`/`precog=`/`bullettime=` list, matched + to the caller's datasets after a categorical `hue=`/`cluster=` split + them into drawn runs: each run takes the flag of the dataset it + comes from (`seg_dataset`, as `_expand_styles_to_runs` does for + `fmt` and the styling kwargs). Anything that is not a list of one + entry per input dataset is returned as it is, for + `broadcast_trail_flag` to check. A markers-only plot is grouped by + CATEGORY instead (`by_category`): its traces are not datasets, so a + per-dataset list cannot be applied and is refused in those words.""" + if isinstance(value, np.ndarray): + value = value.tolist() + if not isinstance(value, (list, tuple)): + return value + if seg_dataset is not None and len(seg_dataset) == n_runs: + if n_datasets is None: + n_datasets = max(seg_dataset) + 1 + if len(value) == n_datasets: + return [value[dataset] for dataset in seg_dataset] + if len(value) != n_runs: + # (counted in the caller's datasets, not in the runs) + raise ValueError( + f"{name} list has {len(value)} entries but there are " + f"{n_datasets} datasets to plot; pass a single value to " + "apply it to every dataset, or a list matching the " + "dataset count.") + elif by_category and len(value) != n_runs: + raise ValueError( + f"{name} list has {len(value)} entries, but a markers-only " + f"plot colored by a categorical hue= or cluster= draws one " + f"trace per category ({n_runs} here), not one per dataset, " + f"so a per-dataset list cannot be applied; pass a single " + f"value to apply it to every category, or a format with a " + f"line (e.g. '-o'), which keeps the datasets apart.") + return value + + def _expand_styles_to_runs(fmt, mpl_kwargs, seg_dataset, n_datasets): """Propagate per-INPUT-DATASET styles across run segmentation (GH #291 follow-up). @@ -2124,6 +2166,11 @@ def _validate_extra_plot_kwargs(extra_kwargs): 'frame_rate': 30, 'focused': None, 'morph_samples': None, + # GH #299 + 'head_marker': None, + 'tail_linewidth': None, + 'trail_alpha': None, + 'hold': 0, } @@ -2441,6 +2488,145 @@ def _resolve_animate_mode(animate, n_datasets, order='parallel'): } +def _is_finite_number(value): + """Whether `value` is one real, finite number (never a bool).""" + return (isinstance(value, (int, float, np.integer, np.floating)) + and not isinstance(value, bool) and bool(np.isfinite(value))) + + +#: what each checked styling option must be, as the error says it +_STYLE_VALUE_NEEDS = { + 'fontsize': "a font size in points greater than 0, or one of {sizes}", + 'markersize': "a marker size in points greater than 0", + 'linespacing': "a line spacing (a multiple of the font size) greater " + "than 0", + 'fontweight': "a number from 0 to 1000 or one of {weights}", + 'fontstyle': "'normal', 'italic' or 'oblique'", + 'fontfamily': "a font family name or a list of them", + 'color': "a matplotlib color (a name such as 'gray', a hex string, " + "or an RGB(A) tuple)", + 'markeredgecolor': "a matplotlib color (a name such as 'gray', a hex " + "string, or an RGB(A) tuple)", + 'backgroundcolor': "a matplotlib color (a name such as 'gray', a hex " + "string, or an RGB(A) tuple)", + 'markerfacecolor': "a matplotlib color (a name such as 'gray', a hex " + "string, or an RGB(A) tuple), or 'none'", + 'markerfacecoloralt': "a matplotlib color (a name such as 'gray', a " + "hex string, or an RGB(A) tuple), or 'none'", + 'alpha': "a number between 0 and 1", + 'markeredgewidth': "a line width in points, 0 or more", + 'fillstyle': "one of {fillstyles}", + 'zorder': "a number", +} + +#: `title_kwargs=` keys that are arguments of `Axes.set_title` itself and +#: not properties of the title's `Text` +_SET_TITLE_ARGUMENTS = frozenset({'y', 'pad', 'loc'}) + + +def _check_style_values(style, name, given=None, marker=False): + """Refuse a bad VALUE in a dict of text or marker styling options + (`title_kwargs=`, `caption_kwargs=`, `suptitle_kwargs=`, and with + ``marker=True`` `head_marker=`), naming the argument and the key. + `style` is keyed by the resolved option names; `given` maps each back + to the key the caller wrote (an alias such as ``'size'``), which is + the one the error names. + + MATPLOTLIB DECIDES what a property accepts: every value is set on a + throwaway `Text` (or `Line2D`), and whatever matplotlib takes is + taken here: ``None`` for its default, a size as the string ``'12'``, + a weight as ``'700'``, ``alpha=True``, an edge color of ``'auto'``. + (The first version of this check, in the 1.2.1 draft, compared + against lists written by hand and refused all of those, which 1.2.0 + had drawn correctly.) What matplotlib refuses is refused here, with + the same error for every key. Beyond that only values that + matplotlib accepts and then draws nothing readable with, or fails on + later in the draw, are refused: a size, line spacing or edge width + that is not finite or not positive (matplotlib quietly draws a + negative or zero font size at 1 pt and a NaN one not at all), a line + spacing or z-order that is not a number, a font family that is not + a name or a list of names, and a text color of ``'auto'``.""" + from matplotlib import font_manager + from matplotlib.markers import MarkerStyle + given = given or {} + + def _refuse(option, reason=None): + key = given.get(option, option) + need = _STYLE_VALUE_NEEDS.get( + option, "a value matplotlib accepts for this property") + need = need.format( + sizes=', '.join(size for size in font_manager.font_scalings + if isinstance(size, str)), + weights=', '.join(font_manager.weight_dict), + fillstyles=', '.join(MarkerStyle.fillstyles)) + if option not in _STYLE_VALUE_NEEDS and reason: + need += f" (matplotlib: {reason})" + raise ValueError( + f"{name}[{key!r}] must be {need}; got {style[option]!r}.") + + def _number(value): + """`value` as the float matplotlib reads it as, or None for a + name (a font size such as 'large').""" + try: + return float(value) + except (TypeError, ValueError): + return None + + for option, value in style.items(): + if option in _SET_TITLE_ARGUMENTS or option in ('position',) \ + or (option == 'loc') or (marker and option == 'marker'): + continue + try: + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + if marker: + from matplotlib.lines import Line2D + Line2D([0], [0], **{option: value}) + else: + import matplotlib.text as mtext + mtext.Text().update({option: value}) + except Exception as error: # whatever matplotlib raises + _refuse(option, str(error)) + if value is None: + continue # matplotlib's own default + if option in ('fontsize', 'markersize', 'linespacing', + 'markeredgewidth'): + number = _number(value) + if number is None: + if option != 'fontsize': + _refuse(option) + elif not np.isfinite(number) or number < 0 or ( + number == 0 and option != 'markeredgewidth'): + _refuse(option) + elif option == 'fontfamily': + # (matplotlib stores any family and only looks the names up + # when the text is drawn: an unknown name, an empty one or + # an empty list falls back to the default font, with + # matplotlib's own "not found" log line. A family that is + # not a name or a list of names fails in the draw.) + names = [value] if isinstance(value, str) else value + if not isinstance(names, (list, tuple)) or not all( + one is None or isinstance(one, str) for one in names): + _refuse(option) + elif option in ('color', 'backgroundcolor') and not marker: + # (`Text.set_color('auto')` is accepted and then fails when + # the text is drawn) + from matplotlib.colors import is_color_like + if not is_color_like(value): + _refuse(option) + elif option in ('markeredgecolor', 'markerfacecolor', + 'markerfacecoloralt'): + # (a `Line2D` takes any edge or face color and fails on a + # bad one when it is drawn) + from matplotlib.colors import is_color_like + if not (isinstance(value, str) and value == 'auto') \ + and not is_color_like(value): + _refuse(option) + elif option == 'zorder': + if _number(value) is None or isinstance(value, str): + _refuse(option) + + def _normalize_title_kwargs(title_kwargs, _name='title_kwargs'): """Resolve `title_kwargs=`'s short aliases and reject unknown keys. @@ -2454,7 +2640,7 @@ def _normalize_title_kwargs(title_kwargs, _name='title_kwargs'): f"{_name}= must be a dict of title styling options (e.g. " f"{{'size': 20, 'weight': 'bold', 'color': 'k', 'y': 0.93}}); " f"got {type(title_kwargs).__name__}: {title_kwargs!r}.") - resolved = {} + resolved, given = {}, {} for key, value in title_kwargs.items(): name = _TITLE_KWARG_ALIASES.get(key, key) if name not in _TITLE_KWARG_KEYS: @@ -2464,6 +2650,8 @@ def _normalize_title_kwargs(title_kwargs, _name='title_kwargs'): f"parentheses): {sorted(_TITLE_KWARG_KEYS)} " f"(aliases: {sorted(_TITLE_KWARG_ALIASES)}).") resolved[name] = value + given[name] = key + _check_style_values(resolved, _name, given) return resolved @@ -3165,6 +3353,266 @@ def _validate_loop(loop, style): return True +# -------------------------------------------------------------------------- +# GH #299: `head_marker=`, `tail_linewidth=`, `trail_alpha=`, `hold=`. +# -------------------------------------------------------------------------- + +#: Short aliases accepted in a `head_marker=` dict, mapped onto the +#: matplotlib `Line2D` property names. +_HEAD_MARKER_ALIASES = { + 'size': 'markersize', + 'edgecolor': 'markeredgecolor', + 'edgewidth': 'markeredgewidth', + 'facecolor': 'markerfacecolor', + 'facecoloralt': 'markerfacecoloralt', + 'fillstyle': 'fillstyle', + # matplotlib's own short names, which `hyp.plot` takes as keyword + # arguments for the datasets' markers (1.2.1 review round 4: a + # `head_marker=` dict refused them) + 'ms': 'markersize', + 'mec': 'markeredgecolor', + 'mew': 'markeredgewidth', + 'mfc': 'markerfacecolor', + 'mfcalt': 'markerfacecoloralt', + 'c': 'color', +} + +#: Every key a `head_marker=` dict accepts after alias resolution. +_HEAD_MARKER_KEYS = frozenset({ + 'marker', 'markersize', 'color', 'alpha', 'markeredgecolor', + 'markeredgewidth', 'markerfacecolor', 'markerfacecoloralt', + 'fillstyle', 'zorder', +}) + + +def _matplotlib_only_animation_argument(name, what): + """The error a frame-driven matplotlib argument raises on plotly.""" + return NotImplementedError( + f"{name}= is matplotlib-only. On plotly an animation is a list of " + f"go.Frame payloads, so {what} would have to be rebuilt inside " + "every frame's payload -- separate work from the matplotlib " + f"artists this draws. Pass backend='matplotlib' for {name}=, or " + f"drop {name}=.") + + +def _validate_head_marker(head_marker, backend_name): + """`head_marker=` -> a dict of `Line2D` marker properties (always with + ``'marker'``), or None (GH #299). + + ``True`` is ``'o'``; a string (or any other matplotlib marker) is the + marker; a dict styles it (``'marker'`` defaults to ``'o'``; ``size``, + ``edgecolor``, ``edgewidth`` and ``facecolor`` are short for + ``markersize``, ``markeredgecolor``, ``markeredgewidth`` and + ``markerfacecolor``, and matplotlib's own ``ms``/``mec``/``mew``/ + ``mfc``/``mfcalt``/``c`` are taken as well). ``None``/``False`` is no + head marker. + """ + if isinstance(head_marker, np.bool_): + head_marker = bool(head_marker) + if head_marker is None or head_marker is False: + return None + if isinstance(head_marker, bytes): + head_marker = head_marker.decode('utf-8') + if head_marker is True: + spec = {'marker': 'o'} + elif isinstance(head_marker, dict): + spec, given = {}, {} + for key, value in head_marker.items(): + name = _HEAD_MARKER_ALIASES.get(key, key) + if name not in _HEAD_MARKER_KEYS: + raise ValueError( + f"head_marker={{{key!r}: ...}} is not a supported head " + f"marker option. Supported keys (short aliases in " + f"parentheses): {sorted(_HEAD_MARKER_KEYS)} (aliases: " + f"{sorted(_HEAD_MARKER_ALIASES)}).") + if name in given: + # (matplotlib refuses a property given under two names + # too; the later one silently won here) + raise ValueError( + f"head_marker= names one option twice: {given[name]!r} " + f"and {key!r} are both the marker's {name}. Pass one " + "of them.") + spec[name] = value + given[name] = key + # (the values too: a size of -3, 0 or NaN drew no marker and said + # nothing; a wrong color or an alpha of 2 raised from matplotlib + # without naming `head_marker=`) + _check_style_values(spec, 'head_marker', given, marker=True) + # (None is matplotlib's "the default": the marker then follows + # the dataset as if the key had not been written) + spec = {key: value for key, value in spec.items() + if value is not None} + if isinstance(spec.get('marker'), (bool, np.bool_)): + # `{'marker': True}` is `head_marker=True`: matplotlib reads + # a bare True as marker number 1, a tick mark + if not spec['marker']: + return None + spec['marker'] = 'o' + spec.setdefault('marker', 'o') + else: + spec = {'marker': head_marker} + from matplotlib.markers import MarkerStyle + marker = spec['marker'] + try: + MarkerStyle(marker) + # (a marker may also be a path, a tuple or an array of vertices, + # which cannot be compared with the "no marker" names) + drawable = not (isinstance(marker, str) + and marker in ('', ' ', 'None', 'none')) + except (ValueError, TypeError): + drawable = False + if not drawable: + raise ValueError( + f"head_marker= needs a matplotlib marker (e.g. 'o', '*', 'D'), " + f"True for 'o', or a dict such as {{'marker': 'o', 'size': 9, " + f"'color': 'k'}}; got {head_marker!r}.") + if backend_name == 'plotly': + raise _matplotlib_only_animation_argument( + 'head_marker', 'a marker at the reveal head') + return spec + + +def _validate_tail_linewidth(tail_linewidth, backend_name): + """`tail_linewidth=` -> a positive float, or None (GH #299).""" + if tail_linewidth is None: + return None + if isinstance(tail_linewidth, bool) or not isinstance( + tail_linewidth, (int, float, np.integer, np.floating)) \ + or not np.isfinite(tail_linewidth) or tail_linewidth <= 0: + raise ValueError( + "tail_linewidth= must be a positive number: the line width, in " + "points, of the tail (the recent window `tail_duration=` " + f"sizes); got {tail_linewidth!r}.") + if backend_name == 'plotly': + raise _matplotlib_only_animation_argument( + 'tail_linewidth', "the tail's own line width") + return float(tail_linewidth) + + +#: the factor a trail's alpha is the dataset's alpha times, without +#: `trail_alpha=` +DEFAULT_TRAIL_ALPHA = 0.3 + + +def _validate_trail_alpha(trail_alpha): + """`trail_alpha=` -> a float in [0, 1], or None (GH #299).""" + if trail_alpha is None: + return None + if isinstance(trail_alpha, bool) or not isinstance( + trail_alpha, (int, float, np.integer, np.floating)) \ + or not 0.0 <= trail_alpha <= 1.0: + raise ValueError( + "trail_alpha= must be a number between 0 and 1: the opacity of " + "a chemtrails/precog/bullettime trail, as a fraction of its " + f"dataset's own alpha (default {DEFAULT_TRAIL_ALPHA}); got " + f"{trail_alpha!r}.") + return float(trail_alpha) + + +def _validate_hold(hold, style, frame_rate, backend_name): + """`hold=` (seconds) -> how many times the last frame is repeated at + the end of the animation: ``round(hold * frame_rate)`` (GH #299). + + A hold shorter than half a frame is therefore no frame at all, and + that is said in a warning (1.2.1 review round 4: ``hold=0.01`` added + nothing and said nothing).""" + if hold is None or hold is False: + return 0 + if isinstance(hold, bool) or not isinstance( + hold, (int, float, np.integer, np.floating)) \ + or not np.isfinite(hold) or hold < 0: + raise ValueError( + "hold= must be a number of seconds, 0 or more: how long the " + f"last frame is held at the end of the animation; got {hold!r}.") + if hold == 0: + return 0 + if isinstance(style, (list, tuple)): + animated = len(style) > 0 + else: + animated = bool(style) + if not animated: + raise ValueError( + "hold= requires an animated plot; pass animate=True (or " + "'spin'/'serial'/'window'/'morph').") + if backend_name == 'plotly': + raise _matplotlib_only_animation_argument( + 'hold', 'the held frames') + frames = int(round(float(hold) * float(frame_rate))) + if frames == 0: + warnings.warn( + f"hold={hold!r} is shorter than half a frame at frame_rate=" + f"{frame_rate!r} and adds no frame: the hold is round(hold * " + f"frame_rate) repeats of the last frame. Pass hold=" + f"{1.0 / float(frame_rate):.3g} or more to hold for at least " + "one frame.", + UserWarning, stacklevel=external_stacklevel()) + return frames + + +def _warn_ignored_grid_styling(cases): + """`_warn_ignored_animation_styling` for a `panels=` grid, once for + the whole figure: `cases` are the panels' own cases, and an argument + is ignored only when NO panel draws what it styles.""" + if cases: + _warn_ignored_animation_styling(**dict( + cases[0], + any_trail=any(case['any_trail'] for case in cases), + any_line=any(case['any_line'] for case in cases))) + + +def _warn_ignored_animation_styling(animate, head_marker, tail_linewidth, + trail_alpha, any_trail, any_line=True): + """Say so when `head_marker=`/`tail_linewidth=`/`trail_alpha=` cannot + apply (GH #299), as the trail flags do: on a static plot, on a style + with no reveal head ('spin', 'morph'), for `trail_alpha=` when no + dataset draws a trail, and for `tail_linewidth=` when no dataset is + drawn with a line (`any_line`: a markers-only format has no line to + widen).""" + given = [name for name, value in (('head_marker', head_marker), + ('tail_linewidth', tail_linewidth), + ('trail_alpha', trail_alpha)) + if value is not None] + if not given: + return + if not animate: + warnings.warn( + f"{'/'.join(given)} only " + f"{'affects' if len(given) == 1 else 'affect'} ANIMATED plots " + "and will be ignored here; pass animate=True (or 'parallel').", + UserWarning, stacklevel=external_stacklevel()) + return + if animate in ('spin', 'morph'): + warnings.warn( + f"animate={animate!r} has no reveal head, tail or trail; " + f"ignoring {'/'.join(given)}", + UserWarning, stacklevel=external_stacklevel()) + return + if trail_alpha is not None and animate == 'window': + # (not "pass chemtrails=True": the caller may well have, and + # 'window' is what draws no trail; 1.2.1 review round 4) + warnings.warn( + "trail_alpha= sets the opacity of chemtrails/precog/bullettime " + "trails, and animate='window' draws none (it shows the " + "sliding window alone); ignoring it. Use animate=True or " + "'serial' with chemtrails=True (or precog=/bullettime=) for a " + "trail.", + UserWarning, stacklevel=external_stacklevel()) + elif trail_alpha is not None and not any_trail: + warnings.warn( + "trail_alpha= sets the opacity of chemtrails/precog/bullettime " + "trails, and this animation draws none; ignoring it. Pass " + "chemtrails=True (or precog=/bullettime=) with animate=True or " + "'serial' to draw one.", + UserWarning, stacklevel=external_stacklevel()) + if tail_linewidth is not None and not any_line: + warnings.warn( + "tail_linewidth= sets the width of the tail's line, and no " + "dataset of this animation is drawn with a line (a " + "markers-only format such as 'o'); ignoring it. Use a format " + "with a line ('-', '-o') or size the markers with markersize=.", + UserWarning, stacklevel=external_stacklevel()) + + def _validate_dataset_fade(dataset_fade, style, order): """`dataset_fade=` -> ``(floor, decay)`` or None (GH #285). @@ -3269,15 +3717,26 @@ def _update(ctx): return n = len(counts) for i, artist in enumerate(ctx.artists): - # heads are artists 0..n-1; trails (when any) follow in the - # same dataset order, so artist n + i belongs to dataset i. - dataset = i if i < n else i - n - if dataset >= n: + # heads are artists 0..n-1; trails (when any) follow in + # dataset order. A trail says which dataset it belongs to + # (`_hyp_trace_index`): with a per-dataset flag list such as + # ``chemtrails=[False, True]`` not every dataset has one, so + # its place among the trails does not. + dataset = i if i < n else getattr( + artist, '_hyp_trace_index', i - n) + if dataset is None or dataset >= n: continue alpha = dataset_fade_alpha(dataset, current, counts[dataset], floor, decay) if hasattr(artist, 'set_alpha'): # matplotlib artist artist.set_alpha(alpha) + # its `head_marker=` and, with a continuous `hue=`, the + # markers of a line-and-marker format fade with the + # dataset (GH #299) + for _name in ('_hyp_head_marker', '_hyp_markers'): + _follower = getattr(artist, _name, None) + if _follower is not None: + _follower.set_alpha(alpha) else: # plotly trace artist.opacity = alpha return _update @@ -4001,6 +4460,53 @@ def _panel_narrow_kwargs(kw, index, n_datasets, lengths): _panel_slice_forecast_kwargs(kw, index, n_datasets, grid_kw) kw['predict'] = _panel_bind_forecaster(kw['predict'], index, n_datasets) + kw['_legend_entry_styles'] = _panel_legend_entry_styles(grid_kw, + n_datasets) + + +def _panel_legend_entry_styles(grid_kw, n_datasets): + """The grid's `legend_entry_styles`, from the WHOLE grid's kwargs. + + A ``(label, color)`` pair list is forwarded to every panel unchanged, + and a panel draws one dataset, so no panel can pair the entries with + the datasets itself. One entry per dataset of the grid (nothing + regrouping the traces, as in `_panel_slice_legend`) is paired here, + with each dataset's own `fmt` and line styling narrowed out of the + grid's per-dataset arguments by the rule the panels use + (`_panel_slice_per_dataset`). None otherwise: plain swatches. + """ + from .matplotlib_backend import (LEGEND_KEY_STYLE_KEYS, + legend_entry_styles) + try: + _, entries = _normalize_legend_colors(grid_kw.get('legend_colors')) + except (TypeError, ValueError): + return None + if entries is None or len(entries) != n_datasets: + return None + if (grid_kw.get('hue') is not None or grid_kw.get('cluster') + or grid_kw.get('n_clusters') is not None): + return None + + def _own(value, index): + """Dataset `index`'s value of one per-dataset argument, or None.""" + value = _panel_slice_per_dataset(value, index, n_datasets) + if isinstance(value, (list, tuple)): + value = value[0] if len(value) == 1 else None + return value + + aliases = {'linestyle': ('linestyle', 'linestyles'), + 'marker': ('marker', 'markers')} + per_dataset, fmts = [], [] + for index in range(n_datasets): + style = {} + for key in LEGEND_KEY_STYLE_KEYS: + for name in aliases.get(key, (key,)): + value = _own(grid_kw.get(name), index) + if value is not None and np.ndim(value) == 0: + style[key] = value + per_dataset.append(style) + fmts.append(_own(grid_kw.get('fmt'), index)) + return legend_entry_styles(entries, fmts, per_dataset) def _panel_slice_per_observation(value, index, lengths): @@ -4150,6 +4656,24 @@ def _labels_as_lists(labels, n_datasets): return out +def _any_label_given(labels): + """Whether `labels=` names at least one observation: anything but + None, an empty sequence, or (flat or one sequence per dataset) all + None. A sequence may be a list, a tuple, an array or a Series, as + everywhere `labels=` is read (`_labels_as_lists`).""" + def _entries(value): + if value is None or is_text_item(value): + return [value] + if is_array_dataset(value) or is_series_like(value): + return np.asarray(value, dtype=object).ravel().tolist() + if isinstance(value, (list, tuple)): + return list(value) + return [value] + + return any(one is not None + for row in _entries(labels) for one in _entries(row)) + + def _flatten_dataset_labels(labels): """A nested per-dataset `labels=` (one sub-list per dataset) as the flat one-entry-per-observation list; a flat one is returned unchanged.""" @@ -4520,6 +5044,112 @@ def _panel_cluster_labels(probe_labels, model, spec, rows=None, #: blank room (inches) kept above and below the caption's text _CAPTION_PAD_IN = 0.1 +#: ``gid`` of the figure-level title `suptitle=` draws (GH #299) +SUPTITLE_GID = 'hypertools-suptitle' + +#: the figure-level texts hypertools reserves a measured strip for +_FIGURE_TEXT_GIDS = (CAPTION_GID, SUPTITLE_GID) + +#: Short aliases accepted in `caption_kwargs=`/`suptitle_kwargs=` (the +#: ones `title_kwargs=` accepts). +_FIGURE_TEXT_ALIASES = { + 'size': 'fontsize', + 'weight': 'fontweight', + 'family': 'fontfamily', + 'style': 'fontstyle', +} + +#: Every key `caption_kwargs=`/`suptitle_kwargs=` accept after alias +#: resolution: font and color options applied to the text BEFORE its room +#: is measured, plus where it goes (``position``: 'bottom' or 'top' of the +#: figure, `caption_kwargs=` only; ``loc``: 'center', 'left' or 'right'). +_FIGURE_TEXT_KEYS = frozenset({ + 'fontsize', 'fontweight', 'fontfamily', 'fontstyle', 'color', 'alpha', + 'linespacing', 'loc', 'position', +}) + + +def _validate_figure_text_kwargs(kwargs, name, given=True, + allow_position=True): + """Resolve `caption_kwargs=`/`suptitle_kwargs=` (GH #299): aliases + mapped, unknown keys and bad ``position``/``loc`` values refused by + name. Returns a dict (empty without styling). `given` is whether the + text the options style was passed: styling for a text that is not + there is refused, not ignored.""" + if kwargs is None: + return {} + what = name.rsplit('_', 1)[0] + if not isinstance(kwargs, dict): + raise TypeError( + f"{name}= must be a dict of styling options (e.g. " + f"{{'size': 14, 'color': 'gray', 'loc': 'left'}}); got " + f"{type(kwargs).__name__}: {kwargs!r}.") + if not given: + raise ValueError( + f"{name}= styles the text of {what}=, and no {what}= was " + f"given; pass {what}= or drop {name}=.") + keys = _FIGURE_TEXT_KEYS if allow_position \ + else _FIGURE_TEXT_KEYS - {'position'} + resolved, written = {}, {} + for key, value in kwargs.items(): + option = _FIGURE_TEXT_ALIASES.get(key, key) + if option not in keys: + raise ValueError( + f"{name}={{{key!r}: ...}} is not a supported styling " + f"option. Supported keys (short aliases in parentheses): " + f"{sorted(keys)} (aliases: {sorted(_FIGURE_TEXT_ALIASES)}).") + resolved[option] = value + written[option] = key + # (None is "the default", as in matplotlib: as if the key had not + # been written) + resolved = {option: value for option, value in resolved.items() + if value is not None} + _check_style_values(resolved, name, written) + if resolved.get('position', 'bottom') not in ('bottom', 'top'): + raise ValueError( + f"{name}['position'] must be 'bottom' (under the figure, the " + f"default) or 'top' (above it); got {resolved['position']!r}.") + if resolved.get('loc', 'center') not in ('center', 'left', 'right'): + raise ValueError( + f"{name}['loc'] must be 'center' (the default), 'left' or " + f"'right'; got {resolved['loc']!r}.") + return resolved + + +def _validate_suptitle(suptitle, suptitle_kwargs, backend_name, ax=None): + """`suptitle=` -> ``(text, style)`` (GH #299): one fixed title for + the whole FIGURE, above everything it holds -- what a `panels=` grid, + whose `title=` names its panels, has no other argument for. Both are + empty without one. Refused where a caption is (`_validate_caption`): + on plotly and with a caller's ``ax=``.""" + if isinstance(suptitle, bytes): + suptitle = suptitle.decode('utf-8') + if suptitle is not None and not isinstance(suptitle, str): + raise TypeError( + "suptitle= must be a string (one title for the whole figure); " + f"got {type(suptitle).__name__}: {suptitle!r}. For a title " + "that changes on every frame, use caption= with " + "caption_kwargs={'position': 'top'}.") + given = suptitle is not None and bool(suptitle.strip()) + style = _validate_figure_text_kwargs( + suptitle_kwargs, 'suptitle_kwargs', given=given, + allow_position=False) + if not given: + return None, {} + if backend_name == 'plotly': + raise NotImplementedError( + "suptitle= is matplotlib-only: it is a matplotlib text in a " + "strip hypertools measures and adds above the figure. Pass " + "backend='matplotlib' for suptitle=, or drop it (title= works " + "on both backends).") + if ax is not None: + raise ValueError( + "suptitle= is drawn above the whole figure, which hypertools " + "resizes to make room for it, so it cannot be combined with a " + "caller-supplied ax=. Drop ax= (or use panels= for a grid), or " + "add the title yourself with ax.figure.suptitle(...).") + return suptitle, style + def _validate_caption(caption, row_indices, backend_name, ax=None): """Split `caption=` into ``(static_text, dynamic)`` (GH #295). @@ -4581,7 +5211,14 @@ def _grow_figure(fig, left=0.0, right=0.0, top=0.0, bottom=0.0): pass placed = [(axis, axis.get_position(original=True), axis.get_position()) for axis in fig.axes] + # hypertools' own figure-level texts (the caption, the suptitle) keep + # their place in inches too -- they are positioned in figure fractions + strip_texts = [(text, text.get_position()) for text in fig.texts + if text.get_gid() in _FIGURE_TEXT_GIDS] fig.set_size_inches(new_w_in, new_h_in) + for text, (x, y) in strip_texts: + text.set_position(((x * w_in + left) / new_w_in, + (y * h_in + bottom) / new_h_in)) for axis, original, active in placed: for which, pos in (('original', original), ('active', active)): axis.set_position( @@ -4614,6 +5251,19 @@ def _blank_bottom_in(fig): return max(0.0, bottom) +def _blank_top_in(fig): + """`_blank_bottom_in`'s counterpart for the TOP of `fig`: the inches + between the highest thing drawn and the canvas' top edge.""" + try: + box = fig.get_tightbbox(_measurement_renderer(fig)) + top = float(fig.get_size_inches()[1]) - float(box.y1) + except Exception: # noqa: BLE001 - an unmeasurable figure: assume none + return 0.0 + if not np.isfinite(top): + return 0.0 + return max(0.0, top) + + #: blank room (inches) kept between the caption and the canvas' side edges _CAPTION_SIDE_PAD_IN = 0.1 @@ -4625,6 +5275,17 @@ def _caption_sample_frames(n_frames): return sorted({0, n_frames // 2, n_frames - 1}) +def _caption_text_frames(n_frames): + """The frames whose TEXTS size a per-frame caption's room: every + frame of the animation, so the room holds the tallest text the + caption ever shows (1.2.1 review round 2; it was the first, middle + and last, and a caption that was tallest on another frame ran off + the canvas). Getting a frame's text costs one run of the frame's + updater and of the caller's function, nothing is rendered, and equal + texts are measured once (`_add_caption`).""" + return range(max(int(n_frames), 1)) + + def _static_axes_artists(ax): """The data artists a finished static axes holds (its lines, then its collections): a static plot's ``FrameContext.artists``.""" @@ -4746,8 +5407,11 @@ def _set_caption_text(artist, text): artist.set_text(_wrap_caption(artist, text)) -def _add_caption(fig, text, font=None, family=None, samples=()): +def _add_caption(fig, text, font=None, family=None, samples=(), style=None, + gid=CAPTION_GID, settle=None): """Draw `text` as `fig`'s caption (GH #295) and return its ``Text``. + The figure-level `suptitle=` is drawn by this same function (GH #299: + ``gid=SUPTITLE_GID``, at the top). The caption is centered under everything the figure holds, a small gap below the lowest thing drawn (`_blank_bottom_in`). It is WRAPPED to @@ -4776,33 +5440,99 @@ def _add_caption(fig, text, font=None, family=None, samples=()): `font` is the resolved explicit ``font=`` (a ``FontProperties``), and `family` the fallback font stack used without one -- the caption is styled like the title beside it. + + `style` (`caption_kwargs=`/`suptitle_kwargs=`, GH #299, as + `_validate_figure_text_kwargs` resolves them) is applied to the text + BEFORE anything is measured, so the wrapping and the room are those of + the text as it is drawn, at any size. ``position='top'`` puts the + text ABOVE everything the figure holds instead (`_blank_top_in`; the + figure grows upward by what is missing) and ``loc`` aligns it with the + figure's left or right edge. `settle` is, for an animation, a pair + ``(draw, frames)``: the room above the figure is the least found over + those frames (``draw(frame)`` draws one; a per-frame title has a + different height on each), and the figure is left showing the first. """ from matplotlib.font_manager import FontProperties + style = dict(style or {}) + position = style.pop('position', 'bottom') + loc = style.pop('loc', 'center') text = '' if text is None else str(text) if font is not None: props = FontProperties(font) if isinstance(font, str) else font.copy() else: props = FontProperties(family=family or sans_serif_stack()) props.set_size(plt.rcParams['font.size']) + if gid == SUPTITLE_GID: + # a figure title's default size and weight are matplotlib's own + props.set_size(plt.rcParams['figure.titlesize']) + props.set_weight(plt.rcParams['figure.titleweight']) + if 'fontfamily' in style: + props.set_family(style.pop('fontfamily')) + if 'fontsize' in style: + props.set_size(style.pop('fontsize')) + if 'fontweight' in style: + props.set_weight(style.pop('fontweight')) + if 'fontstyle' in style: + props.set_style(style.pop('fontstyle')) # placed for good below, once its wrapped height is known - artist = fig.text(0.5, 0.0, '', ha='center', va='top', - fontproperties=props, gid=CAPTION_GID) + top = position == 'top' + artist = fig.text(0.5, 0.0, '', ha=loc, va='bottom' if top else 'top', + fontproperties=props, gid=gid, **style) # excluded from the "lowest thing drawn" measurement artist.set_visible(False) wrapped = _wrap_caption(artist, text) - candidates = [wrapped] + [_wrap_caption(artist, str(sample)) - for sample in samples] + # (each different text once: a per-frame caption is sampled on every + # frame and mostly repeats itself) + candidates = [wrapped] + [ + _wrap_caption(artist, sample) for sample in dict.fromkeys( + str(sample) for sample in samples) if sample != text] line_in = 1.2 * props.get_size_in_points() / 72.0 text_in = max(max((candidate.count('\n') + 1) * line_in, _caption_text_height_in(artist, candidate)) for candidate in candidates) strip_in = text_in + 2 * _CAPTION_PAD_IN - blank_in = _blank_bottom_in(fig) + # the tallest text this artist will ever show (a per-frame caption + # shows frame 0's now): what a text added later must stay clear of + artist._hyp_tallest_text = max( + candidates, key=lambda candidate: _caption_text_height_in( + artist, candidate)) + # ...and the texts already on the figure are measured at THEIR + # tallest: a suptitle placed against a top caption's first-frame text + # sat in the room the caption's later, longer texts grow into + earlier = [(other, other.get_text()) for other in fig.texts + if other is not artist + and other.get_gid() in _FIGURE_TEXT_GIDS + and getattr(other, '_hyp_tallest_text', None) is not None] + for other, _shown in earlier: + other.set_text(other._hyp_tallest_text) + try: + if top and settle is not None: + draw, frames = settle + frames = list(frames) + blank_in = None + for frame in frames + frames[:1]: + draw(frame) + found = _blank_top_in(fig) + blank_in = found if blank_in is None \ + else min(blank_in, found) + else: + blank_in = _blank_top_in(fig) if top else _blank_bottom_in(fig) + finally: + for other, shown in earlier: + other.set_text(shown) if blank_in < strip_in: - _grow_figure_downward(fig, strip_in - blank_in) + if top: + _grow_figure(fig, top=strip_in - blank_in) + else: + _grow_figure_downward(fig, strip_in - blank_in) blank_in = strip_in - _, h_in = fig.get_size_inches() - artist.set_position((0.5, (blank_in - _CAPTION_PAD_IN) / h_in)) + w_in, h_in = fig.get_size_inches() + x = {'center': 0.5, 'left': _CAPTION_SIDE_PAD_IN / w_in, + 'right': 1.0 - _CAPTION_SIDE_PAD_IN / w_in}[loc] + if top: + artist.set_position((x, 1.0 - (blank_in - _CAPTION_PAD_IN) / h_in)) + else: + artist.set_position((x, (blank_in - _CAPTION_PAD_IN) / h_in)) artist.set_text(wrapped) artist.set_visible(True) return artist @@ -4836,8 +5566,9 @@ def _panel_probe(data, kw, ndims, caught_warnings, panel_shared=None): reduces to RGB is not reduced again by the grid's color resolution (`_matrix_hue_to_rgb_once`).""" probe_kwargs = dict(kw) - if panel_shared: - probe_kwargs['_panel_shared'] = dict(panel_shared) + # (whether a styling argument is ignored is said once, for the whole + # figure, by the grid that draws: `_warn_ignored_grid_styling`) + probe_kwargs['_panel_shared'] = dict(panel_shared or {}, styling=[]) probe_kwargs.update(return_model=True, show=False, save_path=None, colorbar=None, legend=None, labels=None, names=None, surface=None, density=None, title=None) @@ -5036,7 +5767,8 @@ def _panel_dataset_colors(grid_kw, sources): 'axis_scale', 'title', 'title_kwargs', 'title_color', 'title_wrap', 'frame_kwargs', 'dataset_fade', 'slow_warning_seconds', 'backend', 'mpl_backend', 'show', 'save_path', 'return_model', 'ax', 'panels', - 'subplots', 'panel_fit', 'caption') + 'subplots', 'panel_fit', 'caption', 'caption_kwargs', 'suptitle', + 'suptitle_kwargs', 'hold') #: ...and the ones that ask for the legend and the colorbar, left out of #: the resolution `panel_fit='independent'` runs BEFORE its panels are fit @@ -5151,6 +5883,8 @@ def _resolve_grid_colors(rows, grid_kw, ndims, caught_warnings, call_shared['matrix_cache'] = matrix_cache if column_names is not None: call_shared['series_columns'] = column_names + # (not this call's to say: `_warn_ignored_grid_styling`) + call_shared['styling'] = [] with warnings.catch_warnings(record=True) as caught: warnings.simplefilter('always') probe = plot(rows, reduce=None, normalize=None, align=None, @@ -6240,6 +6974,19 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): # validated here, before any panel is analyzed, and drawn below caption, dynamic_caption = _validate_caption( call_kwargs.get('caption'), _capture_row_indices(x), backend) + # ...and so do its styling, the figure-level `suptitle=` and `hold=` + # (GH #299): the grid is the one animation, so the grid holds + caption_style = _validate_figure_text_kwargs( + call_kwargs.get('caption_kwargs'), 'caption_kwargs', + given=caption is not None or dynamic_caption is not None) + suptitle, suptitle_style = _validate_suptitle( + call_kwargs.get('suptitle'), call_kwargs.get('suptitle_kwargs'), + backend) + hold_frames = _validate_hold( + call_kwargs.get('hold', 0), _animate, + call_kwargs.get('frame_rate', 30), backend) + figure_texts = dict(caption_style=caption_style, suptitle=suptitle, + suptitle_style=suptitle_style) if call_kwargs.get('ax') is not None: raise ValueError( f"{_name}= creates its own figure and axes, so it cannot also " @@ -6297,7 +7044,8 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): # re-shows: this function owns the figure, the save and the display. shared = dict(call_kwargs) for key in ('title', 'show', 'save_path', 'return_model', 'panels', - 'subplots', 'ax', 'panel_fit', 'caption'): + 'subplots', 'ax', 'panel_fit', 'caption', 'caption_kwargs', + 'suptitle', 'suptitle_kwargs', 'hold'): shared.pop(key, None) shared['show'] = False # on_frame= on an animated grid is called once per DRAWN frame for the @@ -6686,6 +7434,9 @@ def _draw_grid(consolidate): #: (GH #295) cells = [] if animated else None colorbars = [] + #: each panel's case for the "this styling is ignored" warnings, + #: which are about the whole figure (`_warn_ignored_grid_styling`) + styling = [] try: with warnings.catch_warnings(record=True) as caught: warnings.simplefilter('always') @@ -6697,7 +7448,7 @@ def _draw_grid(consolidate): if animated: kw['_panel_animation'] = cells kw['_panel_shared'] = dict( - panel_shared[i], + panel_shared[i], styling=styling, **({'colorbars': colorbars} if consolidate else {})) if grid_colorbar is not None: # the grid's one colorbar is already resolved @@ -6718,6 +7469,7 @@ def _draw_grid(consolidate): # 2026-09-07, 3) result['pipeline'] = panel_pipelines[i] models.append(result) + _warn_ignored_grid_styling(styling) except Exception: plt.close(fig) raise @@ -6803,7 +7555,8 @@ def _draw_grid(consolidate): shared_pipeline=shared_pipeline, resize=call_kwargs.get('size') is None, _name=_name, strip=strip, grid_colors=grid_colors, - rotations=call_kwargs.get('rotations', 1)) + rotations=call_kwargs.get('rotations', 1), + hold_frames=hold_frames, figure_texts=figure_texts) # the layout an animated grid gets, at the one view; a dynamic caption # is resolved once, for the finished figure (as a dynamic title= is on @@ -6814,7 +7567,8 @@ def _draw_grid(consolidate): caption=caption, dynamic_caption=dynamic_caption, font=call_kwargs.get('font'), frame_context=lambda _frame: _static_grid_context( - fig, panel_axes, panel_xforms, order='parallel'), _name=_name) + fig, panel_axes, panel_xforms, order='parallel'), _name=_name, + **figure_texts) if save_path is not None: fig.savefig(save_path) @@ -6880,22 +7634,22 @@ def _grid_caption_font(font, text): def _add_grid_caption(fig, caption, dynamic_caption, font, context, - sample_contexts=()): + sample_texts=(), **placement): """Draw a panel grid's caption and return its ``Text``. A dynamic caption (pattern or callable) is resolved for `context` -- frame 0 of an animated grid (`_panel_grid_context`), or the finished static figure (`_static_grid_context`) -- and its room is sized for that text - and for `sample_contexts`' (see `_add_caption`).""" + and for `sample_texts`, the caption's texts on the other frames (see + `_add_caption`, which `placement` -- ``style``, ``gid``, ``settle`` + -- is handed to).""" text, samples = caption, [] if dynamic_caption is not None: text = _resolve_dynamic_title_text(dynamic_caption, context, name='caption') - samples = [_resolve_dynamic_title_text(dynamic_caption, sample, - name='caption') - for sample in sample_contexts] + samples = list(sample_texts) resolved_font, family = _grid_caption_font(font, text) return _add_caption(fig, text, font=resolved_font, family=family, - samples=samples) + samples=samples, **placement) def _static_grid_context(fig, panel_axes, panel_rows, order=None): @@ -7153,6 +7907,288 @@ def _outer_label_margins(fig, cubes, strip): return grow +def _zoomed_in(zoom): + """Whether `zoom=` asks for a closer view than the default (1).""" + try: + return float(zoom) > 1.0 + except (TypeError, ValueError): + return False + + +class _AnimatedCubeZoom: + """A single ANIMATED 3-D plot's zoom handle, in the shape + `_keep_cube_clear` fits (``zoom_scale`` and ``draw``): the factor its + frame functions multiply their box zoom by, and a draw of frame 0 (the + updater alone, no hook), which applies it.""" + + def __init__(self, zoom_scale, draw_first_frame): + self.zoom_scale = zoom_scale + self._draw_first_frame = draw_first_frame + + def draw(self, frame=0): + """Draw frame 0 (`frame` is ignored: the fit measures from it).""" + self._draw_first_frame() + + +def _cube_corners_px(axis, azimuths): + """The cube's eight corners on the canvas, in pixels, at each camera + angle of `azimuths` (the axes' current elevation and box zoom): + an array of shape ``(len(azimuths), 8, 2)``. + + Turning the camera round the vertical axis by an angle shows what + turning the cube the other way round the same axis (through the + middle of the box the camera looks at) shows from where the camera + is. So the projection is asked for ONCE, at the axes' own azimuth, + and the corners are turned instead, all views in one go. (Asking + matplotlib for a projection per view cost 9 ms for the 121 views of + a full turn, several times per animated 3-D plot: 1.2.1 review + round 2.) An axes whose vertical axis is not z is measured view by + view (`_cube_corners_px_by_view`).""" + import itertools + from mpl_toolkits.mplot3d import proj3d + aspect = getattr(axis, '_box_aspect', None) + if getattr(axis, '_vertical_axis', None) != 2 or aspect is None: + return _cube_corners_px_by_view(axis, azimuths) + limits = np.array([axis.get_xlim3d(), axis.get_ylim3d(), + axis.get_zlim3d()], dtype=float) + low, span = limits[:, 0], limits[:, 1] - limits[:, 0] + aspect = np.asarray(aspect, dtype=float) + corners = np.array(list(itertools.product(*limits))) + # (the square a 3-D axes is drawn in is settled by `apply_aspect`) + axis.apply_aspect() + # in the box the camera turns round: every side scaled to its aspect + box = (corners - low) / span * aspect - 0.5 * aspect + turn = -np.radians(np.asarray(list(azimuths), dtype=float) - axis.azim) + cos, sin = np.cos(turn)[:, None], np.sin(turn)[:, None] + turned = np.stack([box[None, :, 0] * cos - box[None, :, 1] * sin, + box[None, :, 0] * sin + box[None, :, 1] * cos, + np.broadcast_to(box[None, :, 2], + (len(turn), len(box)))], axis=-1) + data = (turned + 0.5 * aspect) / aspect * span + low + flat = data.reshape(-1, 3) + px, py, _ = proj3d.proj_transform( + flat[:, 0], flat[:, 1], flat[:, 2], axis.get_proj()) + return axis.transData.transform( + np.column_stack([px, py])).reshape(len(turn), len(box), 2) + + +def _cube_corners_px_by_view(axis, azimuths): + """`_cube_corners_px` the long way: the camera is put at each angle + in turn and matplotlib is asked for that view's projection.""" + import itertools + from mpl_toolkits.mplot3d import proj3d + elev, azim0 = axis.elev, axis.azim + corners = np.array(list(itertools.product( + axis.get_xlim3d(), axis.get_ylim3d(), axis.get_zlim3d()))) + # (the square a 3-D axes is drawn in is settled by `apply_aspect`) + axis.apply_aspect() + views = [] + for azim in azimuths: + axis.view_init(elev=elev, azim=azim) + px, py, _ = proj3d.proj_transform( + corners[:, 0], corners[:, 1], corners[:, 2], axis.get_proj()) + views.append(axis.transData.transform(np.column_stack([px, py]))) + axis.view_init(elev=elev, azim=azim0) + return np.array(views) + + +def _cube_excess(views, center, room, obstacles): + """By what factor the cube drawn at `views` (`_cube_corners_px`) is + too large: the smallest number its size, measured from `center`, + must be divided by for every corner to stay inside the box `room` + (x0, y0, x1, y1) and for the cube to stay off every box of + `obstacles`. 1.0 or less means it is clear already. An obstacle that + covers `center` cannot be cleared at any size and is ignored.""" + offsets = views - np.asarray(center, dtype=float) + low = np.array([center[0] - room[0], center[1] - room[1]]) + high = np.array([room[2] - center[0], room[3] - center[1]]) + with np.errstate(divide='ignore', invalid='ignore'): + excess = float(np.nanmax(np.where( + offsets >= 0, offsets / high, -offsets / low))) + for x0, y0, x1, y1 in obstacles: + box = np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]]) - center + for corners in offsets: + # two convex shapes are apart exactly when some edge normal of + # one of them separates them. The cube's outline is convex and + # its edges join pairs of corners, so the normals of all the + # corner pairs (and the box's own two) cover every candidate. + # Along a normal the cube spans [a, b] around the center + # (a < 0 < b) and the box [c, d]: shrunk by s the cube clears + # the box on that side when s * b < c (or s * a > d). The + # largest such s over all normals is the size that just fits. + pairs = corners[:, None, :] - corners[None, :, :] + pairs = pairs[np.triu_indices(len(corners), 1)] + normals = np.vstack([np.column_stack([-pairs[:, 1], pairs[:, 0]]), + [[1.0, 0.0], [0.0, 1.0]]]) + lengths = np.hypot(normals[:, 0], normals[:, 1]) + normals = normals[lengths > 1e-9] / lengths[lengths > 1e-9, None] + cube = corners @ normals.T + a, b = cube.min(axis=0), cube.max(axis=0) + rect = box @ normals.T + c, d = rect.min(axis=0), rect.max(axis=0) + with np.errstate(divide='ignore', invalid='ignore'): + fits = np.where(c > 0, c / b, np.where(d < 0, d / a, 0.0)) + fits = float(np.nanmax(fits)) + if fits > 0.0: + excess = max(excess, 1.0 / fits) + return excess + + +#: the smallest a single plot's cube is drawn to keep it off a legend (or +#: another axes of the figure), as a share of its usual size: under this +#: the cube stays at that share and the legend covers part of it. (0.7 +#: until 1.2.1 review round 5: matplotlib 3.11 gives a line of text its +#: font's full line height, so the ten-entry corner legend of the GH #297 +#: tests is a quarter taller there than under 3.10 and the cube needs +#: 0.61 of its size to clear it, on 8 of 36 frames it was drawn under +#: the legend.) +_LEGEND_CLEAR_CUBE_SHARE = 0.55 + + +def _axis_text_boxes_px(fig, axis, azimuths): + """The boxes ``(x0, y0, x1, y1)``, in pixels, of every axis label + and tick label the 3-D axes `axis` draws, at each camera angle of + `azimuths` (its current elevation and box zoom): an ``(n, 4)`` array + of all of them, all views together + (`matplotlib_backend.axis_text_boxes_px` at each view).""" + from .matplotlib_backend import axis_text_boxes_px + _measurement_renderer(fig) + elev, azim0 = axis.elev, axis.azim + boxes = [] + try: + for azim in azimuths: + axis.view_init(elev=elev, azim=azim) + boxes.extend(axis_text_boxes_px(axis)) + finally: + axis.view_init(elev=elev, azim=azim0) + return np.array(boxes, dtype=float).reshape(-1, 4) + + +def _keep_cube_clear(fig, axis, handle, rotations, frame_azimuths=None): + """Zoom a single 3-D plot's cube out until, at EVERY camera angle it + is seen from, it stays inside the canvas and off the plot's legend + and the figure's other axes (GH #297). The one fit of a single plot's + cube, static or animated; a `panels=` grid has its own + (`_fit_panel_cubes`). + + The cube's AXIS LABELS (and tick labels, where an axes draws any) + turn with the cube, hanging outside it, so they are fitted too + (1.2.1 review round 5): at every view the plot is seen from, each of + them stays on the canvas and off everything that does not move (the + legend, a colorbar, the title, the suptitle and the caption; the + boxes `_label_obstacles_pt` gives the observation labels). For an + animation the views are those of ALL its frames (`frame_azimuths`, a + callable that returns every frame's camera angle), not a sample: + which edge a label hangs from changes from one view to the next, so + the widest view cannot be found from a few. The one layout this + makes holds for the whole animation: nothing that does not turn is + moved or resized between frames. + + An animated 3-D axes fills the canvas and its cube is drawn zoomed + in, so on a square or portrait figure the cube, seen corner-on, + reached to the canvas edge and past it (the left corner of + `examples/animate_conversation.py` sat on the edge for the whole + clip); a legend placed in a corner of the axes + (``legend_kwargs={'loc': 'upper left'}``) met the cube's top corner; + and the default legend, right of the plot, was reached by the cube's + right corner at its widest view. The cube's eight corners are + projected at the views the plot is seen from (`_camera_azimuths`: the + whole turn of a rotating animation, the one view of a static plot) + and the box zoom is lowered (the `handle`'s ``zoom_scale``) until + they are all on the canvas, less the margin a panel's cube is given + (`_PANEL_CUBE_FILL`), and the cube's outline is that margin away from + the legend and from every other axes of the figure (a colorbar). A + cube that is clear already is not touched: a static plot unless its + legend was put inside the axes, and an animated landscape plot + without a legend. To clear a legend or another axes the cube is drawn + no smaller than `_LEGEND_CLEAR_CUBE_SHARE` of its size. + """ + if not hasattr(axis, 'get_proj'): + return + width, height = fig.bbox.width, fig.bbox.height + margin = 0.5 * (1.0 - _PANEL_CUBE_FILL) * min(width, height) + room = (margin, margin, width - margin, height - margin) + obstacles = [] + for other in fig.axes: + if other is axis or not other.get_visible(): + continue + box = other.get_position() + obstacles.append((box.x0 * width, box.y0 * height, + box.x1 * width, box.y1 * height)) + legend = axis.get_legend() + if legend is not None and legend.get_visible(): + import matplotlib + with plt.rc_context(matplotlib.rcParamsDefault): + extent = legend.get_window_extent(_measurement_renderer(fig)) + obstacles.append(tuple(extent.extents)) + obstacles = [(x0 - margin, y0 - margin, x1 + margin, y1 + margin) + for x0, y0, x1, y1 in obstacles] + start = handle.zoom_scale[0] + for _ in range(4): + # frame 0 sets the plot's elevation and applies its box zoom + handle.draw(0) + views = _cube_corners_px( + axis, _camera_azimuths(axis, rotations, 3.0)) + square = axis.get_position() + center = ((square.x0 + square.x1) * 0.5 * width, + (square.y0 + square.y1) * 0.5 * height) + excess = max(_cube_excess(views, center, room, []), min( + _cube_excess(views, center, room, obstacles), + handle.zoom_scale[0] / (_LEGEND_CLEAR_CUBE_SHARE * start))) + if excess <= 1.001: + break + # (the projection is perspective, so the cube's reach is not + # exactly linear in the zoom: correct and measure again) + handle.zoom_scale[0] /= excess + handle.draw(0) + if not _has_axis_text(axis): + return + from .matplotlib_backend import _label_obstacles_pt + azimuths = (_camera_azimuths(axis, rotations, 3.0) + if frame_azimuths is None else frame_azimuths()) + azimuths = sorted({round(float(azim) % 360.0, 6) for azim in azimuths}) + handle.draw(0) + pad = _OUTER_LABEL_PAD_IN * fig.dpi + room = (pad, pad, width - pad, height - pad) + for _ in range(6): + boxes = _axis_text_boxes_px(fig, axis, azimuths) + if not len(boxes): + break + # each text as a shape of its own (its box's four corners) + shapes = boxes[:, [[0, 1], [2, 1], [2, 3], [0, 3]]] + square = axis.get_position() + center = ((square.x0 + square.x1) * 0.5 * width, + (square.y0 + square.y1) * 0.5 * height) + still = _label_obstacles_pt(axis, None, (0.0, 0.0), 1.0, + axis_text=False) + still = [(x0 - pad, y0 - pad, x1 + pad, y1 + pad) + for x0, y0, x1, y1 in still] + excess = max(_cube_excess(shapes, center, room, []), min( + _cube_excess(shapes, center, room, still), + handle.zoom_scale[0] / (_LEGEND_CLEAR_CUBE_SHARE * start))) + if excess <= 1.001: + break + # (a text keeps its size while the cube it hangs from shrinks, + # so its reach is not linear in the zoom: correct, measure again) + handle.zoom_scale[0] /= excess + handle.draw(0) + handle.draw(0) + + +def _has_axis_text(axis): + """Whether the 3-D axes `axis` draws any axis label or tick + label.""" + if not getattr(axis, '_axis3don', True): + return False + for axis3d in axis._axis_map.values(): + if axis3d.label.get_visible() and axis3d.label.get_text().strip(): + return True + if any(tick.label1.get_visible() and tick.label1.get_text().strip() + for tick in axis3d.get_major_ticks()): + return True + return False + + class _StaticCubeZoom: """A STATIC 3-D panel's zoom handle, in the shape of an animated panel's `PanelAnimationStub` (``zoom_scale``, ``start_scale`` and @@ -7168,11 +8204,22 @@ def __init__(self, axis): self._axis = axis self._aspect = tuple(axis.get_box_aspect()) self.zoom_scale = [1.0] + #: the zoom the axes is drawn at now + self._applied = 1.0 def draw(self, frame=0): """Apply the current zoom (`frame` is ignored: a static panel - has one).""" - self._axis.set_box_aspect(self._aspect, zoom=self.zoom_scale[0]) + has one). A zoom that is in effect already is not applied again: + `set_box_aspect` rescales the aspect it is given, so handing an + axes its own aspect back at zoom 1 moved it by one unit in the + last place, and with it a few antialiased pixels of every static + 3-D figure whose cube needed no fitting (1.2.1 gallery review: + three gallery figures differed from 1.2.0 in 2 to 7 pixels).""" + zoom = self.zoom_scale[0] + if zoom == self._applied: + return + self._axis.set_box_aspect(self._aspect, zoom=zoom) + self._applied = zoom def _has_axis_labels(axis): @@ -7517,7 +8564,8 @@ def _illegible(): def _lay_out_panel_grid(fig, panel_axes, grid, strip, cells=None, resize=True, rotations=0, caption=None, dynamic_caption=None, font=None, frame_context=None, sample_frames=(), - _name='panels'): + _name='panels', caption_style=None, suptitle=None, + suptitle_style=None, text_frames=None): """Finish the layout of a drawn matplotlib `panels=` grid -- the ONE path of static and animated grids (1.2.0). When this is called the panels are drawn, shared axis labels are on the outer panels only @@ -7531,8 +8579,10 @@ def _lay_out_panel_grid(fig, panel_axes, grid, strip, cells=None, only as far as legible labeled cubes need (`_fit_panel_cubes`); 2. re-centers the shared legend/colorbar on the panels (`_place_shared_furniture`); - 3. adds the caption's room under the grid and draws it - (`_add_grid_caption`), then re-centers the strip again. + 3. adds the caption's room under the grid (or above it: + `caption_style`) and draws it (`_add_grid_caption`), then the + figure-level `suptitle`'s room above everything, a top caption + included (GH #299), and re-centers the strip again. An animated grid passes its `cells` (each panel's `PanelAnimationStub`) and differs in exactly two inputs, both of them @@ -7583,6 +8633,9 @@ def _lay_out_panel_grid(fig, panel_axes, grid, strip, cells=None, # showing its tallest per-frame title; see `plot`) cell['stub'].draw(0) _place_emptied_cube_labels(fig, panel_axes) + # a text added ABOVE an animated grid has its room measured over the + # sampled frames (a per-frame panel title is taller on some) + settle = (frame_context, sample_frames) if animated else None caption_artist = None if caption is not None or dynamic_caption is not None: dynamic = dynamic_caption is not None @@ -7590,15 +8643,38 @@ def _lay_out_panel_grid(fig, panel_axes, grid, strip, cells=None, # the sampled frames' it sizes the caption's room; an animated # grid's panels are drawn at each to get its real context (frames # are idempotent, see `FrameContext`) - samples = ([frame_context(frame) for frame in sample_frames] - if dynamic else ()) + # (each frame's text is resolved while the panels show that + # frame: a context holds the panels' artists, which the next + # frame changes) + samples = ([_resolve_dynamic_title_text( + dynamic_caption, frame_context(frame), name='caption') + for frame in (text_frames if text_frames is not None + else sample_frames)] if dynamic else ()) caption_artist = _add_grid_caption( fig, caption, dynamic_caption, font, context=frame_context(0) if dynamic else None, - sample_contexts=samples) + sample_texts=samples, style=caption_style, settle=settle) # the caption's room was added under the grid: re-center the # shared legend/colorbar on the panels _place_shared_furniture(fig, strip) + if suptitle is not None: + _add_grid_caption( + fig, suptitle, None, font, context=None, + style=dict(suptitle_style or {}, position='top'), + gid=SUPTITLE_GID, settle=settle) + _place_shared_furniture(fig, strip) + # the grid is laid out: observation labels are placed from their + # usual places on the first draw of the finished figure + from .matplotlib_backend import reset_label_places, track_labels + reset_label_places(fig) + if animated: + # ...and an animated grid's follow a table worked out for every + # frame of each panel (`solve_label_tracks`) + for cell in cells: + if getattr(cell['axes'], '_hyp_labels_and_points', None): + cell['stub'].draw(0) + track_labels(cell['axes'], cell['stub']._save_count, + cell['stub'].draw, cell['stub']._interval) return caption_artist @@ -7606,7 +8682,8 @@ def _animate_panel_grid(fig, cells, panel_axes, panel_models, grid, grid_hooks, caption, dynamic_caption, font, save_path, show, return_model, shared_pipeline, resize=True, _name='panels', strip=None, - grid_colors=None, rotations=1): + grid_colors=None, rotations=1, hold_frames=0, + figure_texts=None): """Turn a drawn grid of animated panels into ONE animation (GH #295). Every panel call left its frame function in `cells` (a @@ -7661,7 +8738,9 @@ def _draw_panels(num): rotations=rotations, caption=caption, dynamic_caption=dynamic_caption, font=font, frame_context=_draw_panels, - sample_frames=_caption_sample_frames(n_frames), _name=_name) + sample_frames=_caption_sample_frames(n_frames), + text_frames=_caption_text_frames(n_frames), _name=_name, + **(figure_texts or {})) except Exception: _abandon() raise @@ -7674,9 +8753,13 @@ def _grid_frame(num, *_): for callback in grid_hooks.callbacks: callback(context) + # `hold=` (GH #299): the grid's ONE animation repeats its last frame + # (`held_frame_sequence`), so every panel, the caption and the + # `on_frame=` callbacks see the last index again line_ani = HyperFuncAnimation( - fig, _grid_frame, n_frames, interval=interval, blit=False, - repeat=False) + fig, _grid_frame, held_frame_sequence(n_frames, hold_frames), + interval=interval, blit=False, repeat=False) + line_ani._hyp_content_frames = int(n_frames) # a morph grid's panels share one hold/transition schedule (they have # the same frame count); `HyperAnimation.n_segments` reads this segments = {getattr(cell['stub'], '_hyp_morph_segments', None) @@ -8049,6 +9132,13 @@ def plot( legend_kwargs=None, legend_colors=None, caption=None, + caption_kwargs=None, + suptitle=None, + suptitle_kwargs=None, + head_marker=None, + tail_linewidth=None, + trail_alpha=None, + hold=0, **kwargs, ): """ @@ -8701,7 +9791,116 @@ def plot( `ax.annotate` call-outs; plotly draws the same points as `layout.scene.annotations` (3D) or `layout.annotations` (2D), at the same data coordinates, honoring the resolved `font=` (see - below) the same way the legend/colorbar/title do. + below) the same way the legend/colorbar/title do. With + ``animate='morph'`` no label is drawn, on either backend, and a + ``UserWarning`` says so: a morph draws one cloud that moves from + each dataset's shape to the next, so it has no observation for a + label to stay on. + + On matplotlib a label hangs up and to the left of its point. A + label whose box is covered by an earlier label's is moved to + another place around its point (a corner or a side, at the usual + distance or further out): the free place nearest to where it + was. A label is also kept off the figure's legends (the one + shared legend of a `panels=` grid included), its colorbars, the + panel titles and the `suptitle=` and `caption=` texts: a label + that would lie on one of them, a single label too, takes the + nearest place that is clear of them, and a place on one of them + is the last resort: where there is no room for every label (a + very small figure with large texts) labels lie on each other + rather than on a title or the legend. A static figure is placed + when it is drawn, and the same + call always saves the same picture. The placement is worked out + in points from the figure's own size, not from the pixels of + the draw, so the screen, a PNG at any dpi, a PDF and an SVG show + the same arrangement (a figure whose size is changed is placed + again). Several labeled calls into one `ax=` are kept off each + other as one set. When a 3-D plot is rotated + by hand a label stays where it is until its box is covered, and + does not go back when its old place becomes free. + + In an animation every frame's labels are placed for that frame: + each label is attached to its point where the frame shows it + (as a 3-D plot turns, the labels turn with their points) and + placed by the same rule, off the other labels shown on that + frame and off the legend, the colorbar, the titles, the + suptitle and the caption, and inside the canvas. A 3-D plot's + own axis labels, which turn with the cube, are kept clear as + well, and so is the next panel of a `panels=` grid. The labels + of points a frame does not show (not yet revealed, outside the + sliding window) are hidden. So that labels do not hop about, + every label is given a plan for the whole animation before a + frame is drawn: it stays at one place by its point for as long + as that place is clear, at the nearest such place, further out + (up to 130 points) where the plot is crowded; when another + label is about to arrive it glides to its next place over about + a third of a second, BEFORE the other gets there, and then + stays for a second, so it never goes out and straight back; an + animation that loops is planned round the loop. With a dozen + labels no two overlap on any frame; with more than the canvas + has room for (30 on a default-size cube that turns in four + seconds) a few still do for a moment, far fewer than if each + frame were placed on its own. A frame is the same picture + whatever was drawn before it, in a saved file too. The price is + paid when the plot is made (every frame's geometry is worked + out, nothing is rendered): about half a second for 20 labels on + 60 frames, 1.5 s for 60 and 2.5 s for 200 (the more labels, the fewer + times each plan is revised: above 80 labels a label that still + lies on another is not planned a second time, and above 300 the + labels stay at their usual places). An animation with more + than 3600 labels x frames is planned at evenly spaced frames + (3600 over the number of labels, at least 40) and its labels + move evenly between them, so a long animation takes no longer + to plan than a short one. The plan is made again when the + figure is resized, a label's text or font is changed, or a + legend or text is added. A pickled or copied figure keeps its + labels where the frame it was taken at had them. Legends, titles, the suptitle, the caption and + the size of the cube are laid out once, for the widest view of + the whole animation, and do not move between frames. + + On a STREAM (an iterator, generator or Hugging Face + ``IterableDataset`` as `x`; matplotlib) the number of samples is + not known, so `labels` is not one list with an entry per + observation. It is either a callable ``labels(index, sample)``, + called once per consumed sample with the sample's position in + the stream (from 0) and the sample as the stream yielded it + (so ``labels=lambda i, row: row['title']`` reads a text field of + a dict sample), or any iterable consumed in step with the + samples, one entry per sample: a list, tuple, array or Series, + or an iterator or generator, which may be endless. When an + iterable runs out the later samples have no label, so a list of + 5 entries labels the first 5 samples. An entry or return value + of None (or NaN, or a blank string) draws no label; a bare + string or a non-iterable raises ``TypeError`` before a sample is + consumed. The per-dataset form and `label_anchor=` do not apply + to a stream. Each label is attached to its sample's drawn + position on every frame and, with `stream_window=`, is removed + when its sample leaves the window; the labels of every consumed + sample are kept in ``fig.stream_info['labels']``. The samples + to come are not known, so the labels cannot be planned ahead as + an animation's are. They are placed once per update, by the + same rule (off the other labels, the title, legends and figure + texts, inside the canvas), from where the update before left + them: a label keeps its place while that place is clear; a new + label takes a free place and the labels already shown stay + where they are; a label that has to move (the figure was + resized or turned, or room has come free for a label that had + none) glides to the nearest free place over about 0.4 seconds + of frames (at `frame_rate=`, at least 3 updates), rests there + for three glides, and does not go back to the place it left + for six glides unless no other place is free. The title, the + axes and the display box are laid out once, from the first + `stream_init` samples, and do not move. The same stream in the + same chunks saves the same frames: the placement depends on the + updates so far, never on a clock or on how often the figure is + drawn. An update's placement is cheap (about 0.5 ms with 10 + visible labels, 1 ms with 50, 3 ms with 200, far less than + drawing them); at most 300 visible labels are kept off each + other (the oldest), the others hang at the usual place, and a + ``UserWarning`` says so once. Without `stream_window=` every + label stays on the figure, so memory grows with the number of + labeled samples; with it the number of labels is bounded by + the window. label_anchor : 'first', 'center', 'last', int, or None Where a PER-DATASET `labels=` list attaches its annotation inside @@ -8774,6 +9973,15 @@ def plot( 'orientation': 'h'}`) under `backend='plotly'`. Applied LAST, so anything given here wins over hypertools' own defaults (a frameless legend centered outside the right edge). Default None. + On a single 3-D matplotlib plot the cube is kept clear of the + legend wherever it is placed: a legend in a corner of the axes + (``'upper left'``) has the cube drawn a little smaller, by up to + 30%, rather than drawn across it. On a single 2-D matplotlib + plot a named ``loc`` (``'upper left'``, ``'best'``, ...) places + the legend inside the frame that is drawn around the data, as a + ``loc`` places it inside the axes' frame in matplotlib; with a + ``bbox_to_anchor`` (or a coordinate pair as ``loc``) the + placement is yours, in axes fractions. In a `panels=` grid these style the grid's ONE shared legend, and its position is read relative to the whole GRID. On matplotlib a @@ -8808,7 +10016,13 @@ def plot( REPLACES the legend outright with exactly those entries, on both backends -- which is how a figure adds a key entry no trace corresponds to (e.g. a gray "Market" line alongside per-sector - swatches). Mixing the two forms raises ``ValueError``. Under + swatches). A pair's key is a plain swatch (a 2-point solid line, + or a marker when `fmt` draws markers only), except when there is + exactly one pair per drawn dataset, in order: each key is then + drawn in that dataset's own `fmt` and its given `linewidth`, + `linestyle`, `marker`, `markersize` and `alpha` (plotly: its + `linewidth`), so a heavier line has a heavier key. Mixing the + two forms raises ``ValueError``. Under `panels=`, a plain list naming the datasets (one color per dataset, then one per shared entry such as a forecast model or ``truth``) recolors those entries of the grid's one shared @@ -8912,7 +10126,11 @@ def plot( ``variant``, ``stretch``, and the already-real names ``color``, ``alpha``, ``y``, ``pad``, ``loc``, ``rotation``, ``linespacing``, ``backgroundcolor``. An unknown key raises ``ValueError`` naming - the supported set. A ``size`` given here also sizes the room + the supported set. matplotlib decides what each key accepts + (``None`` where it takes ``None``, a size as a number, a numeric + string or a size name); a value it refuses, and a size or line + spacing that is not positive and finite, raises ``ValueError`` + naming ``title_kwargs`` and the key. A ``size`` given here also sizes the room reserved above an animated 3-D title (matplotlib's top-margin probe; plotly's ``layout.margin.t``), so a larger title still fits on the canvas. @@ -8943,10 +10161,8 @@ def plot( A dynamic (callable / ``{index``) title is wrapped afresh every frame. An animated 3-D title reserves top margin per line on both backends: for a per-segment list, the tallest entry; for a - dynamic title, plotly measures every frame (all frames are built - up front) while matplotlib measures the first, middle and last - frames' texts (see `title=`), so only a frame in between that - needs more lines than all three can clip there. Default None. + dynamic title, both backends measure every frame's text (see + `title=`). Default None. font : None, str, or matplotlib.font_manager.FontProperties Controls the font used for every text surface hypertools draws, @@ -9269,7 +10485,11 @@ def plot( observations, so its labels cannot group the plotted rows -- use `hyp.cluster(data, cluster='FeatureAgglomeration')` directly. Cluster labels are drawn as one trace per cluster (palette - colors, legend entries in sorted label order). + colors, legend entries in sorted label order). A model that + starts from a random state (KMeans, MiniBatchKMeans, + SpectralClustering, the mixture models) can group the same data + differently on each call; pass `random_state=` for the same + clusters, and so the same picture, every time. n_clusters : int If n_clusters is passed, HyperTools will perform clustering with @@ -9611,7 +10831,8 @@ def plot( e.g. `'spin'`) and every OTHER key maps onto one of the flat animation kwargs below (`duration`, `tail_duration`, `rotations`, `zoom`, `chemtrails`, `precog`, `bullettime`, `frame_rate`, - `focused`, `morph_samples`) -- e.g. ``animate={'style': 'spin', 'rotations': + `focused`, `morph_samples`, `head_marker`, `tail_linewidth`, + `trail_alpha`, `hold`) -- e.g. ``animate={'style': 'spin', 'rotations': 2, 'duration': 15}`` is exactly equivalent to ``animate='spin', rotations=2, duration=15``. The dict is unpacked into the flat kwargs at the very top of `plot()`, before anything @@ -9721,15 +10942,26 @@ def plot( chemtrails (animation only) : bool or list of bool A low-opacity trail is left behind the trajectory (default: False). - Pass a list of bool (one entry per drawn dataset -- i.e. the FINAL - count after any `cluster`/`hue`/`n_clusters` regrouping) for - per-dataset control (GH #127): e.g. `chemtrails=[True, False]` turns + Pass a list of bool, one entry per dataset, for per-dataset + control (GH #127): e.g. `chemtrails=[True, False]` turns chemtrails on for dataset 0 only. A bare bool is broadcast to every - dataset. Raises `ValueError` if a list's length does not match the - number of drawn datasets (naming both counts). Trail styles + dataset. When a categorical `hue=` or `cluster=` splits the + datasets of a line format into several drawn traces, each trace + takes the flag of the dataset it comes from (a list with one + entry per drawn trace, the FINAL count after the regrouping, is + accepted too). A markers-only format colored by category draws + one trace per category, not per dataset, so there a list needs + one entry per category. Raises `ValueError` if a list's length + matches neither count (naming both counts). Trail styles (`chemtrails`/`precog`/`bullettime`) apply to `animate=True`/ `'parallel'` and to `animate='serial'`, on BOTH backends (see the note under `bullettime` below). + A trail is drawn in its dataset's own format and color, at 0.3 + times the dataset's alpha (`trail_alpha=` changes the 0.3): a + line's trail is the faded line, a line+marker format's (``'-o'``, + ``'o-'``, ``'.-'``, ``'--s'``) the faded line with faded markers + on the observations, as its tail is drawn, and a markers-only + format's its faded markers. precog (animation only) : bool or list of bool A low-opacity trail is plotted ahead of the trajectory (default: @@ -9760,6 +10992,99 @@ def plot( `UserWarning` naming the mode, the ignored flag(s), and which dataset indices had them set. + trail_alpha (animation only) : float or None + The opacity of the `chemtrails`/`precog`/`bullettime` trails, as + a fraction (0 to 1) of each dataset's own `alpha=`. Default None: + 0.3, what hypertools has always drawn (``trail_alpha=0.6`` draws + the trails twice as strong; with ``alpha=0.5`` a trail is then at + 0.3). One number for every trail. Works on both backends. Warns + (``UserWarning``) when the animation draws no trail. + + tail_linewidth (animation only, matplotlib only) : float or None + The line width, in points, of the TAIL -- the recent window that + `tail_duration=` (or `focused=`) sizes, drawn at full opacity -- + while a `chemtrails`/`precog`/`bullettime` trail keeps the + dataset's `linewidth=`; e.g. ``linewidth=1, tail_linewidth=3, + chemtrails=True`` draws a thick tail ahead of a thin faded trail. + On a serial reveal it applies to the dataset being revealed (its + comet head, when it has a trail); a finished dataset is drawn in + full at `linewidth=`. One number for every dataset. Default None + (the tail is drawn at `linewidth=`). Ignored, with a + ``UserWarning``, on a static plot (either backend), for + ``animate='spin'``/``'morph'`` (every line keeps `linewidth=`) + and when no dataset is drawn with a line (a markers-only format + such as ``'o'``). An ANIMATED plot under ``backend='plotly'`` + raises ``NotImplementedError``. + + head_marker (animation only, matplotlib only) : str, bool, dict, or None + A marker drawn at the reveal HEAD only: the last revealed point + of each dataset, on every frame (`animate=True`/``'parallel'``, + ``'window'`` and ``'serial'``; on a serial reveal a dataset that + has not started has none, and a finished one keeps its marker on + its last point; on the first frame of a serial reveal, before + any point is revealed, the first dataset's marker is on its + first point). Each dataset has ONE marker: when a categorical `hue=` + or `cluster=` colors a dataset in several pieces, the marker is + on the dataset's current point, in the color of the category + that point is in. Pass a matplotlib marker (``head_marker='o'``), + ``True`` for ``'o'``, or a dict to style it: ``{'marker': 'D', + 'size': 10, 'color': 'k', 'edgecolor': 'w', 'edgewidth': 1, + 'alpha': 1.0}`` (``marker`` defaults to ``'o'``; ``size``, + ``edgecolor``, ``edgewidth`` and ``facecolor`` are short for + ``markersize``, ``markeredgecolor``, ``markeredgewidth`` and + ``markerfacecolor``; ``fillstyle``, ``facecoloralt`` + (``markerfacecoloralt``) and ``zorder`` are accepted too, and so + are matplotlib's own short names ``ms``, ``mec``, ``mew``, + ``mfc``, ``mfcalt`` and ``c``). ``color`` is the color of the + whole marker; ``facecolor`` fills it with another color + (``'none'`` for a hollow marker) and ``edgecolor`` outlines it + in another. One option under two names (``size`` and ``ms``) + raises ``ValueError``. What the dict leaves out follows + the dataset: its color (with a continuous `hue=`, the color of + the point the head is on), its `alpha=`, and its `markersize=` + (matplotlib's default without one), never less than 2.5 times + the tail's line width so that it shows on a thick tail. It is + drawn in addition to the format's own markers and is never a + legend entry. Default None (no head marker). The marker may be + any marker matplotlib draws: a name, an array of vertices, a + tuple such as ``(5, 1)``, a ``Path`` or a ``'$...$'`` string. + Inside the dict ``'marker': True`` is ``'o'`` and ``'marker': + False`` is no head marker, as for the argument itself, and a key + set to ``None`` is left to follow the dataset. matplotlib + decides what each key accepts; a value it refuses (an unknown + color, an alpha outside 0 to 1), and a size that is not a + positive, finite number, raises ``ValueError`` naming + ``head_marker`` and the key. The head marker is hidden when its + dataset's line is hidden (see `on_frame=`). Ignored, with a ``UserWarning``, on + a static plot (either backend) and for ``animate='spin'``/ + ``'morph'`` (no reveal head). An ANIMATED plot under + ``backend='plotly'`` raises ``NotImplementedError``. + + hold (animation only, matplotlib only) : float + Hold the LAST frame for this many seconds at the end of the + animation (default 0): ``round(hold * frame_rate)`` frames are + appended, each drawing the last frame again, so the pause is in + a saved ``.mp4``/``.gif`` and in every pass of a looping player. + A hold shorter than half a frame (``hold=0.01`` at 10 frames a + second) therefore adds no frame, and a ``UserWarning`` says so + and names the shortest hold that adds one (``1 / frame_rate``). + A saved ``.mp4`` holds every one of those frames. A ``.gif`` + plays for the same time with fewer stored frames: the GIF writer + (Pillow) stores a run of identical frames as one frame with the + run's total duration, so ``duration=1, frame_rate=10, hold=1`` + with a still camera is 10 stored frames, the last shown for 1.1 + seconds. + The animation is then ``duration + hold`` seconds long + (``HyperAnimation.n_frames`` counts the held frames). During the + hold everything stays on its last value: the camera stops where + `rotations=` left it, and per-frame titles, `caption=` and + `on_frame=` callbacks see the last frame's context again + (``ctx.frame`` stays ``ctx.n_frames - 1`` and ``ctx.progress`` + 1.0). Works with every `animate=` style, with ``loop=True`` (the + closing return to the first cloud is held) and on an animated + `panels=` grid. Raises ``ValueError`` on a static plot and + ``NotImplementedError`` under ``backend='plotly'``. + forecast_trail (animation only) : bool or int Keep earlier forecasts on screen as a fading fan -- the forecast analog of `chemtrails` (default: False). Requires `predict=`; @@ -10121,7 +11446,13 @@ def plot( (``ctx.axes`` is ``None`` on plotly, whose ``ctx.artists`` are that frame's traces), so a callback that touches them is **not** portable across backends; every other field is identical across - backends. + backends. On matplotlib ``ctx.artists`` holds one artist per + dataset's reveal head, then the trails. Two things are drawn by + a second artist that is not in the list and follows the listed + one: with a continuous `hue=` on a line-and-marker format + (``'-o'``) the markers, which are hidden when the listed line + is hidden and take its ``alpha``; and a `head_marker=`, which is + hidden when its dataset's head artist is hidden. With an animated `panels=` grid the callback is called once per frame for the whole figure, with ``ctx.axes`` a tuple of the panel @@ -10187,12 +11518,12 @@ def plot( start; a frame in between that needs more lines than all three runs below that room. An empty caption (``''``) draws nothing and adds no room. It is drawn in the plot's font (`font=`), at the - default text size; it is a matplotlib ``Text`` with - ``gid='hypertools-caption'``, should you want to restyle it:: + default text size, unless `caption_kwargs=` styles it; it is a + matplotlib ``Text`` with ``gid='hypertools-caption'``, should you + want to find it on the figure:: caption = anim.figure.findobj( lambda a: a.get_gid() == 'hypertools-caption')[0] - caption.set_color('gray') Raises ``NotImplementedError`` under ``backend='plotly'`` (use a per-frame `title=` there, which both backends support) and @@ -10204,6 +11535,62 @@ def plot( >>> anim.draw_frame(4).figure.texts[-1].get_text() 'frame 5' + caption_kwargs (matplotlib only) : dict or None + Styling and placement for `caption=`: ``size`` (``fontsize``), + ``color``, ``weight`` (``fontweight``), ``style`` + (``fontstyle``), ``family`` (``fontfamily``), ``alpha``, + ``linespacing``, ``position`` -- ``'bottom'`` (default, under + the figure) or ``'top'`` (above everything the figure holds, + axes titles included) -- and ``loc`` -- ``'center'`` (default), + ``'left'`` or ``'right'``, aligned with the figure's edge. E.g. + ``caption_kwargs={'size': 14, 'color': 'gray', 'position': + 'top', 'loc': 'left'}``. The style is applied BEFORE the caption + is wrapped and its room measured, and a per-frame caption is + measured on every frame, so a caption of any size has + the room it needs and is never clipped. matplotlib decides what + each key accepts (a size may be a number, a numeric string or + one of matplotlib's size names; a key set to ``None`` keeps its + default). An unknown key, a value matplotlib refuses (an unknown + weight or color, an alpha outside 0 to 1), a size or line + spacing that is not positive and finite (the error names + ``caption_kwargs`` and the key), + or `caption_kwargs=` without a `caption=`, raises + ``ValueError``. Default None. + + suptitle (matplotlib only) : str or None + One title for the whole FIGURE, centered above everything it + holds. This is the figure-level title of a `panels=` grid, where + `title=` names the panels (a single string names every panel), + static or animated; it works on a single plot too, above its + `title=`. Its room is measured as a caption's is: the figure is + made taller by the title's height, nothing already drawn moves + or shrinks, and it clears every panel title, the shared legend + and colorbar, and a caption placed at the top (the suptitle goes + above it). A title wider than the figure is wrapped. It is fixed + text; for a figure-level text that changes on every frame use + ``caption=`` with ``caption_kwargs={'position': 'top'}`` (the + suptitle stays clear of the tallest text such a caption shows on + any frame). A ``bytes`` value is decoded + as UTF-8, as for `caption=`. `suptitle_kwargs=` takes the keys + of `caption_kwargs=` except ``position`` and checks their values + the same way. A + matplotlib ``Text`` with ``gid='hypertools-suptitle'``. Raises + ``NotImplementedError`` under ``backend='plotly'`` and + ``ValueError`` with a caller-supplied `ax=`. Default None. + + >>> fig = hyp.plot([data, data * 2], panels=(1, 2), show=False, + ... title=['one', 'two'], suptitle='Both walks') + >>> fig.texts[-1].get_text() + 'Both walks' + + suptitle_kwargs (matplotlib only) : dict or None + Styling for `suptitle=`: the keys of `caption_kwargs=` except + ``position`` (``size``, ``color``, ``weight``, ``style``, + ``family``, ``alpha``, ``linespacing``, ``loc``). The defaults + are matplotlib's own figure-title size and weight + (``rcParams['figure.titlesize']``/``['figure.titleweight']``). + Default None. + simplify : bool Whether hypertools may silently downsample to keep a render tractable. Today this governs ``animate='morph'`` **only**: a morph @@ -10639,7 +12026,7 @@ def plot( every frame. A per-frame `title=` (callable or ``{index}`` pattern, one for all panels or a list with one per panel) is given its room above each panel like a fixed title, sized for - the tallest of the first, middle and last frames' titles (see + the tallest title of any frame (see `title=`). `on_frame=` is called once for the whole figure each time a frame is drawn, not once per panel (see `on_frame=`: a save draws frame 0 twice): its ``FrameContext`` has ``axes`` as a tuple of the panel @@ -10720,7 +12107,21 @@ def plot( ``ValueError`` -- not yet supported for streams -- but accepted at their defaults), `save_path`, `show`, `frame_rate`, `markersize`, `linewidth`, `color`, `palette`, `title`, `size`, `elev`, `azim`, - and `ax`. Any other parameter explicitly set alongside a + `ax`, `legend` (with `legend_kwargs` and `legend_colors`), + `caption` (with `caption_kwargs`) and `suptitle` (with + `suptitle_kwargs`), which are placed once, when the first + `stream_init` samples are drawn, and stay where they are for the + whole stream (the display box is frozen from those samples, + so the room made for a legend then holds for every later + frame; a stream's `caption=` must be one fixed string: a + callable raises ``TypeError`` before a sample is consumed, + since a stream has no known number of frames; with `ax=`, + `caption=` and `suptitle=` raise ``ValueError`` as on any plot + drawn into a caller's axes, and `legend=` is drawn in that + axes), and `labels` with `label_alpha` (see `labels` for the + forms a stream's labels take: a callable ``labels(index, + sample)`` or an iterable consumed in step with the samples). + Any other parameter explicitly set alongside a streaming input is ignored, with a ``UserWarning`` naming it. In particular, streaming plots are always drawn with the matplotlib backend: a `backend=` request (e.g. ``backend='plotly'``) is @@ -11253,6 +12654,10 @@ def plot( _grid_blend_groups = (_panel_shared or {}).get('blend_groups') _grid_furniture = (_panel_shared is not None and 'colorbars' in _panel_shared) + # a `panels=` grid's legend key styling (`_panel_legend_entry_styles`): + # one dict per `legend_colors=` pair, paired with the GRID's datasets. + # Internal, never a user kwarg. + _grid_entry_styles = kwargs.pop('_legend_entry_styles', None) # early kwarg validation (release-1.0 audit): catch renamed/misspelled/ # unknown keyword arguments HERE, with a clear TypeError naming the @@ -11287,7 +12692,8 @@ def plot( '_grid_furniture', '_grid_hue_kind', '_grid_legend_names', '_grid_quiet', '_grid_report', '_grid_resolve_only', - '_grid_hue_rgb', '_grid_blend_groups')} + '_grid_hue_rgb', '_grid_blend_groups', + '_grid_entry_styles')} _panel_call.update(kwargs) return _plot_panels(x, _panels_spec, _panel_call, _name=_panels_name) @@ -11509,7 +12915,9 @@ def plot( 'rotations': rotations, 'zoom': zoom, 'chemtrails': chemtrails, 'precog': precog, 'bullettime': bullettime, 'frame_rate': frame_rate, 'focused': focused, - 'morph_samples': morph_samples}) + 'morph_samples': morph_samples, 'head_marker': head_marker, + 'tail_linewidth': tail_linewidth, 'trail_alpha': trail_alpha, + 'hold': hold}) duration = _animate_flat['duration'] tail_duration = _animate_flat['tail_duration'] rotations = _animate_flat['rotations'] @@ -11520,6 +12928,10 @@ def plot( frame_rate = _animate_flat['frame_rate'] focused = _animate_flat['focused'] morph_samples = _animate_flat['morph_samples'] + head_marker = _animate_flat['head_marker'] + tail_linewidth = _animate_flat['tail_linewidth'] + trail_alpha = _animate_flat['trail_alpha'] + hold = _animate_flat['hold'] # fail-fast on hue_mode= for the same reason title= fails fast here: a # typo or a contradictory pair should not survive the reduce pipeline. @@ -11662,6 +13074,22 @@ def plot( # forms `title=` takes (fixed text, a `{index...}` pattern, a callable). caption, _dynamic_caption = _validate_caption( caption, _row_indices, resolve_backend(backend), ax=ax) + # GH #299: caption styling, the figure-level `suptitle=`, and the + # animation arguments `head_marker=`/`tail_linewidth=`/`trail_alpha=`/ + # `hold=`. Private names: the streaming-kwarg check below compares the + # parameters themselves against their signature defaults. + _caption_style = _validate_figure_text_kwargs( + caption_kwargs, 'caption_kwargs', + given=caption is not None or _dynamic_caption is not None) + _suptitle, _suptitle_style = _validate_suptitle( + suptitle, suptitle_kwargs, resolve_backend(backend), ax=ax) + _frame_backend = resolve_backend(backend) if animate else None + _head_marker = _validate_head_marker(head_marker, _frame_backend) + _tail_linewidth = _validate_tail_linewidth(tail_linewidth, + _frame_backend) + _trail_alpha = _validate_trail_alpha(trail_alpha) + _hold_frames = _validate_hold(hold, animate, frame_rate, + _frame_backend) # fail-fast on on_frame= (plan 1.1 Task 7, same precedent as title=/ # order= above): needs only its own callability and the raw animate= @@ -11885,7 +13313,7 @@ def plot( # review 2026-09-11: an axis label alone in a script outside the stack # rendered as tofu). _font_texts = [labels, legend, title, hue, xlabel, ylabel, zlabel, - caption] + caption, _suptitle] if colorbar is not None: _font_texts.append(colorbar.get('label')) _font_texts.append(colorbar.get('ticks')) @@ -12035,7 +13463,9 @@ def plot( 'stream_window', 'ndims', 'reduce', 'normalize', 'align', 'cluster', 'n_clusters', 'save_path', 'show', 'frame_rate', 'markersize', 'linewidth', 'color', 'palette', 'title', - 'size', 'elev', 'azim', 'ax'} + 'size', 'elev', 'azim', 'ax', 'labels', 'label_alpha', + 'legend', 'legend_kwargs', 'legend_colors', 'caption', + 'caption_kwargs', 'suptitle', 'suptitle_kwargs'} _local_vals = locals() _stream_dropped = [] for _pname, _param in inspect.signature(plot).parameters.items(): @@ -12059,8 +13489,47 @@ def plot( "honored for streams: fmt, stream_init, stream_chunk, " "stream_max, stream_window, ndims, reduce, normalize, " "save_path, show, frame_rate, markersize, linewidth, " - "color, palette, title, size, elev, azim, ax (see the " - "stream_init docstring).", UserWarning, stacklevel=external_stacklevel()) + "color, palette, title, size, elev, azim, ax, labels, " + "label_alpha, legend, legend_kwargs, legend_colors, " + "caption, caption_kwargs, suptitle, suptitle_kwargs (see " + "the stream_init docstring).", + UserWarning, stacklevel=external_stacklevel()) + # the fixed texts of a stream are placed ONCE, with the plot of + # the first stream_init samples. A caption that changes per frame + # (a callable, or a '{index}'/'{frame}' pattern: `_validate_caption` + # above has set it aside as `_dynamic_caption`) has no frame + # count to be laid out for. + if _dynamic_caption is not None: + raise TypeError( + "caption= on a streaming plot must be one fixed string: it " + "is placed once, when the first stream_init samples are " + "drawn, and stays for the whole stream. A per-frame caption " + "(a callable, or a '{...}' format pattern) is not supported " + "for streams, whose number of frames is not known in " + "advance.") + # a stream is ONE dataset, so the entry counts can be checked + # here, before a sample is taken from the stream (the plot of + # the first stream_init samples would raise the same errors, but + # only after consuming them). + if isinstance(legend, (list, tuple)) and len(legend) != 1: + raise ValueError( + f"legend= was given as a list of length {len(legend)}, but " + "there are 1 dataset(s)/group(s) to plot; pass one entry " + "per drawn dataset, or legend=True to auto-number them.") + _stream_recolor, _ = _normalize_legend_colors(legend_colors) + if (_stream_recolor is not None and len(_stream_recolor) != 1 + and legend is not None and legend is not False): + raise ValueError( + f"legend_colors has {len(_stream_recolor)} entries but the " + "legend has 1; pass one color per legend entry, or pass " + "(label, color) pairs to define the entries outright.") + _stream_extras = { + _name: _value for _name, _value in ( + ('legend', legend), ('legend_kwargs', legend_kwargs), + ('legend_colors', legend_colors), ('caption', caption), + ('caption_kwargs', caption_kwargs), ('suptitle', suptitle), + ('suptitle_kwargs', suptitle_kwargs)) + if _value is not None} return plot_stream( x, fmt, stream_init=stream_init, stream_chunk=stream_chunk, stream_max=stream_max, stream_window=stream_window, @@ -12069,7 +13538,8 @@ def plot( n_clusters=n_clusters, save_path=save_path, show=show, frame_rate=frame_rate, markersize=markersize, linewidth=linewidth, color=color, palette=palette, title=title, - size=size, elev=elev, azim=azim, ax=ax) + size=size, elev=elev, azim=azim, ax=ax, labels=labels, + label_alpha=resolved_label_alpha, **_stream_extras) # remember whether the USER supplied an axis before `_draw` reassigns the # local `ax` to the axis it created (used by the GH #148 close below). @@ -14433,8 +15903,15 @@ def _compute_forecasts(datasets): # dataset count -- reshaping above can change how many traces are # actually drawn, so this must run after it, not against the original # `x`. - surface_list = (broadcast_surface(_surface_norm, len(xform)) - if _surface_norm is not None else None) + # (a per-dataset list is matched to the caller's datasets, as the + # trail flags are: `_trail_flag_per_run`) + surface_list = (broadcast_surface( + _trail_flag_per_run( + _surface_norm, "surface", seg_dataset=_seg_ds, + n_runs=len(xform), + n_datasets=(_hue_regrouped_counts or (None,))[0], + by_category=_global_regrouped), len(xform)) + if _surface_norm is not None else None) # density= (GH #108/#191): broadcast to the FINAL (post cluster/hue- # reshape) dataset count, same as surface= above. @@ -14595,9 +16072,25 @@ def _compute_forecasts(datasets): # dataset) or a list/tuple of bool (one entry per drawn dataset, mixed # per-dataset combinations allowed). `animate` itself stays a single # GLOBAL mode -- only these trail FLAGS become per-dataset. - chemtrails = broadcast_trail_flag(chemtrails, len(xform), "chemtrails") - precog = broadcast_trail_flag(precog, len(xform), "precog") - bullettime = broadcast_trail_flag(bullettime, len(xform), "bullettime") + # A categorical `hue=`/`cluster=` has by now split the caller's + # datasets into the runs that are drawn; a per-dataset list is the + # caller's, so it is matched to THEIR datasets and each run takes its + # dataset's flag (1.2.1 review round 2: `chemtrails=[False, True, + # True]` for three datasets was refused with "3 entries but there + # are 5 datasets"). + _flag_runs = dict( + seg_dataset=_seg_ds, n_runs=len(xform), + n_datasets=(_hue_regrouped_counts or (None,))[0], + by_category=_global_regrouped) + chemtrails = broadcast_trail_flag( + _trail_flag_per_run(chemtrails, "chemtrails", **_flag_runs), + len(xform), "chemtrails") + precog = broadcast_trail_flag( + _trail_flag_per_run(precog, "precog", **_flag_runs), + len(xform), "precog") + bullettime = broadcast_trail_flag( + _trail_flag_per_run(bullettime, "bullettime", **_flag_runs), + len(xform), "bullettime") # trail flags on a STATIC plot (release-1.0 audit, F05-007): the same # user mistake the spin/serial/morph/window branch below already warns @@ -14619,6 +16112,22 @@ def _compute_forecasts(datasets): stacklevel=external_stacklevel(), ) + # GH #299: the same for head_marker=/tail_linewidth=/trail_alpha= + # (a panel of a `panels=` grid reports to its grid instead: whether + # an argument is ignored is a question about the whole figure, e.g. + # `['-', 'o']` has a line to widen though the second panel has none, + # and the grid warns once; 1.2.1 review round 2) + _styling_case = dict( + animate=animate, head_marker=_head_marker, + tail_linewidth=_tail_linewidth, trail_alpha=_trail_alpha, + any_trail=any(chemtrails) or any(precog) or any(bullettime), + any_line=any(has_line_component(_one) for _one in ( + fmt if isinstance(fmt, (list, tuple, np.ndarray)) else [fmt]))) + if (_panel_shared or {}).get('styling') is not None: + _panel_shared['styling'].append(_styling_case) + else: + _warn_ignored_animation_styling(**_styling_case) + # GH #127 (+ morph/window follow-up): 'spin' has no "current position" # (only the camera moves, so a trail has nothing to trail BEHIND or AHEAD # of), 'morph' draws a single traveling point-cloud artist with no @@ -14661,6 +16170,24 @@ def _compute_forecasts(datasets): stacklevel=external_stacklevel(), ) + # labels= with animate='morph' (1.2.1 review round 2): a morph draws + # ONE cloud that travels from each dataset's shape to the next, and + # its points are not the labeled observations, so there is nothing + # for a label to stay on. matplotlib hid every label without a word + # and plotly drew them (in 2-D only) at the first positions while the + # cloud moved away. Neither backend shows them now, and the call + # says so (matplotlib keeps the hidden label artists it has always + # made, for a caller that reaches for them; plotly makes none). + if animate == 'morph' and _any_label_given(labels): + warnings.warn( + "animate='morph' draws one cloud that moves from each " + "dataset's shape to the next, so it has no observation for a " + "label to stay on; ignoring labels=. Use another animate= " + "style (e.g. True, 'spin' or 'window') to show labels.", + UserWarning, stacklevel=external_stacklevel()) + if resolve_backend(backend) == 'plotly': + labels = None + # names= (QC 2026-07): per-DATASET names, distinct from per-point `labels=` # (text call-outs on individual observations) and the `legend=True` # auto-numbering. Each name labels its dataset's trace and turns the legend @@ -15704,6 +17231,16 @@ def _surface_inherits_color(i): # fmt=None + hue on a list input crashed with a bare IndexError) draw_fmt = ["-"] * len(xform) + # `legend_colors=[(label, color), ...]` with one pair per drawn dataset: + # each key takes its dataset's own line styling (a panel's comes from + # the grid, which sees every dataset). Read HERE, before the animated + # drawing pops `linewidth` out of `kwargs_list`. + _legend_key_styles = _grid_entry_styles + if _legend_key_styles is None and _legend_entries is not None \ + and _panel_shared is None: + _legend_key_styles = legend_entry_styles( + _legend_entries, draw_fmt, kwargs_list) + # convert all nans to zeros for i, xi in enumerate(xform): xform[i] = np.nan_to_num(xi) @@ -16022,6 +17559,8 @@ def _plotly_before_show(drawn): chemtrails=chemtrails, precog=precog, bullettime=bullettime, + trail_alpha=(DEFAULT_TRAIL_ALPHA if _trail_alpha is None + else _trail_alpha), zoom=zoom, forecasts=raw_forecasts, # which drawn run each forecast continues after hue=/cluster= @@ -16060,6 +17599,7 @@ def _plotly_before_show(drawn): title_segment_colors=_title_segment_colors, legend_kwargs=_legend_kwargs, legend_entries=_final_legend_entries, + legend_entry_styles=_legend_key_styles, legend_explicit=_legend_entries is not None, # the pre-resampling observations, so an 'o-' marks only them # (the matplotlib `_draw` call's `raw_data=`) @@ -16217,6 +17757,12 @@ def _plotly_before_show(drawn): chemtrails=chemtrails, precog=precog, bullettime=bullettime, + head_marker=(None if _head_marker is None + else [_head_marker] * len(xform)), + tail_linewidth=_tail_linewidth, + trail_alpha=(DEFAULT_TRAIL_ALPHA if _trail_alpha is None + else _trail_alpha), + hold_frames=_hold_frames, frame_rate=frame_rate, elev=elev, azim=azim, @@ -16244,6 +17790,7 @@ def _plotly_before_show(drawn): title_kwargs=_title_kwargs, legend_kwargs=_legend_kwargs, legend_entries=_final_legend_entries, + legend_entry_styles=_legend_key_styles, legend_order=_legend_order, # a plain color list recolors the FINAL legend, so it is # applied after the forecast/truth entries below when @@ -16374,7 +17921,8 @@ def _plotly_before_show(drawn): ax, _forecast_artists, _truth_artists, **legend_call_kwargs( is_3d=hasattr(ax, 'get_proj'), zlabel=zlabel, - font=_artist_font, legend_kwargs=_legend_kwargs)) + font=_artist_font, legend_kwargs=_legend_kwargs, + ax=ax)) if (_legend_recolor is not None and legend is not None and _final_legend_entries is None and (raw_forecasts is not None or raw_truths is not None) @@ -16533,7 +18081,8 @@ def _plotly_before_show(drawn): ax, _live_forecast_artists, None, **legend_call_kwargs( is_3d=hasattr(ax, 'get_proj'), zlabel=zlabel, - font=_artist_font, legend_kwargs=_legend_kwargs)) + font=_artist_font, legend_kwargs=_legend_kwargs, + ax=ax)) if (_legend_recolor is not None and legend is not None and _final_legend_entries is None and ax.get_legend() is not None @@ -16688,23 +18237,39 @@ def _fill(art, pts): "morph with its default colors.", UserWarning, stacklevel=external_stacklevel()) - elif (line_ani is not None and animate != 'spin' - and has_line_component(fmt)): + elif line_ani is not None and animate != 'spin': # animated reveal styles (parallel/window/serial): # per-frame multicolor rendering (F04-001/F05-002 -- # the static swap froze the animation; 'spin' keeps # the static swap below, which is exactly right for a - # camera-only animation). Marker+line combos animate - # as a single line artist (see _draw's raw_data note), - # so they take this path too. + # camera-only animation). A line format gets a + # per-segment-colored collection, a line-and-marker + # format that plus its markers on the observations, + # and a markers-only format (GH #297) one + # per-point-colored scatter per head window and + # trail -- each DATASET by its own format, so a call + # that mixes them (``['-', 'o']``) draws each as + # asked. The static scatter below REMOVED the animated + # artists and drew every observation on every frame: + # no reveal, no trail, and in 2-D every frame the + # same picture. + _fmts = (list(fmt) if isinstance( + fmt, (list, tuple, np.ndarray)) + else [fmt] * len(xform)) _apply_multicolor_animation( ax, xform, line_colors, kwargs_list, line_ani, style=animate, chemtrails=chemtrails, precog=precog, bullettime=bullettime, + trail_alpha=(DEFAULT_TRAIL_ALPHA + if _trail_alpha is None + else _trail_alpha), antialias=antialias, total_frames=max(1, int(round(frame_rate * duration))), - frame_hooks=_frame_hooks) + frame_hooks=_frame_hooks, + markers=[not has_line_component( + _fmts[_i] if _i < len(_fmts) else None) + for _i in range(len(xform))]) elif is_line(fmt): _apply_multicolor_lines(ax, xform, line_colors, kwargs_list, @@ -16732,6 +18297,38 @@ def _fill(art, pts): warn_non_finite=False, limits=_hue_limits) _apply_multicolor_markers(ax, raw_xform, _marker_colors, kwargs_list, fmt=fmt) + elif (isinstance(fmt, (list, tuple, np.ndarray)) + and any(has_line_component(_one) for _one in fmt)): + # a call that MIXES formats (``['-', 'o']``): each + # dataset is drawn by its own, a line as the + # multicolored line, markers as the per-point-colored + # scatter, a line-and-marker format as both. Every + # dataset used to be drawn as markers as soon as one + # of them had no line. + _fmts = list(fmt) + + def _fmt_of(_i): + return _fmts[_i] if _i < len(_fmts) else None + + _with_line = {_i for _i in range(len(xform)) + if has_line_component(_fmt_of(_i))} + _with_marker = { + _i for _i in range(len(xform)) + if _i not in _with_line or ( + isinstance(_fmt_of(_i), str) + and split_marker_line_fmt(_fmt_of(_i))[1])} + _apply_multicolor_lines(ax, xform, line_colors, + kwargs_list, + row_counts=[len(r) for r in + raw_xform], + only=_with_line) + _marker_colors = _multicolor_line_colors( + multicolor_hue, pre_interp_lengths, raw_xform, + palette, is_rgb=multicolor_hue_is_rgb, + warn_non_finite=False, limits=_hue_limits) + _apply_multicolor_markers(ax, raw_xform, _marker_colors, + kwargs_list, fmt=fmt, + only=_with_marker) else: _apply_multicolor_markers(ax, xform, line_colors, kwargs_list, fmt=fmt) @@ -16779,11 +18376,16 @@ def _real_frame_context(frame): return FrameContext(figure=fig, axes=ax, **_frame_hooks.state) + _dynamic_title_texts = [] + def _sampled_dynamic_titles(): - """The dynamic `title=`'s wrapped text on the frames that - size its room -- the first, the middle and the last - (`_caption_sample_frames`, as a per-frame caption's room is - sized) -- frame 0's first. Each is resolved against that + """The different texts the dynamic `title=` shows over + the animation, wrapped, frame 0's first: what sizes its + room. EVERY frame is asked (`_caption_text_frames`, as + for a per-frame caption; until 1.2.1 it was the first, + middle and last, and a title that was tallest on another + frame ran off the canvas), once per call of `plot()`. + Each is resolved against that frame's REAL context (`_real_frame_context`: the frame is drawn to get it), and the resolver is a pure function of the context by contract (`FrameContext`), so these cannot @@ -16791,16 +18393,18 @@ def _sampled_dynamic_titles(): a resolver that is going to fail fails HERE, before the animation runs, instead of inside a frame. The animation is left showing frame 0.""" + if _dynamic_title_texts: + return list(_dynamic_title_texts) try: - texts = [ + texts = list(dict.fromkeys( _wrap_title_text( _resolve_dynamic_title_text( _dynamic_title, _real_frame_context(_frame)), _title_wrap, _wrap_break) - for _frame in _caption_sample_frames( - int(line_ani._save_count))] - if len(texts) > 1: - _real_frame_context(0) + for _frame in _caption_text_frames( + content_frame_count(line_ani)))) + _real_frame_context(0) + _dynamic_title_texts.extend(texts) except Exception: # the user's title raised before the animation was # ever handed back: detach it (no HyperAnimation @@ -16847,8 +18451,8 @@ def _sampled_dynamic_titles(): or _dynamic_title is not None or on_frame is not None)): # a dynamic (callable / `{index...}`) title has no text yet: - # the tallest of the first, middle and last frames' titles - # sizes the margin (`_sampled_dynamic_titles`) + # the tallest of every frame's titles sizes the margin + # (`_sampled_dynamic_titles`) _probe_title = None if _dynamic_title is not None: _probe_title = _tallest_title(_sampled_dynamic_titles()) @@ -16898,7 +18502,7 @@ def _sampled_dynamic_titles(): # title was then drawn off the top of the canvas (top # row) or over the x-axis labels of the row above. The # layout -- this one and the grid's -- arranges the - # TALLEST of the first, middle and last frames' titles + # TALLEST of every frame's titles # like a fixed one (frame 0's alone left a title that # grows lines later off the canvas); the grid draws # frame 0 once it is laid out (`_animate_panel_grid`) @@ -16995,6 +18599,38 @@ def _sampled_dynamic_titles(): # figure's size and its layout engine are all untouched. if _caller_figure and ax is not None: _keep_inside_caller_slot(ax) + # the cube of a single 3-D plot stays off the canvas edge and + # off its legend at every camera angle (GH #297). After the + # title margin, the colorbar and the legend fit: they decide + # the room the axes has. A `panels=` grid fits its own cubes, + # and an axes the caller passed (`ax=`) is one of several in a + # figure laid out by the caller or by `hyp.subplots`. + if (ax is not None and not _user_supplied_ax + and _panel_animation is None and not _grid_furniture + and hasattr(ax, 'get_proj')): + if line_ani is not None: + _zoom_scale = getattr(line_ani, '_hyp_zoom_scale', None) + # (a `zoom=` above 1 asks for a closer view than the + # canvas holds: that is the caller's to have) + if _zoom_scale is not None and not _zoomed_in(zoom): + def _frame_azimuths(): + """The camera angle of every frame (each + frame's updater is run; nothing is + rendered).""" + _angles = [] + for _frame in range( + content_frame_count(line_ani)): + _orig_frame_func(_frame, *line_ani._args) + _angles.append(ax.azim) + _orig_frame_func(0, *line_ani._args) + return _angles + _keep_cube_clear( + fig, ax, _AnimatedCubeZoom( + _zoom_scale, + lambda: _orig_frame_func(0, *line_ani._args)), + rotations, frame_azimuths=_frame_azimuths) + elif not animate: + _keep_cube_clear(fig, ax, _StaticCubeZoom(ax), 0) # companion= panels (GH #285): extra 2-D panels laid out beside # the animated plot and revealed in lockstep with it. Created @@ -17040,6 +18676,42 @@ def _update_companions(ctx, _drawn=_panels_drawn): for _panel in _panels_drawn: update_companion_panel(_panel, 0) + def _figure_text_settle(): + """For a text added ABOVE an animated figure (a top + caption, the suptitle): the frames its room is measured + over, and how to draw one (see `_add_caption`). None for + a static figure, measured as it stands.""" + if not animate or line_ani is None: + return None + return (_real_frame_context, _caption_sample_frames( + content_frame_count(line_ani))) + + def _add_over_tallest_title(add): + """Run `add()` -- which measures the room above the + figure -- with the axes showing the TALLEST title an + animation gives it. A per-frame or per-segment title is + set by a frame hook, so it is not on the figure yet (or + is frame 0's) when a top caption or the suptitle is + placed; measured against that, the text landed on the + taller titles of later frames.""" + candidates = [] + if animate and line_ani is not None and ax is not None \ + and _panel_animation is None: + if _dynamic_title is not None: + candidates = _sampled_dynamic_titles() + elif _segment_titles is not None: + candidates = [_text for _text in _segment_titles + if isinstance(_text, str)] + if not candidates: + return add() + _artist = _title_artist(ax, _title_kwargs) + _shown = _artist.get_text() + _artist.set_text(_tallest_title(candidates)) + try: + return add() + finally: + _artist.set_text(_shown) + # caption= (GH #295): one figure-level line of text under # everything drawn above -- the plot, its legend and colorbar, # any companion panel -- so it is added LAST, in a strip the @@ -17056,17 +18728,18 @@ def _update_companions(ctx, _drawn=_panels_drawn): if _dynamic_caption is not None: try: if _animated_caption: - # the REAL contexts of the first, middle and - # last frames (each is drawn to get it): frame - # 0's text is what a still shows, and the three - # together size the caption's room - _n = int(line_ani._save_count) + # the REAL context of every frame (its + # updater is run to get it; nothing is + # rendered): frame 0's text is what a still + # shows, and all of them together size the + # caption's room + _n = content_frame_count(line_ani) _caption_samples = [ _resolve_dynamic_title_text( _dynamic_caption, _real_frame_context(_frame), name='caption') - for _frame in _caption_sample_frames(_n)] + for _frame in _caption_text_frames(_n)] _real_frame_context(0) _caption_text = _caption_samples[0] else: @@ -17095,10 +18768,12 @@ def _update_companions(ctx, _drawn=_panels_drawn): and isinstance(fig, plt.Figure)): plt.close(fig) raise - _caption_artist = _add_caption( - fig, _caption_text, font=_artist_font, - family=list(plt.rcParams['font.family']), - samples=_caption_samples) + _caption_artist = _add_over_tallest_title( + lambda: _add_caption( + fig, _caption_text, font=_artist_font, + family=list(plt.rcParams['font.family']), + samples=_caption_samples, style=_caption_style, + settle=_figure_text_settle())) if _dynamic_caption is not None and _animated_caption: def _update_caption(ctx, _fn=_dynamic_caption, _artist=_caption_artist): @@ -17106,6 +18781,50 @@ def _update_caption(ctx, _fn=_dynamic_caption, _fn, ctx, name='caption')) _frame_hooks.add_internal(_update_caption) + # suptitle= (GH #299): the figure-level title, drawn by the + # caption's own code in a measured strip ABOVE everything else + # -- a caption placed at the top included, so it is added last + if _suptitle is not None and isinstance(fig, plt.Figure): + _add_over_tallest_title( + lambda: _add_caption( + fig, _suptitle, font=_artist_font, + family=list(plt.rcParams['font.family']), + style=dict(_suptitle_style, position='top'), + gid=SUPTITLE_GID, settle=_figure_text_settle())) + + # the figure is finished: its observation labels are placed + # from their usual places on the first draw of it, not from + # where a draw made while it was being laid out left them + # An ANIMATED plot's labels follow a table worked out for + # the whole animation, frame 0 to the last in order + # (`solve_label_tracks`): every frame's labels are placed + # for that frame's own view, and a frame is the same picture + # whatever was drawn before it. + if isinstance(fig, plt.Figure): + from .matplotlib_backend import (reset_label_places, + solve_label_tracks, + track_labels, + tracks_labels) + reset_label_places(fig) + if (ax is not None and _panel_animation is None + and getattr(ax, '_hyp_labels_and_points', None)): + if line_ani is not None: + _orig_frame_func(0, *line_ani._args) + # (the animation keeps the function: the + # labels' state refers to it weakly, so a + # closed figure is freed) + line_ani._hyp_label_frames = ( + lambda _frame: _orig_frame_func( + int(_frame), *line_ani._args)) + track_labels( + ax, content_frame_count(line_ani), + line_ani._hyp_label_frames, + getattr(line_ani, '_interval', None)) + elif tracks_labels(ax): + # (labels a static call adds to an axes that + # holds an animation's join its table) + solve_label_tracks(ax) + # save. `fig.savefig`, NOT `plt.savefig` (release-1.0 audit, # F09-001: `plt.savefig` writes pyplot's CURRENT figure, so # with a user-supplied ax= whose figure was not current the @@ -17797,14 +19516,30 @@ def _measurement_renderer(fig): reads back via `self.canvas` when it fires `'draw_event'` at the end of the draw (`Figure.draw`, matplotlib source), not stale state left on whatever canvas existed before. + + The figure keeps ITS OWN canvas (1.2.1 review round 2): constructing + the Agg canvas rebinds `fig.canvas`, and a figure left on it has lost + its window -- on a GUI backend (macosx, QtAgg, TkAgg) the animation's + `fig.canvas.draw_idle()` then went to the offscreen canvas and the + window stopped updating, for every call that measures (a legend, a + caption, a `panels=` grid, and since 1.2.1 a labeled animation). The + canvas that was there is put back, with the figure's `_original_dpi` + (which a new canvas overwrites with the current, possibly + pixel-ratio-scaled, dpi), exactly as `print_figure` restores them. """ from matplotlib.backends.backend_agg import FigureCanvasAgg + own_canvas = fig.canvas + original_dpi = getattr(fig, '_original_dpi', None) canvas = FigureCanvasAgg(fig) canvas._is_saving = True try: canvas.draw() finally: canvas._is_saving = False + if own_canvas is not None and fig.canvas is not own_canvas: + fig.set_canvas(own_canvas) + if original_dpi is not None: + fig._original_dpi = original_dpi return canvas.get_renderer() @@ -18064,7 +19799,7 @@ def _reserve_animated_2d_title_room(fig, ax, tallest, shown, font=None, axes' top margin (about three lines) and a taller one ran off the top of the canvas. `tallest` is the title's tallest text (a fixed title: itself; a per-segment list: its tallest entry; a per-frame title: the - tallest of the first, middle and last frames', as a caption's room is + tallest of every frame's, as a caption's room is sized). It is set on `ax` and measured on a real draw, and the figure grows UPWARD by what leaves the canvas plus `pad_in` (`_grow_figure`: the axes keeps its size and nothing else moves). A title that already @@ -18802,10 +20537,155 @@ def _multicolor_line_colors(hue_src, orig_lengths, xform, palette, is_rgb=False, return out +def _draw_both_halves(coll, renderer, draw): + """Draw `coll` (a scatter of half-filled markers) with `draw`, then + the OTHER half of every marker: the same edges around the fill + `coll._hyp_other_half` names (none, unless the caller gave a + ``markerfacecoloralt``).""" + draw(renderer) + other = getattr(coll, '_hyp_other_half', None) + if other is None or not coll.get_visible(): + return + path, face = other + paths, faces = coll._paths, coll._facecolors + try: + coll._paths, coll._facecolors = [path], face + draw(renderer) + finally: + coll._paths, coll._facecolors = paths, faces + + +class _HalfFilledMarkers(PathCollection): + """A scatter whose markers have a ``fillstyle`` of one half + (`_HueMarkerLook.wear`): one artist, one offset and one color per + observation like any scatter, drawn as matplotlib draws such a + marker on a line, the filled half and then the other.""" + + def draw(self, renderer): + """Draw the filled half of every marker, then the other half + (`_draw_both_halves`).""" + _draw_both_halves(self, renderer, super().draw) + + +class _HalfFilledMarkers3D(Path3DCollection): + """`_HalfFilledMarkers` in a 3-D axes.""" + + def draw(self, renderer): + """Draw the filled half of every marker, then the other half + (`_draw_both_halves`).""" + _draw_both_halves(self, renderer, super().draw) + + +class _HueMarkerLook: + """How the markers of a dataset colored by a continuous `hue=` wear + the marker styling the caller gave the dataset. + + Such markers are drawn as a scatter, one color per observation, in + place of the `Line2D` the styling kwargs were written for, and the + scatter took the glyph and the size alone: ``markerfacecolor='none', + markeredgecolor='k', markeredgewidth=3`` drew plain filled dots with + default edges, static and animated (1.2.1 review round 2). The same + reading as on a `Line2D`, with the hue in the place of the line's + one color: the hue fills the marker unless ``markerfacecolor`` names + another fill (``'none'`` for a hollow marker), and it colors the + edge unless ``markeredgecolor`` names one; ``markeredgewidth`` is + the edge's width and ``fillstyle`` the half that is filled (the + other half is outlined, and filled with ``markerfacecoloralt`` when + that is given). + matplotlib's short names (``mfc``, ``mec``, ``mew``, ``ms``) are + read as it reads them.""" + + def __init__(self, tkwargs): + from matplotlib import cbook + from matplotlib.lines import Line2D + named = {key: value for key, value in (tkwargs or {}).items() + if isinstance(key, str)} + try: + named = cbook.normalize_kwargs(named, Line2D) + except TypeError: + pass # a name and its alias together: left as written + self.face = named.get('markerfacecolor') + self.edge = named.get('markeredgecolor') + self.width = named.get('markeredgewidth') + self.fillstyle = named.get('fillstyle') + self.other_face = named.get('markerfacecoloralt') + self.size = named.get('markersize') + for name in ('face', 'edge'): + if isinstance(getattr(self, name), str) and getattr( + self, name).lower() == 'auto': + setattr(self, name, None) + if self.fillstyle == 'none': + self.face, self.fillstyle = 'none', None + #: nothing asked for: the scatter is drawn as it always was + self.plain = (self.face is None and self.edge is None + and self.width is None and self.fillstyle is None) + + def glyph(self, marker): + """`marker` with the dataset's ``fillstyle`` (if it has one).""" + if self.fillstyle is None: + return marker + from matplotlib.markers import MarkerStyle + return MarkerStyle(marker, fillstyle=self.fillstyle) + + def wear(self, scatter, marker, alpha=None): + """Give `scatter` (just drawn with ``glyph(marker)``) the half + of each marker that its ``fillstyle`` leaves unfilled. + + A scatter draws one path per marker, and for a half-filled + marker that is the filled half alone: ``fillstyle='left'`` drew + half-discs where a `Line2D` draws a whole outlined marker with + its left half filled (1.2.1 review round 3). The scatter becomes + one that draws both halves (`_HalfFilledMarkers`); it stays one + artist with one offset and one color per observation, so an + animation moves and colors it like any other.""" + if self.fillstyle is None: + return + from matplotlib.colors import to_rgba_array + style = self.glyph(marker) + path = style.get_alt_path() + if path is None: # 'full', or a marker that has no fill + return + path = path.transformed(style.get_alt_transform()) + face = self.other_face + if face is None or (isinstance(face, str) + and face.lower() == 'none'): + face = np.zeros((0, 4)) + else: + face = to_rgba_array(face, alpha) + scatter._hyp_other_half = (path, face) + scatter.__class__ = (_HalfFilledMarkers3D + if isinstance(scatter, Path3DCollection) + else _HalfFilledMarkers) + + def color(self, scatter, colors, alpha=None): + """Color `scatter` by the per-observation `colors` (rows of + RGB(A)); `alpha` is applied to a fill or edge color the caller + named (the rows carry their own).""" + from matplotlib.colors import to_rgba + + def _named(color): + if isinstance(color, str) and color.lower() == 'none': + return 'none' + return to_rgba(color, alpha) + + scatter.set_facecolors( + colors if self.face is None else _named(self.face)) + scatter.set_edgecolors( + colors if self.edge is None else _named(self.edge)) + + +def _hue_marker_look(tkwargs): + """The `_HueMarkerLook` of one dataset's styling kwargs.""" + return _HueMarkerLook(tkwargs) + + def _apply_multicolor_lines(ax, xform, line_colors, kwargs_list, - row_counts=None): + row_counts=None, only=None): """Replace single-color line artists with per-segment-colored - collections (matplotlib backend). + collections (matplotlib backend). `only`: the indices of the datasets + to draw a collection for (every one by default); the data lines of + ALL datasets are removed either way, so a call that mixes formats + draws its markers-only datasets with `_apply_multicolor_markers`. `row_counts` (one per trace): the ORIGINAL row count behind each (possibly antialiased) trace, so a 1-D trace's x stays the row index @@ -18846,6 +20726,8 @@ def _apply_multicolor_lines(ax, xform, line_colors, kwargs_list, is_3d = xform[0].shape[1] >= 3 for i, (xi, ci) in enumerate(zip(xform, line_colors)): + if only is not None and i not in only: + continue tkwargs = kwargs_list[i] if i < len(kwargs_list) else {} lw = tkwargs.get('linewidth') or plt.rcParams['lines.linewidth'] if xi.shape[1] == 1: @@ -18927,9 +20809,17 @@ def _update(ctx): def _apply_multicolor_animation(ax, xform, line_colors, kwargs_list, line_ani, style, chemtrails, precog, bullettime, total_frames, antialias=True, - frame_hooks=None): + frame_hooks=None, trail_alpha=0.3, + markers=False): """Per-frame multicolored (continuous/matrix hue) line rendering for - ANIMATED matplotlib plots (release-1.0 audit, F04-001/F05-002). + ANIMATED matplotlib plots (release-1.0 audit, F04-001/F05-002), and, + for each dataset `markers` flags (one bool per dataset, or one for + all), the same for a MARKERS-ONLY format (GH #297): its hidden artist + is then stood in for by a scatter of its own marker, one color per + observation, over exactly the rows the artist was just drawn over + (never antialiased: a marker sits on an observation). A dataset whose + format has a line AND a marker ('-o') gets the line collection plus a + scatter of its markers on the observations. The static multicolor path (`_apply_multicolor_lines`) swaps the single-color line artists for full-trajectory collections -- on an @@ -18957,11 +20847,15 @@ def _apply_multicolor_animation(ax, xform, line_colors, kwargs_list, then reach what is actually rendered. Without the swap, setting alpha on ``ctx.artists`` changed invisible artists and rendered nothing. """ - from matplotlib.collections import LineCollection + from matplotlib.collections import LineCollection, PathCollection from mpl_toolkits.mplot3d.art3d import Line3DCollection + from .matplotlib_backend import follow_artist is_3d = xform[0].shape[1] >= 3 n = len(xform) + if isinstance(markers, (bool, np.bool_)): + markers = [bool(markers)] * n + markers = [bool(flag) for flag in markers] # artist bookkeeping mirrors matplotlib_backend.animate_plot3D/2D: the # n head lines are created first, then one trail artist per dataset # that wants one (parallel/True AND serial create trails -- serial now @@ -18978,7 +20872,11 @@ def _apply_multicolor_animation(ax, xform, line_colors, kwargs_list, if wants_trail[i] and _trail_artists: trail_lines[i] = _trail_artists.pop(0) - def _linewidth(i): + def _linewidth(i, role='head'): + # a trail keeps its own width: `tail_linewidth=` (GH #299) makes + # the head line's differ from it + if role == 'trail' and i in trail_lines: + return trail_lines[i].get_linewidth() # the hidden head artist already carries the caller's linewidth=: # `animate_plot3D`/`animate_plot2D` pop it out of kwargs_list ONCE per # dataset (matplotlib_backend.py:1602-1606 / :2197-2201, so it cannot @@ -19000,17 +20898,40 @@ def _points(i): return np.column_stack([np.arange(xi.shape[0]), xi[:, 0]]) return xi[:, :3] if is_3d else xi[:, :2] - def _make_collection(i, alpha=None, role='head'): + def _has_marker(artist): + return artist.get_marker() not in (None, 'None', 'none', '', ' ') + + def _make_scatter(i, alpha, role): + """An (invisible until filled) scatter standing in for the markers + of dataset `i`'s hidden artist: same glyph, same size.""" + source = trail_lines[i] if role == 'trail' else head_lines[i] + glyph = source.get_marker() + if not _has_marker(source): + glyph = 'o' + pts = _points(i)[:1] + # (made from one real observation, with the limits put back: the + # animation has fixed them, and a scatter rescales the axes) + limits = [ax.get_xlim(), ax.get_ylim()] + ( + [ax.get_zlim()] if is_3d else []) + auto = ax.get_autoscale_on() + extra = {'depthshade': False} if is_3d else {} + look = _hue_marker_look( + kwargs_list[i] if i < len(kwargs_list) else {}) + coll = ax.scatter(*pts.T, s=float(source.get_markersize()) ** 2, + marker=look.glyph(glyph), alpha=alpha, **extra) + look.wear(coll, glyph, alpha=alpha) + if look.width is not None: + coll.set_linewidth(look.width) + coll._hyp_marker_look = look + ax.set_xlim(limits[0]) + ax.set_ylim(limits[1]) if is_3d: - coll = Line3DCollection([], linewidths=_linewidth(i), - alpha=alpha) - # autolim=False: the animation already fixed the axes limits - # (cube_scale), and autoscaling an EMPTY collection crashes - # inside Axes3D.add_collection3d - ax.add_collection3d(coll, autolim=False) - else: - coll = LineCollection([], linewidths=_linewidth(i), alpha=alpha) - ax.add_collection(coll) + ax.set_zlim(limits[2]) + ax.autoscale(auto) + coll.set_visible(False) + return coll + + def _tag(coll, i, role): coll.set_label('_nolegend_') # match the line artists' unclipping (see animate_plot3D's # axes-box slicing fix) @@ -19028,9 +20949,61 @@ def _make_collection(i, alpha=None, role='head'): coll._hyp_trace_role = role return coll + def _make_collection(i, role='head'): + # the opacity of the artist it stands in for: the dataset's own + # `alpha=` on the head, and that times `trail_alpha=` on the trail + # (the backend folded the two together when it made the trail). + # Giving every trail the bare `trail_alpha` drew the trail of a + # faint dataset more opaque than its head. + source = trail_lines[i] if role == 'trail' else head_lines[i] + alpha = source.get_alpha() + if role == 'trail' and alpha is None: + alpha = trail_alpha + if markers[i]: + coll = _make_scatter(i, alpha, role) + elif is_3d: + coll = Line3DCollection([], linewidths=_linewidth(i, role), + alpha=alpha) + # autolim=False: the animation already fixed the axes limits + # (cube_scale), and autoscaling an EMPTY collection crashes + # inside Axes3D.add_collection3d + ax.add_collection3d(coll, autolim=False) + else: + coll = LineCollection([], linewidths=_linewidth(i, role), + alpha=alpha) + ax.add_collection(coll) + _tag(coll, i, role) + if not markers[i] and _has_marker(source): + # a line-and-marker format ('-o'): the hidden artist carries + # its markers too, on the observations (`markevery`), so the + # collection gets a scatter of them, each in its observation's + # color. Without it the animated plot drew the line alone, + # tail and trail, where the static plot draws both. + # (tagged apart from the trace's own collection, which stays + # the one artist carrying `_hyp_trace_index`/`_hyp_trace_role`) + dots = _make_scatter(i, alpha, role) + dots.set_label('_nolegend_') + dots.set_clip_on(False) + dots._hyp_markers_of = (i, role) + dots.set_zorder(coll.get_zorder() + 0.1) + coll._hyp_markers = dots + # one trace, two artists: the markers are drawn when their + # line is, at its opacity (a callback holds the line alone) + follow_artist(ax, dots, coll, alpha=True) + return coll + head_colls = [_make_collection(i) for i in range(n)] - trail_colls = {i: _make_collection(i, alpha=0.3, role='trail') + trail_colls = {i: _make_collection(i, role='trail') for i in trail_lines} + for i in range(n): + # `dataset_fade=` fades a dataset's `head_marker=` through the + # artist it is handed, which is the collection (GH #299) + _head_marker = getattr(head_lines[i], '_hyp_head_marker', None) + if _head_marker is not None: + head_colls[i]._hyp_head_marker = _head_marker + # ...and is hidden with the collection, which is the artist a + # callback is handed in place of the hidden line + follow_artist(ax, _head_marker, head_colls[i]) for artist in head_lines + list(trail_lines.values()): artist.set_visible(False) @@ -19039,7 +21012,41 @@ def _artist_len(artist): return (len(artist.get_data_3d()[0]) if is_3d else len(artist.get_xdata())) - def _set_segments(coll, pts, colors): + def _set_points(coll, pts, colors): + """Fill the scatter `coll`: one marker per row of `pts`, each in + its own color; no rows, nothing drawn.""" + coll.set_visible(pts.shape[0] > 0) + # (the markers of a line are then hidden again, at draw time, if + # their line is: `follow_artist`) + coll._hyp_hidden_with_leader = False + if pts.shape[0] == 0: + return + colors = np.asarray(colors, dtype=float) + if is_3d: + coll._offsets3d = tuple( + np.asarray(pts[:, k], dtype=float) for k in range(3)) + else: + coll.set_offsets(pts[:, :2]) + coll._hyp_marker_look.color(coll, colors) + coll.stale = True + + def _set_segments(coll, pts, colors, source=None): + """Draw the window `pts` (with its per-vertex `colors`) in `coll`. + `source` is the hidden artist the window was read from: its + `markevery` names the vertices that are observations, where a + line-and-marker format's markers go.""" + if isinstance(coll, PathCollection): + _set_points(coll, pts, colors) + return + dots = getattr(coll, '_hyp_markers', None) + if dots is not None: + every = source.get_markevery() if source is not None else None + if every is None: + at = np.arange(pts.shape[0]) + else: + at = np.asarray([v for v in every if 0 <= v < pts.shape[0]], + dtype=int) + _set_points(dots, pts[at], np.asarray(colors)[at]) if pts.shape[0] < 2: coll.set_segments([]) return @@ -19056,7 +21063,7 @@ def _set_segments(coll, pts, colors): def _dense_for(i): pts = _points(i) ci = np.asarray(line_colors[i], dtype=float) - if not antialias or pts.shape[0] < 2: + if not antialias or markers[i] or pts.shape[0] < 2: return pts, ci, 1 dense, step = antialias_line(pts) if step == 1: @@ -19081,6 +21088,21 @@ def _aa_slice(i, a, b): orig_func = line_ani._func + def _follow_head(i, end): + # GH #299: the head collection takes the width its hidden line was + # just given (a serial reveal switches `tail_linewidth=` per + # frame), and a `head_marker=` takes the color of the row it sits + # on unless its own color was asked for + if not markers[i]: + head_colls[i].set_linewidth(head_lines[i].get_linewidth()) + marker = getattr(head_lines[i], '_hyp_head_marker', None) + # (frame 0 of a serial reveal: the marker waits on the first + # row, in that row's color) + if (marker is not None and len(line_colors[i]) + and not getattr(marker, '_hyp_color_pinned', False)): + marker.set_color(np.asarray(line_colors[i], dtype=float)[ + min(max(end, 1), len(line_colors[i])) - 1]) + def _multicolor_frame(num, *fargs): result = orig_func(num, *fargs) for i in range(n): @@ -19094,14 +21116,17 @@ def _multicolor_frame(num, *fargs): _win = getattr(head_lines[i], '_hyp_row_window', None) if _win is not None: start, end = _win - _set_segments(head_colls[i], *_aa_slice(i, start, end)) + _set_segments(head_colls[i], *_aa_slice(i, start, end), + source=head_lines[i]) + _follow_head(i, end) trail = trail_lines.get(i) if trail is not None: - _twin = getattr(trail, '_hyp_row_window', None) - if _twin is not None: - _set_segments(trail_colls[i], *_aa_slice(i, *_twin)) - else: - trail_colls[i].set_segments([]) + # (no recorded window: the trail has not been drawn + # yet, so it is empty, whatever kind of collection + # stands in for it) + _twin = getattr(trail, '_hyp_row_window', None) or (0, 0) + _set_segments(trail_colls[i], *_aa_slice(i, *_twin), + source=trail) continue # the hidden head artist was just set to the exact visible # window; recover its [start, end) indices from its length @@ -19126,7 +21151,9 @@ def _multicolor_frame(num, *fargs): / max(1, int(total_frames)))) end = max(1, min(n_pts, end)) start = max(0, end - head_len) - _set_segments(head_colls[i], *_aa_slice(i, start, end)) + _set_segments(head_colls[i], *_aa_slice(i, start, end), + source=head_lines[i]) + _follow_head(i, end) trail = trail_lines.get(i) if trail is not None: @@ -19135,7 +21162,8 @@ def _multicolor_frame(num, *fargs): ts, te = n_pts - trail_len, n_pts # anchored at the end else: ts, te = 0, trail_len # chemtrails/bullettime: from 0 - _set_segments(trail_colls[i], *_aa_slice(i, ts, te)) + _set_segments(trail_colls[i], *_aa_slice(i, ts, te), + source=trail) if frame_hooks is not None and frame_hooks.state: recorded = frame_hooks.state.get('artists') if recorded is not None: @@ -19191,13 +21219,15 @@ def _expand_labels(labels, old_lengths, new_lengths): def _apply_multicolor_markers(ax, xform, point_colors, kwargs_list, - fmt=None): + fmt=None, only=None): """Replace single-color marker artists with per-point-colored scatter (matplotlib backend). Gives exact per-observation colors -- e.g. mixture proportions render as true blends instead of quantized groups. When - `fmt` is a single format string carrying a marker character (e.g. the - 'o' of 'o-'), that marker glyph is used for the scatter points - (F02-004); otherwise the default circle is drawn.""" + a dataset's format string (`fmt`, one for all or one per dataset) + carries a marker character (e.g. the 'o' of 'o-'), that marker glyph + is used for its scatter points (F02-004); otherwise the default + circle is drawn. `only`: the indices of the datasets to scatter + (every one by default).""" # as in `_apply_multicolor_lines`: replace the DATA artists, keep the # tagged forecast overlays _kept_forecasts = [] @@ -19229,16 +21259,25 @@ def _apply_multicolor_markers(ax, xform, point_colors, kwargs_list, and len(point_colors[_ds])): _fc_line.set_color(point_colors[_ds][-1]) - marker = None - if fmt is not None and not isinstance(fmt, (list, tuple, np.ndarray)): - _, marker = split_marker_line_fmt(fmt) - marker = marker or 'o' + def _glyph(i): + one = fmt + if isinstance(fmt, (list, tuple, np.ndarray)): + one = fmt[i] if i < len(fmt) else None + if isinstance(one, bytes): + one = one.decode('utf-8') + if not isinstance(one, str): + return 'o' + return split_marker_line_fmt(one)[1] or 'o' is_3d = xform[0].shape[1] >= 3 for i, (xi, ci) in enumerate(zip(xform, point_colors)): + if only is not None and i not in only: + continue tkwargs = kwargs_list[i] if i < len(kwargs_list) else {} - ms = float(tkwargs.get('markersize') - or plt.rcParams['lines.markersize']) + look = _hue_marker_look(tkwargs) + _marker_name = _glyph(i) + marker = look.glyph(_marker_name) + ms = float(look.size or plt.rcParams['lines.markersize']) s = ms ** 2 # scatter sizes are areas in points^2 # the trace's alpha= travels WITH the per-point colors, as on the # line path (`_apply_multicolor_lines`): the scatter replaces the @@ -19251,13 +21290,20 @@ def _apply_multicolor_markers(ax, xform, point_colors, kwargs_list, ci = np.column_stack([ci[:, :3], np.full(len(ci), float(_alpha))]) if xi.shape[1] == 1: - ax.scatter(np.arange(xi.shape[0]), xi[:, 0], c=ci, s=s, - marker=marker) + dots = ax.scatter(np.arange(xi.shape[0]), xi[:, 0], c=ci, s=s, + marker=marker) elif is_3d: - ax.scatter(xi[:, 0], xi[:, 1], xi[:, 2], c=ci, s=s, - depthshade=False, marker=marker) + dots = ax.scatter(xi[:, 0], xi[:, 1], xi[:, 2], c=ci, s=s, + depthshade=False, marker=marker) else: - ax.scatter(xi[:, 0], xi[:, 1], c=ci, s=s, marker=marker) + dots = ax.scatter(xi[:, 0], xi[:, 1], c=ci, s=s, marker=marker) + look.wear(dots, _marker_name, alpha=_alpha) + if not look.plain: + # a hollow, outlined or half-filled marker keeps that look + # (the animated plot's scatters wear the same one) + if look.width is not None: + dots.set_linewidth(look.width) + look.color(dots, np.asarray(ci, dtype=float), alpha=_alpha) def _mixture_name(model): """Registry name for a cluster-model spec (string or class).""" diff --git a/hypertools/plot/plotly_backend.py b/hypertools/plot/plotly_backend.py index 6dfa799a..98695613 100644 --- a/hypertools/plot/plotly_backend.py +++ b/hypertools/plot/plotly_backend.py @@ -981,21 +981,28 @@ def _frame_title_dict(text, index, style, segment_colors): return title -def _plotly_legend_entry_traces(entries, ndims): +def _plotly_legend_entry_traces(entries, ndims, styles=None): """Invisible traces that exist only to carry an explicit legend entry (GH #285) -- plotly's equivalent of matplotlib's proxy `Line2D` handles. Used for a matrix/mixture `hue=`'s palette swatches and for `legend_colors=[(label, color), ...]`, neither of which corresponds to a drawn trace. A 3-D figure needs `Scatter3d` (a 2-D `Scatter` cannot live - in a `scene`), so the trace type follows `ndims`. + in a `scene`), so the trace type follows `ndims`. `styles` (the + matplotlib backend's `legend_entry_styles`): one dict per entry when + each entry stands for one drawn dataset, whose given line WIDTH its + key then takes (the other line properties keep the plain swatch). """ import plotly.graph_objects as go + if styles is None or len(styles) != len(entries): + styles = [None] * len(entries) traces = [] - for label, color in entries: + for (label, color), given in zip(entries, styles): + width = (given or {}).get('linewidth') common = dict(mode='lines', name=str(label), showlegend=True, hoverinfo='skip', - line=dict(color=_to_plotly_color(color), width=2)) + line=dict(color=_to_plotly_color(color), + width=2 if width is None else width)) if ndims >= 3: traces.append(go.Scatter3d(x=[None], y=[None], z=[None], **common)) @@ -1161,6 +1168,7 @@ def plotly_draw(data, fmt=None, kwargs_list=None, labels=None, legend=None, elev=10, azim=-60, point_colors=None, tail_duration=2, focused=None, chemtrails=False, precog=False, bullettime=False, zoom=1, + trail_alpha=0.3, forecasts=None, forecast_owner=None, forecast_overrides=None, forecast_schedule=None, forecast_trail=0, @@ -1175,6 +1183,7 @@ def plotly_draw(data, fmt=None, kwargs_list=None, labels=None, legend=None, segment_titles=None, ownership=None, forecast_reveal=None, into=None, title_kwargs=None, title_segment_colors=None, legend_kwargs=None, legend_entries=None, + legend_entry_styles=None, axis_scale='unit', xlim=None, ylim=None, x_date=False, truths=None, truth_reveal=None, forecast_labels=None, forecast_datasets=None, datasets_drawn=None, @@ -1335,6 +1344,9 @@ def plotly_draw(data, fmt=None, kwargs_list=None, labels=None, legend=None, bullettime : bool or list of bool Past+future trail flag(s), per trace. Same `animate='serial'` support as `chemtrails` above. + trail_alpha : float + The factor a trail's opacity is its dataset's alpha times + (`plot()`'s ``trail_alpha=``; default 0.3). zoom : float 3-D camera zoom factor, for ANIMATIONS only (as `plot()` documents it, and as the matplotlib backend applies it); a static figure keeps @@ -2403,9 +2415,10 @@ def _rows_of(i, arr): # existed) never reached plotly's trail traces even though the # matching head trace already honors it (see `tkwargs.get('alpha')` # a few dozen lines above, in the head-trace loop). + # (`trail_alpha=`, GH #299, replaces the 0.3 on both backends) _trail_alpha = tkwargs.get('alpha') - _trail_alpha = (0.3 if _trail_alpha is None - else 0.3 * float(_trail_alpha)) + _trail_alpha = (trail_alpha if _trail_alpha is None + else trail_alpha * float(_trail_alpha)) color = _to_plotly_color(tkwargs.get('color'), _trail_alpha) width = float(tkwargs.get('linewidth') or DEFAULT_LINEWIDTH_PT) * PT_TO_PX @@ -2843,7 +2856,8 @@ def _rows_of(i, arr): # swatches, or `legend_colors=[(label, color), ...]`. Added as # data-free traces, plotly's equivalent of matplotlib proxy handles. if legend_entries: - fig.add_traces(_plotly_legend_entry_traces(legend_entries, ndims)) + fig.add_traces(_plotly_legend_entry_traces( + legend_entries, ndims, legend_entry_styles)) # predict= legend entries: one per model name, after the explicit # entries (the matplotlib legend lists them in the same order). Only # with a legend to list in -- like the matplotlib proxies, which exist diff --git a/notes/release_notes_v1.2.0_draft.md b/notes/release_notes_v1.2.0_draft.md index aac2bef7..0616a9d1 100644 --- a/notes/release_notes_v1.2.0_draft.md +++ b/notes/release_notes_v1.2.0_draft.md @@ -21,6 +21,7 @@ Python 3.10 through 3.13. Extras are unchanged from 1.1.0. ## Changed - **Panel grids share their colors, one legend and one colorbar.** In a `panels=` grid each dataset is drawn in the color it has in the single-axes plot of all the datasets, `hue=` uses one scale (or one label-to-color mapping) for the whole figure, and the grid shows one legend and one colorbar beside the panels instead of one per panel. Legends stay per panel only where the colors mean different things in each panel (for example clusters fit separately per panel). +- **Shared axis labels are drawn on the outer panels only:** x under the lowest panel of each column and y on the left-most panel of each row, when the panels of that column or row share the label. Labels that differ are all kept. - **A panel grid's default figure is sized by the grid:** 3.2 in per panel each way, at least 6.4 in wide, instead of a fixed 6.4 x 4.8 in. `size=` is honored as before, and `hyp.subplots()` keeps its default. ## Fixed @@ -34,7 +35,7 @@ Python 3.10 through 3.13. Extras are unchanged from 1.1.0. ## Upgrading from 1.1.0 -- **Static `panels=` figures look different:** per-dataset colors, one shared legend and colorbar, and a figure sized by the grid. Pass `size=` to set the figure size yourself. +- **Static `panels=` figures look different:** per-dataset colors, one shared legend and colorbar, shared axis labels on the outer panels only, and a figure sized by the grid. Pass `size=` to set the figure size yourself. - **If you relied on the automatic `tight_layout`** of a figure made with `plt.subplots` and drawn into with `ax=`, call `fig.tight_layout()` after plotting, create the figure with `layout='constrained'`, or build the grid with `hyp.subplots`. - On a single line plot with a categorical `hue=`, `legend=[...]` now takes one name per category (it took one per drawn run). diff --git a/notes/resume_2026-11-24_release_1.2.1.md b/notes/resume_2026-11-24_release_1.2.1.md new file mode 100644 index 00000000..ed3f0002 --- /dev/null +++ b/notes/resume_2026-11-24_release_1.2.1.md @@ -0,0 +1,223 @@ +# Resume notes: HyperTools 1.2.1 (PR #300), written 2026-11-24 about 05:45 EST + +Read this first in a fresh session. Details per review round are in +`notes/session_2026-11-22_feat295-animated-panels.md`. + +## Where things stand + +- 1.2.0 is released (PyPI, GitHub, Read the Docs, conda-forge). `master` == + `v1.2.0` == 8086b5b8. Nothing for 1.2.1 is tagged, uploaded or on master. +- PR #300 (draft), branch `post-1.2.0`, is the 1.2.1 work. +- Pushed head: 54b11252. Local full suite on it: 9239 passed, 24 skipped + (matplotlib 3.10). The related label, legend and layout files also pass + on matplotlib 3.11.2 (2496 passed on each version). CI on 54b11252 was + running when this was written; CI on the previous head 7a5f997e was + green (16 test and gate jobs; Read the Docs red as expected). +- A commit after 54b11252 holds only these notes and a path fix in the + session notes. See "Unpushed" at the end. + +## What PR #300 contains + +- GH #299: trails and chemtrails with marker formats; `head_marker=`, + `tail_linewidth=`, `trail_alpha=`, `hold=`, `caption_kwargs=`, + `suptitle=` / `suptitle_kwargs=`. +- GH #297: animated cube and its axis labels inside the canvas and off the + legend on every frame; crowded `labels=` moved off each other and off + legends, colorbars, titles, captions; continuous `hue=` on animated + markers; half `fillstyle=` and `markerfacecoloralt=` on hue markers; + named 2-D legend `loc` inside the frame; example edits. +- Animated datapoint labels planned over all frames (no wobble). +- `labels=` on streaming plots (causal placement). +- `legend_colors=` pair keys take their dataset's line styling (a defect + that 1.1.0 and 1.2.0 share). +- Version 1.2.1, CHANGELOG, README image links `v1.2.1`. + +## The owner's decisions, in his words (2026-11-23) + +- Labels in animations: "for axis labels, they should move with the + rotations so they remain aligned with the axes. same for labels of + individual datapoints (e.g., in every frame the labels should have + correct positioning). for static text like legends, titles, and other + annotations: compute placement once based on the *worst case* rotations + of the axes, and then place once so that the static text (and other + static content) remains stable across frames." +- Wobble: "slight shifts between frames are OK but not if they are + wobbling back and forth so that it looks glitchy. movement needs to be + in a consistent direction". Also: "let's see how it looks". +- Streams: asked "What about streaming animations?"; of three options he + chose 2, add streaming labels to 1.2.1 (relayed by his coordinating + session as "hypertools: 2"). +- `hold=` shorter than one frame: "Warn, add no frame". +- `markerfacecoloralt=` on hue markers: "Keep it". +- Argument names (`head_marker`, `tail_linewidth`, `trail_alpha`, `hold`, + `caption_kwargs`, `suptitle`): "Names are fine". +- All of these except the streams question reached this session through + his coordinating session's question dialogs. + +## Waiting on the owner + +Update 2026-11-24 about 06:20 EST: he looked at the review page (version +2, built from 54b11252) and wrote, in this session: "The new figures and +animations look great!" Item 1 below is answered. That is approval of the +pictures, not the go for release. He then answered three questions in a +dialog in this session: +- Cube floor: "Keep 55% (Recommended)". Item 2 is settled. +- Streams: "Add the three now", meaning `legend=`, `caption=` and + `suptitle=` on streaming plots go into 1.2.1. Work started 06:30 EST in + the worktree of branch `worktree-agent-a054066ab320401bb`; see "Status + at wind-down" for how far it got. `head_marker=`, `tail_linewidth=` and + `trail_alpha=` on streams were not asked for. +- Release: "Prepare, then ask me", meaning after the stream arguments are + in and green: final gallery from the last commit, publish + `docs-gallery-v1.2.1` and `docs-notebooks/v1.2.1/`, record commit, dist, + draft GitHub release, mark PR #300 ready; then STOP and ask him before + the master fast-forward, the tag and PyPI. + +1. His look at the review page (private to him): + https://claude.ai/artifact/AYEuVQguA8jJEB9jq2yWC6 + It was built from 7a5f997e. Things he may object to: long leader lines + in animated labels; 30 crowded labels still overlap on about half the + frames; stream labels that end up close together. +2. Cube floor: with a very tall corner legend the animated cube may now + shrink to 55% (was 70%); needed on matplotlib 3.11, where text lines + are taller. An existing test pinned 70% and was changed to 55%. His + call whether to keep 70% and accept the overlap. +3. Whether streams should also take `legend=`, `caption=`, `suptitle=` + (small), `head_marker=` (medium), `tail_linewidth=` / `trail_alpha=` + (large). Not built. +4. A tutorial sentence about LSL discovery of two outlets on one macOS + machine (his to decide; none written). +5. Go for release. Nothing is released without it. + +## Known limits (reported to him) + +- 30 crowded animated labels: 1 to 3 overlapping pairs on about half the + frames (0 for 8 and 12 labels); a little worse on matplotlib 3.11. +- Grid whose panels have unequal label counts: up to 3 overlapping pairs + on most frames under 3.11 (up to 2 on a few frames under 3.10). Not yet + improved. +- Stream labels are causal: they react, they cannot move early. They + cannot be dragged and ignore `font=`. +- `plot()` with animated labels plans up front: about 0.5 s for 20 labels, + 1.8 s for 60. +- The LSL test that failed in full-suite runs before the 2026-11-23 crash: + cause only partly known (see the session notes). + +## Exact next steps + +1. Check CI on the pushed head (`gh pr checks 300`). +2. Gallery: a local rebuild from 54b11252 and a comparison with 1.2.0 is + in `~/hypertools-review-1.2.1/` (`after/`, `before/`, `pairs/`, + `comparison.json`; the 7a5f997e build is under `build_7a5f997e/`). + The status of that rebuild is in the last section of this file. Update + the review page from it (page source: `~/hypertools-review-1.2.1/page/`, + republish to the same artifact URL after reading it). +3. Apply the owner's feedback on the page; each code change means: related + tests on matplotlib 3.10 AND 3.11, full suite, push, CI. +4. Release only on his explicit go, per `RELEASE_CHECKLIST.md` ("The + 1.2.1 release: read this first"): rebuild the gallery from the FINAL + commit, publish `docs-gallery-v1.2.1` and `docs-notebooks/v1.2.1/`, + record commit in `docs/prebuilt_gallery.json`, build dist, draft + release, fast-forward master, tag, PyPI, conda-forge. Read the Docs on + the PR stays red until the gallery is published. +5. On merge: comment on and close GH #297 and #299 with factual + descriptions only. + +## Traps + +- The local venv has matplotlib 3.10; CI uses 3.11 on Python 3.11+. Test + both before pushing. The 3.11 copy used on 2026-11-23 lived in a + temporary folder; rebuild it with + `uv pip install --target "matplotlib==3.11.*"` if it is gone. +- `scripts/add_colab_install_cell.py` must never be run off master, not + even with `--help`. +- Temporary folders do not survive a reboot. Keep review material under + `~/hypertools-review-1.2.1/`. +- Two agent worktrees exist under `.claude/worktrees/` with branches + `worktree-agent-a054066ab320401bb` and + `worktree-agent-abf3e80dedb9e2214`; both are fully merged into + `post-1.2.0` and can be removed. +- The fetch for the comparison added the local ref + `origin/docs-gallery-v1.2.0`. + +## Status at wind-down + +Written 2026-11-24 06:10 EST. + +- Gallery rebuilt locally from 54b11252: 52 of 52 examples, 0 warnings. + Against 1.2.0: 116 of 141 files byte-identical, 25 files (10 figures) + changed, none worse than 1.2.0. `plot_missing_data_001`, `_002` and + `plot_multiindex_001` are byte-identical to 1.2.0 again. The market + legend keys match their paths. +- The review page (version 2) shows that build. +- Not explained: `plot_labels_001` differs between the 7a5f997e build and + the 54b11252 build in 0.0013% of pixels (none by more than 8/255; + labels in the same places). Probably the static cube zoom fix of + 54b11252, which touches every static 3-D figure; not verified. Check it + (render the example on both commits and diff) before release. +- Still showing a few label boxes on data points: + `animate_painting_embeddings`. +- No gallery was published; no `docs-gallery-v1.2.1`, no + `docs-notebooks/v1.2.1/`. +- CI on 54b11252: see `gh pr checks 300`. If it was still running at + suspend, nobody was watching it. + +## Final state at 07:55 EST, before the suspend + +- Pushed head is still 54b11252. CI on it finished GREEN (16 test and + gate jobs; Read the Docs red as expected). +- LOCAL ONLY, on `post-1.2.0`, not pushed (`git status -sb` shows the + branch ahead of `origin/post-1.2.0`): + - two notes commits; + - 5585bdd4 `legend=`, `caption=`, `suptitle=` on streaming plots (his + "Add the three now"); 21 new tests in `tests/test_stream_text_1_2_1.py`; + - a last commit fixing a helper in that new test file. +- Full suite on 5585bdd4 (matplotlib 3.10): 9255 passed, 2 failed. Both + failures were `test_legend_caption_and_suptitle_are_drawn_once_and_stay_clear[2]` + and `[3]` with `ReferenceError: weakly-referenced object no longer + exists`: the new test file's `_live_figures` helper scanned + `gc.get_objects()` with `isinstance`, the same fault fixed earlier in + `tests/test_stream_labels_1_2_1.py` (7a5f997e). The helper now checks + `type()`. The two stream test files pass together (81 passed), but the + FULL SUITE HAS NOT BEEN RERUN after that fix. That is why nothing was + pushed. +- Nothing is running: no suite, no agent, no detached process. + +### First steps of the next session + +1. Full suite on the local head (`.venv/bin/python -m pytest -q -p + no:cacheprovider`, about 40 minutes) and the stream, label, legend and + layout test files on matplotlib 3.11. +2. If green: push `post-1.2.0`, wait for CI. +3. Then release preparation, as he chose ("Prepare, then ask me"): final + gallery from the last commit, publish `docs-gallery-v1.2.1` and + `docs-notebooks/v1.2.1/`, record commit, dist, draft GitHub release, + mark PR #300 ready. STOP and ask him before master, tag and PyPI. +4. The review page was built from 54b11252 and does not show the three + new stream arguments; a contact sheet of them existed only in the + temporary folder. + +## After the suspend (2026-11-24, from 09:52 EST) + +- Full suite on 57453668 (matplotlib 3.10): 9257 passed, 24 skipped. The + 40 label, legend, layout and stream test files on matplotlib 3.11.2: + 1794 passed, 2 skipped. Ruff clean. Pushed 57453668 at 11:51 EST. +- `docs/tutorials/market_sectors.ipynb` re-executed + (`scripts/execute_tutorial.py`); its mp4 now shows the thick "Market" + key and thin sector keys (frame at 20 s looked at). +- `plot_labels_001` difference explained: rendering `examples/plot_labels.py` + on 7a5f997e and on the current head gives 4 differing pixels of 307200 + (0.0013%), each by 1/255, in one spot (x 446 to 463, y 163 to 172). The + example has no legend, so the legend-key part of 54b11252 cannot reach + it; what remains is its static cube zoom change. No visible change. +- Release commit (this one): CHANGELOG heading dated 2026-11-24, the + re-executed market tutorial. The file gates pass with + `HYPERTOOLS_REQUIRE_RELEASE=1` (23 passed; the two published-gallery + gates are run after publishing). +- Next, in this order (RELEASE_CHECKLIST.md step 2): build the gallery + from this commit; rehearse; `publish_prebuilt_gallery.py --push`; + commit `docs/prebuilt_gallery.json` (the one commit allowed after the + build); `publish_gallery_notebooks.py --ref v1.2.1 --push`; both + gallery gates; dist; draft GitHub release; push the branch; PR #300 + body and ready. STOP before master, tag, PyPI: the owner chose + "Prepare, then ask me". diff --git a/notes/session_2026-11-22_feat295-animated-panels.md b/notes/session_2026-11-22_feat295-animated-panels.md index 329d2623..8a794922 100644 --- a/notes/session_2026-11-22_feat295-animated-panels.md +++ b/notes/session_2026-11-22_feat295-animated-panels.md @@ -364,3 +364,841 @@ Final checks after the last change (panel, caption, animation, plot-review, docs - Reading (not reproduced: no Windows machine here): `_kill_process_tree` now also kills `_descendant_pids(proc.pid)` (round 3, Q6). On Windows that list came from `Win32_Process` parent ids, which are never cleared when a parent exits, while process ids are reused. A render worker handed the id of a dead ancestor of the test runner makes the runner its "descendant", and `taskkill /F` ends it (exit code 1, no summary). Intermittent by nature, which fits three green Windows jobs beside one dead one. - Fix: `_descendants_in_table` follows a parent link only when the child is not older than the parent (Windows creation ticks; a row without a creation time is never taken for a child), and `_descendant_pids` never returns the calling process or its ancestors. POSIX tables carry no creation times and are walked as before. Tests: `test_a_stale_parent_link_is_not_followed`, `test_this_process_and_its_ancestors_are_never_descendants`, `test_descendant_pids_finds_a_real_child_and_never_this_process` (real process table). - Also in this stretch: the gallery's own videos are remuxed fast start by the scraper (fa4e765b), two example comments corrected (b81e1d2d), matplotlib 3.11 text metrics (5f104d0a). The user confirmed on 2026-11-22 that the 1.2.0 gallery figures are correct ("Current versions are correct for all figures"). + +## Released: 1.2.0 (2026-11-22, about 23:45 EST) + +Jeremy's instruction: "Go for 1.2.0 release on pypi and then on conda forge". + +- `master` == tag `v1.2.0` == 8086b5b8. Master CI run 45077352879 and tag CI run 45089891535: 17 of 17 jobs green. +- The tag run needed one re-run: `test (macos-latest, 3.13)` failed `tests/test_multibyte.py::test_render_script_exits_NO_BROWSER_when_the_browser_never_answers` on its own sanity check, `the stand-in browser was never seen running: {43413: '(Python)', 43416: ''}` (8431 passed). The re-run passed. Cause and fix below. +- PyPI: `hypertools-1.2.0-py3-none-any.whl` sha256 3aa7d00e04bdfe21a8f234c86faabd4b9684f9dc812468da24e79b0692fd9d3b, `hypertools-1.2.0.tar.gz` sha256 b1ba6eb4d59c8d2f2460783ce28d05665da378cf7db1c7f404e83621af55e125 (the digests recorded at build time; read back from PyPI's simple index). `https://pypi.org/pypi/hypertools/1.2.0/json` kept answering a cached 404 for some minutes after the upload; `https://pypi.org/pypi/hypertools/json` and the simple index showed the files at once. +- GitHub release "HyperTools 1.2.0" published on the tag (Latest), both files attached; the seven links in its body answer 200. +- Read the Docs: `stable` moved to the tag by itself (API: `stable 8086b5b8 built`); `/en/stable/` and `/en/latest/` `optional_dependencies.html` answer 200; a gallery page under stable links `docs-notebooks/v1.2.0/` and that notebook's install cell is `%pip install -q "hypertools[interactive]>=1.2.0"`. +- Clean environment (Python 3.12): `pip install hypertools` gives 1.2.0; static and animated panel grids with `caption=` run. Published-wheel check (`hypertools[interactive]==1.2.0 --only-binary=hypertools --report`): the report names the wheel and its digest; a plotly figure, a Kalman forecast and an animated grid saved as a fast-start mp4 all run. +- On Python 3.9, `pip install hypertools` gives 0.8.2 without a message (`requires-python >=3.10`); the first smoke environment was built on 3.9 by mistake. +- PyPI page: 13 README images at the `v1.2.0` tag and the version badge all answer 200. +- conda-forge: no bot pull request had appeared, so https://github.com/conda-forge/hypertools-feedstock/pull/2 was opened from the `jeremymanning` fork (version and sha256 only; `[project] dependencies` is identical at v1.1.0 and v1.2.0). Checked first: a conda-forge-only Python 3.10 environment with the recipe's requirements solves, the PyPI sdist installs into it, `pip check` is clean, `import hypertools` gives 1.2.0. + +### The flaky sanity check (branch `post-1.2.0`, not on master) + +- Cause: `_run_render_watching_its_processes` kept one command line per process, the latest. A process is described differently over its life (`(Python)` between fork and exec, `sleep 600`, a bare `(sleep)` under load, `` once ended), so a last snapshot that caught the stand-in already ended erased the `sleep 600` seen before it. +- Fix: the watcher keeps every command line each process was seen with; the "was it ever seen" check reads the whole history; `_alive` counts a process as still there when its current command line is any of those seen for it (stricter than before, never looser). Checked on real processes: a running `sleep` is reported, an ended one not yet collected by its parent is reported, a collected one is not. +- Master gets no commits between releases (release gate), so this waits on the branch for the next release. +- `notes/release_notes_v1.2.0_draft.md` now equals the published release body (it lacked the outer-labels bullet). + +## Issue #299 (2026-11-23, branch `post-1.2.0`, for 1.2.1; not pushed) + +Cause of the bug: `animate_plot3D`/`animate_plot2D` (hypertools/plot/matplotlib_backend.py) created the trail artists only inside `if any(is_line(f) for f in fmt)` (and `if is_line(fmt)`). `is_line` means "a PURE line format, no marker", so `'-o'`, `'o-'`, `'.-'`, `'--s'` built no trail artist and the updaters, which tolerate a missing trail through `zip_longest`, drew nothing and said nothing. A markers-only dataset got a trail of faded markers only when another dataset of the same call was a pure line. Plotly was never affected (it builds a trail trace for every flagged dataset). + +Fix: the gate is gone; every dataset with a trail flag gets its trail, drawn with its own format. The trail of a line+marker format carries faded markers on the observations because `_aa_window(..., artist=trail)` already ran `_mark_observations` on it, exactly as for the tail. Markers-only: trail of faded markers (matplotlib now equals plotly), so there is no case left where a trail flag is dropped and no new warning was needed for it. + +Second bug found on the way (fixed, in the CHANGELOG): a trail took its color from the axes' color cycle, so with `chemtrails=[False, True]` dataset 1's trail was drawn in dataset 0's color. `_own_color` gives a trail its head line's color unless the kwargs or the format string name one. + +Added (all real `plot()` arguments, all four animation ones also accepted inside the `animate={...}` dict): + +- `head_marker=`: marker str / True / dict (`marker`, `size`, `color`, `alpha`, `edgecolor`, `edgewidth`, `fillstyle`, `zorder`). One extra `Line2D` per dataset, created after the trails (so `ax.lines[:n]` are still the heads and the trails follow: `_apply_multicolor_animation` finds them by position), placed by `_place_head_marker` in the four updaters. Tagged `_hyp_trace_role='head_marker'`. With continuous `hue=` the multicolor frame function recolors it to the head row's color unless the dict pinned a color. Not in `FrameContext.artists` (the `dataset_fade` updater maps artists to datasets by position); the fade updater follows `line._hyp_head_marker` instead. +- `tail_linewidth=`: head line width; trail keeps `linewidth=`. Serial: switched per frame (`_set_serial_linewidth`), thick only while the dataset is the comet head. +- `trail_alpha=`: replaces the constant 0.3 (matplotlib `_trail_kwargs`, the multicolor trail collection, plotly's trail traces). +- `hold=` seconds: `FuncAnimation` is given the frame LIST `0..n-1` then `n-1` repeated (`held_frame_sequence`), so every wrapper `plot()` puts round the frame function later (multicolor, hooks, titles, captions) just sees the last index again. `_hyp_content_frames` on the animation is the count of distinct frames; `content_frame_count()` is what the caption/title sampling uses, and `HyperAnimation.draw_frame` clamps to it. A panel cell never holds; `_animate_panel_grid` holds for the grid. +- `caption_kwargs=`: size/color/weight/style/family/alpha/linespacing/position/loc, applied to the `Text` before `_wrap_caption`/`_caption_text_height_in` run. +- `suptitle=` + `suptitle_kwargs=`: drawn by `_add_caption` itself (gid `hypertools-suptitle`, position top), in `_lay_out_panel_grid` for grids (static and animated, one path) and at the caption site of `plot()` for single plots. + +Decisions: + +- `title=` as one string with `panels=` names every panel (documented, tested), so the figure title is a new argument, `suptitle=`. +- `caption_kwargs=`/`suptitle_kwargs=` follow `title_kwargs=`/`legend_kwargs=` rather than separate `caption_size=`... arguments. +- Matplotlib-only (NotImplementedError on plotly, the `caption=`/`companion=` wording): `head_marker`, `tail_linewidth`, `hold`, `suptitle`, `caption_kwargs` (through `caption=`). `trail_alpha` works on plotly. +- `head_marker`/`tail_linewidth`/`trail_alpha` on a static plot or `spin`/`morph` warn like the trail flags do; `hold` on a static plot raises like `on_frame=`. +- `_grow_figure` now also keeps hypertools' own figure texts (caption, suptitle) at their place in inches: adding the suptitle's strip at the top would otherwise have moved a bottom caption. +- Room above an animated figure: measured over the first/middle/last frames (grid: the cells' own frame functions set per-frame panel titles), and for a single plot with the tallest per-frame/per-segment title set on the axes while measuring (`_real_frame_context` runs no hooks, so the title was not there). + +Tried and dropped: + +- Clamping the frame number inside the backend's frame function for `hold=`: the wrappers `plot()` adds afterwards would still have received the raw index. The frame list does it for all of them. +- Default head marker size = the dataset's `markersize=` alone: with `'-o', markersize=3, tail_linewidth=3` the marker disappeared under the tail. Now never less than 2.5 x the tail width. +- A warning for markers-only + trail flags: not needed once the trail is drawn. +- Scalar only: `head_marker`, `tail_linewidth`, `trail_alpha` take one value for all datasets (no per-dataset lists). +- Not changed: the legend key of a dataset shows the tail's width when `tail_linewidth=` is set. No example in examples/ was edited (the prebuilt gallery record is not to be touched). + +Tests: tests/test_issue299_animation_arguments.py (new). + +## Issue #297 (2026-11-23, branch `post-1.2.0`, for 1.2.1; not pushed) + +Six gallery layout points plus one suspicion. Three library fixes, four example edits. Tests: tests/test_issue297_layout.py (new, 32). Scratch renders (before/after per point) were kept outside the repo. + +Per point: + +1. `animate_conversation`, cube on the left canvas edge. Cause: a single animated 3-D axes fills the canvas and the frame functions draw the cube at box zoom 1.125 (`_anim_box_zoom`); on a square figure the cube seen corner-on is wider than the canvas (measured on 8 x 8 in: x from -4 to 826 px of 800 over the turn; in landscape 6.4 x 4.8 it is 78 to 575 of 640, which is why the old margin tests never saw it). Fix: `plot._keep_cube_clear` (called in `plot()` after the title margin, colorbar and legend fit, before the companions): projects the cube's eight corners at every camera azimuth of the turn (`_camera_azimuths`, as the panel fit does), and lowers the zoom factor the frame functions already multiply by (`_cell_zoom_scale`, now also on the animation as `_hyp_zoom_scale`) until the corners are 2% of the canvas inside it and the cube's outline (separating-axis test against a box, closed form in `_cube_excess`) is that far from the legend and from the figure's other axes. Static single plots go through the same function with `_StaticCubeZoom` (the handle static grids use); a static cube only ever changes when the legend was put inside the axes. Not run for a plot drawn into an `ax=` (other panels of the figure would count as obstacles), for `panels=` grids, or with `zoom=` above 1. +2. `animate_weather_decades`, last marker cut. Cause: the example's own `fig.add_axes([0.615, .., 0.38, ..])` ends at 0.995 of the width and its head marker is drawn unclipped, centered on that edge at the last month. The library's `companion=` panel was checked and is fine (ends at 0.98; marker 14 px inside). Fix in the example (and the tutorial notebook's source): width 0.37. +3. `plot_labels`, label boxes on each other. Cause: every label is annotated at the fixed offset (-20, 20) pt. Fix: `matplotlib_backend.declutter_labels`, run at draw time by `_LabelDeclutter`, an invisible child artist of the axes with the lowest zorder (so it runs before the labels are drawn, with the final layout, at any dpi, at the frame's camera angle: one path for static, hand-rotated and animated). Greedy in label order: a label keeps its place unless its box covers an earlier one, else the first free corner (4 corners x 3 distances), on the canvas if possible, else the least overlap. No hysteresis on purpose: frames must be idempotent. A label moved by the reader or the caller (its `xyann` no longer what hypertools set) is left alone. More than 300 visible labels: nothing is moved. +4. `plot_shapes_zoo`, teapot. Cause: the example's `,` pixel marker; the teapot has 1,728 rows but only 301 distinct points (it is the Utah teapot's control points). Fix in the example: `.` at markersize 2.5 for clouds under 5,000 points. It is visible now; it still does not read as a teapot from the PCA view, because it is 301 control points. +5. `animate_market_sectors`, legend against the cube. Cause: the example added its own `ax.legend(loc='upper left')` to the full-canvas axes after the call, so the library knew nothing of it. Fix: the example uses the library's legend (`legend_colors=` pairs, `legend_kwargs={'loc': 'upper left', 'fontsize': 8}`) and `_keep_cube_clear` keeps the cube off it. Side effect: the "Market" key line is drawn at the width of the other keys (it was 3.4). +6. `plot_datasets_tour`, Bechdel panel. Cause: the data. Dollar columns from $828 to $3.2e9; PCA's first axis is stretched by a few blockbusters, and the display transform (documented: mean-center, then one pooled min/max into [-1, 1]) centers on the MEAN, so skewed data sits in a corner; the point "outside the box" is the maximum, whose center is exactly on a cube face. Fix in the example: log10 of the dollar columns. +7. Animated markers-only plot with continuous `hue=`: real defect. `plot()` sent it to `_apply_multicolor_markers`, which removes the animated line artists and scatters every observation once. Measured: 80 of 80 points on frames 0, 15 and 29; 2-D frames byte-identical; 3-D only the camera moved; trails never drawn. Fix: `_apply_multicolor_animation(markers=True)`: the same per-frame path as lines, with a scatter (the hidden artist's glyph and size) per head and per trail, filled from the hidden artist's `_hyp_row_window`. `spin` keeps the static scatter (all points, camera only). + +Behavior changes for existing figures (all in the CHANGELOG): animated single 3-D plots on square/portrait figures draw the cube about 10% smaller (zoom factor 0.90 on 8 x 8, 5 x 8, 6 x 6); landscape with the default legend 0.946 (the cube corner was 5.6 px inside the legend's box at the widest view); landscape with a colorbar 0.98; landscape without either unchanged (1.0). Static plots unchanged unless a legend is inside the axes. `zoom=` above 1 is not fitted. An animated figure shows frame 0 when `plot()` returns (the fit draws frame 0 through the updater alone, no hooks). Regression renders, old library against new: 11 static examples (23 figures: basic, legend, hue, colorbar, 2D, multiindex, nested_lists, density, surface, predict, align) and animate_panels, animate_painting_embeddings, animate_spin, animate_trails, animate_trails_mix, animate_surface_morph, save_movie pixel-identical at frames first/mid/last; animate (legend), animate_forecast and animate_morph_zoo changed as described (smaller cube). animate.py's MDS panel differs run to run on the same code (unseeded MDS). + +Tried and dropped: + +- Room = the axes' own box (`get_position(original=True)`): after `_fit_right_legend` that box is the SQUARE the cube is drawn in (it re-sets the position from the active one), so every legend plot shrank to 0.90. The room is the canvas; the legend and other axes are obstacles. +- Changing the display transform to center on the bounding box (it would cure point 6 in the library): it is the documented `axis_scale='unit'` contract and moves the data in every figure. Left for the owner to decide; not done. +- Hysteresis for label corners (keep the previous corner): breaks frame idempotence. +- Deciding label places once at annotate time: stale after `tight_layout`, a resize or a rotation. +- Explicit calls of the declutter in `update_position`/`_sync_anim_labels`: three call sites instead of the one draw-time artist. + +Not done: the two tutorial notebooks (market_sectors, weather_decades) have their SOURCE cells updated to match the scripts but were not re-executed, so their stored outputs are from the old code. docs/prebuilt_gallery.json untouched. Plotly: labels and the cube fit are matplotlib-only changes. + +## 1.2.1 review round 1 (2026-11-23, branch `post-1.2.0`; not pushed) + +Two reviews of the #299/#297 work: a tester who ran the code (T1-T7) and a code-only review (C1-C8). Each item was reproduced with a real call first, on the unmodified head in a scratch worktree, then fixed. Tests: tests/test_review_round1_1_2_1.py (new, 86; 69 of them fail on the head before this round, the rest are "good values still work" controls). + +Per item: + +- T1 labels jump between frames. Confirmed: 71 changes of place in 60 frames for 8 labels on a spin, 777 for 30, 233 on a window animation. Cause: `declutter_labels` put every label back up-left and placed all of them afresh on every draw, so any small move of the points reshuffled the greedy result. (Superseded for ANIMATED plots by the follow-up below: placed once, then held.) Fix (matplotlib_backend.py `declutter_labels`): the placement is stateful. A label keeps its place (`_hyp_place`) until its box meets the box of an EARLIER label (or a place it was moved to has left the canvas); then it takes, among the 8 directions x 3 distances that are clear of every other label (with 3 pt of room) and on the canvas, the shortest reach and at that reach the nearest place; the place it last left ranks last at its reach; with no clear place it moves only if that halves what it covers. It never goes back on its own. Up to 3 passes per draw. Now 26 / 130 / 27 changes on the same three runs, 0 or 1 straight-back hops, no overlaps for 8 labels (30 labels on 640 x 480 still overlap in places: 3.8 pairs on average, 6.0 before). Because a draw now depends on where the labels were, `reset_label_places` puts them home: at the end of `plot()` and of `_lay_out_panel_grid` (so a draw made during layout leaves nothing behind), when an animation's frame number goes down (`_sync_anim_labels`: loop, save after preview, `draw_frame` of an earlier frame), and for a label that is hidden. Two passes through an animation give identical placements (tested). Dropped: ordering the candidates by distance moved alone (labels walked out to the 70 pt reach); a 1 px tolerance on "covered" (left sub-pixel overlaps that the box test counts). +- T2 / C3 animated `'-o'` + continuous hue draws no markers. Confirmed (2-D, 3-D, panels; tail and trail). Cause: `_apply_multicolor_animation` hides the line artist, which carries the markers too, and stood a line collection in for it. Fix: each such collection gets a scatter (`coll._hyp_markers`, tagged `_hyp_markers_of=(dataset, role)`) filled from the hidden artist's `markevery` (the observation vertices) with the per-observation colors. +- T3 `tail_linewidth=` on a markers-only format silently ignored. Confirmed. `_warn_ignored_animation_styling(any_line=)` warns when no dataset has a line. +- T4 values inside the dicts. Confirmed for all the listed values except `suptitle=b'bytes'`: that is decoded as UTF-8 on purpose, exactly as `caption=b'...'` is (documented and tested now, not changed). Fix: `_check_style_values` (plot.py), called by `_validate_head_marker`, `_validate_figure_text_kwargs` and `_normalize_title_kwargs`; errors read `head_marker['size'] must be a marker size in points greater than 0; got -3.` (the key is the one the caller wrote). +- T5 docstring said plotly raises; a static plotly plot warns. Confirmed. Decided by what `chemtrails=` does on a static plotly plot (warns): code kept, docstring/guide/changelog corrected (static: warning on either backend; animated plotly: NotImplementedError). Grammar: "head_marker only affects". +- T6 `hold=` in a gif. Confirmed: 10 stored frames, the last 1100 ms, for a 20-frame animation (Pillow merges identical frames); mp4 has all 20. Kept; docstring, guide and changelog now say exactly that; test reads the gif back. +- T7 cube-to-legend gap under 2%. Not confirmed as stated: the tester divided a bounding-box gap by the canvas WIDTH. Measured on every frame with the real renderer, cube outline to legend box: 1.99% of the canvas's shorter side; cube to canvas edge 1.95-1.97%. The changelog now says "about 2% of the shorter side (1.95% to 2%)"; a test measures it (at least 1.9%). +- C1 serial marker trail + hue crashes at frame 0. Confirmed (AttributeError `set_segments`, 2-D and 3-D, chemtrails/precog/bullettime). Fix: an empty window goes through `_set_segments`, which knows scatters. +- C2 serial hue trails keep stale geometry. Confirmed (frame 5 then frame 0: 432 segments still drawn; same at the last frame). Fix: the serial updaters (2-D and 3-D) record `_hyp_row_window = (0, 0)` on a trail they clear. +- C4 trail alpha with hue. Confirmed (0.5 instead of 0.1). Fix: the stand-in collection takes the hidden artist's alpha. Found with it: an animated hue LINE ignored `alpha=` (drawn opaque); fixed the same way. +- C5 suptitle over a top caption that grows. Confirmed (single 2-D/3-D and grids). Fix in `_add_caption`: each hypertools figure text remembers its tallest text (`_hyp_tallest_text`) and earlier ones are shown at it while a later text's room is measured. +- C6 label anchors stale after `_keep_cube_clear`. Confirmed (8.7 px off). Fix: `declutter_labels` projects every 3-D label's anchor at draw time. +- C7 head markers do not fade with hue. Confirmed. Fix: the head collection carries `_hyp_head_marker`; the fade updater also fades `_hyp_markers`. +- C8 spin draws the whole line at `tail_linewidth=`. Confirmed. Fix: `_head_linewidths(linewidths, style)` leaves spin/morph alone. +- N1 notebooks: docs/tutorials/market_sectors.ipynb and weather_decades.ipynb were regenerated (scripts/generate_tutorial_notebook.py; sources identical to the committed ones once the generator's prose was in American spelling) and executed with scripts/execute_tutorial.py (kernel hypertools-venv, install cell skipped, venv still editable afterwards). Market fetched live data: 318 months through Oct 2026 (317 through Sep before). Both mp4 clips were re-rendered by the notebooks (market 5.4 MB, weather 4.5 MB); a frame of each was looked at (legend clear of the cube; last-month marker inside the canvas). scripts/add_colab_install_cell.py was not run (the generator only imports `portable_video_source` from it; its `main()` is guarded). +- N2 neighbors found and fixed: mixed formats with hue (`['-', 'o']`) drew every dataset as markers, animated (`markers=` is per dataset now) and static (`only=` in `_apply_multicolor_lines`/`_apply_multicolor_markers`, each dataset's own glyph); `dataset_fade=` mapped a trail to a dataset by its place among the trails, wrong with `chemtrails=[False, True]` (trail lines carry `_hyp_trace_index` now); `title_kwargs=` values were as unchecked as the new dicts'; scripts/generate_tutorial_notebook.py still had British spellings in its prose, so regenerating undid the American spelling of the committed notebooks. + +Behavior changes this round adds (all in the changelog): `title_kwargs={'size': -3 | 0 | nan}` raises instead of drawing nothing; an animated hue-colored line honors `alpha=`; a hue trail is `trail_alpha` x `alpha`; static and animated mixed-format hue plots draw lines as lines. + +### T1 follow-up: an animation's labels are placed once and hold (2026-11-23) + +Design decision from the coordinator after round 1: the stateful declutter still moved labels during an animation (26 switches in 60 frames with 8 labels) and made `draw_frame(i)` depend on the frames drawn before it. Rule now: frames are deterministic. + +- matplotlib_backend.py `freeze_label_places(ax, draw)` (new): puts the labels home, shows every label (hidden ones included), makes one real draw (which runs the same `declutter_labels`), restores visibility, sets `ax._hyp_labels_frozen`. `declutter_labels` on a frozen axes only reprojects 3-D anchors and returns; `reset_label_places` skips frozen axes; the rewind reset in `_sync_anim_labels` is gone. No second placement implementation. +- plot.py `plot()`: after the final layout, for an animated single axes: frame 0 through the frame function, then `freeze_label_places`. `_lay_out_panel_grid`: the same per cell for an animated grid. +- Static figures are unchanged (declutter at draw time, stateful under hand rotation, `reset_label_places` at the end of `plot()`). +- Measured (60 frames): switches 0 for spin 8, spin 30, window 3-D, window 2-D and reveal, on two passes. Cost of holding: label boxes meet at later views (overlapping pairs mean/max: spin 8 3.2/6, spin 30 20.9/36, window 30 3.6/11; the stateful version had 0 for spin 8). With 30 crowded 2-D labels the one placement itself leaves 3 overlapping pairs (26 at the usual places). +- Determinism, pixel for pixel (scratch `det.py`, 14 configurations: labeled spin/window/reveal, parallel, line+marker with trails and head marker, hue window, serial, serial hue 2-D, dataset_fade, caption+suptitle, morph, panels with labels, legend spin): frame i in order == shuffled == reversed == the frames a real Pillow writer received from `animation.save` == the same frames of a second identical call. Static `plot()` twice: identical. So history dependence applied to labels only (the stale serial hue trail of C2 was the other case and was fixed in round 1). +- Tests: section A of tests/test_review_round1_1_2_1.py rewritten (zero switches, first-view placement, shuffled/reversed pixels, saved == drawn, panels, static twice, hysteresis moved to the hand-rotated static figure). tests/test_issue297_layout.py passes unmodified. + + +## 1.2.1 review round 2 (2026-11-23, branch `post-1.2.0`; not pushed) + +Library commit 9fed77ec, then tests/docs/CHANGELOG in the next commit. +Tests: `tests/test_review_round2_1_2_1.py` (117 of its tests fail on +82933121). 1.2.0 reference venv: scratchpad `review121/old` (mpl 3.10.8). + +Per item (confirmed? cause; fix): + +- T1 confirmed. `_check_style_values` had its own list of allowed types. + Now it asks matplotlib (`Text().update` / `Line2D(**{k: v})`), and adds + only: size/markersize/linespacing must be positive and finite (also as + numeric strings), text color not `'auto'`, family a str or list of str. + None-valued keys are dropped in `_validate_figure_text_kwargs` and + `_validate_head_marker`. Against 1.2.0 over 290 `title_kwargs` values the + only differences left: size False/0/negative/NaN (and as strings) and + linespacing 0/negative/NaN now raise; 1.2.0 accepted them. +- T2 confirmed. The axes kept only the last call's label list. + `_watch_labels` merges lists per axes. +- T3 confirmed. Each panel warned for itself. `_warn_ignored_grid_styling` + collects one case per panel and warns only if true of all. +- T4 confirmed. Placement used the renderer's pixels. `declutter_labels` + now works in points; text sizes come from ONE Agg renderer at 100 dpi + (`_label_size_pt`). Tried first: base `RendererBase` metrics; dropped, + its sizes were up to 4.5 px smaller than Agg's drawn boxes and labels + "clear" in points overlapped by a pixel on screen. +- T5 fixed the garbled line and rewrote the claims that changed. +- T6 `{'marker': True}` is 'o', `{'marker': False}` no marker. +- T7 made true: caption and dynamic title text is resolved on every frame + (`_caption_text_frames`, `_sampled_dynamic_titles`). Cost about 0.9 ms a + frame for a callable; no extra draws. +- T8 see timings in the hand-back. Causes: a full declutter on every + draw (now memoized in `ax._hyp_label_answer`, skipped while `plot()` + lays out via `labels_held_while_plotting`), a draw in + `freeze_label_places` (now none), `_cube_corners_px` projecting per view + (now one vectorized projection, equal to 1e-12 px). +- P1 confirmed. Trail lists were checked against drawn runs. + `_trail_flag_per_run` maps dataset flags onto runs (also `surface=`). +- P2 confirmed, NOT changed: `random_state=None` is the documented + default for every random stage; `random_state=0` gives the same picture. + Added a sentence to the `cluster` docstring. +- P3 decided: a warning on both backends; plotly makes no annotations, matplotlib keeps its hidden label artists (an existing test reads them). +- C1 confirmed (in 1.2.0 too for legend/caption/panels). + `_measurement_renderer` restores the canvas and `_original_dpi`. +- C2 confirmed. `_watch_labels` reinstalls the declutter artist when it + is not among the axes' children and clears the frozen flag when no + earlier label survives. +- C3 confirmed. `_TraceFollowers` (one invisible artist per axes) makes + the hue marker scatter and the head marker follow their leader. Tried + and dropped: a `_hyp_shown` flag that re-showed followers each draw + (broke a round 1 test that hides the dots directly); closures on the + artists (figure no longer pickles). +- C4 confirmed, static plot too. `_HueMarkerLook`. +- C5 confirmed with real MouseEvents (1 of 12 labels changed place after + a 0.7 degree drag on 82933121, 0 now). Hidden labels keep their place. +- C6 confirmed. `isinstance(marker, str)` before the emptiness test. +- C7 confirmed. No measurement draw at all for label placement. + +Test note: a caller-supplied 3-D axes is smaller than hypertools' own, so +the same 30 crowded labels leave 3 overlaps there and 0 in an own figure; +that is crowding, not a C2 defect (cleared axes == never-used axes). + +## 1.2.1 review round 3 (2026-11-23, branch `post-1.2.0`; not pushed) + +Four items from the third review, each reproduced with real code before +the fix. Tests: `tests/test_review_round3_1_2_1.py` (20 of them fail on +20192664). Scratch renders: session scratchpad `round3fix/`. + +| Item | Confirmed | Fix | +|-|-|-| +| 1. `test_datatype_gate` failed on three `isinstance(..., np.ndarray)` sites in `plot.py` | yes | The morph `labels=` check is now `_any_label_given` (shared predicates `is_array_dataset` / `is_series_like`; a Series of labels is read per entry). `_trail_flag_per_run` unwraps an OPTION array, so it has an ALLOWLIST entry like the same line in `trails.py`. | +| 2. Stale label callbacks after `ax.clear()` | yes, 2-D and 3-D: `AttributeError: 'NoneType' object has no attribute 'transData'` out of the button release, new labels left hidden. 1.2.0 did not raise (round 2 regression); 1.2.0 did add a pair of callbacks per call | `_connect_label_events(fig, ax)`: one press/release pair per axes per canvas, reading `_label_entries(ax)` at event time. Which axes a canvas serves is a `WeakSet` on the canvas, so nothing unpicklable is on the axes or figure. | +| 3. `_label_size_pt` cache key | yes: after `set_rotation(90)` the size stayed (78.6, 10.8) pt, and after `set_parse_math(False)` too | Key now also holds `parse_math`, rotation, rotation mode, `transform_rotates_text`. Not the alignment: placing a label changes it, and a key that held it made every redraw a new problem (`test_a_redraw_of_an_unchanged_figure_places_nothing_again`). A wrapped text is never cached. | +| 4. Half `fillstyle=` with continuous `hue=` | yes: only the filled half was drawn (`scatter` ignores `get_alt_path()`). 1.2.0 ignored `fillstyle=` and drew full discs | `_HueMarkerLook.wear` turns the scatter into `_HalfFilledMarkers` / `_HalfFilledMarkers3D` (module-level subclasses, so figures still pickle), whose `draw` draws the collection and then the alt path with the same edges and the `markerfacecoloralt` fill (none by default). One artist, one offset per observation, so the animated path (`_make_scatter`, `_set_points`) needed one line. | + +- Item 4 pixels were compared with `ax.plot(..., fillstyle='left')`. + With `'-o'` the hue line shows through the empty half, as in matplotlib; + a static plot draws the line over the markers (zorder 2 over 1, as + before), so the tests count outline pixels there and read single pixels + for `'o'` only. +- matplotlib's own per-label drag callbacks (`DraggableAnnotation`, 2-D) + are six `button_release_event` entries per labeled call; matplotlib + drops the ones of removed labels at the next release. Not ours. +- CHANGELOG 1.2.1: the labels entry (shared callbacks, restyled labels + measured again) and the hue marker entry (half fill styles, + `markerfacecoloralt=`). + +## 1.2.1 review round 4 (2026-11-23, branch `post-1.2.0`; not pushed) + +Nine items from the fourth review, each reproduced with real code first +(scratch `round4fix/repro.py`, the tester's scripts in `review121c/`, +the 1.2.0 venv `review121/old`). Tests: +`tests/test_review_round4_1_2_1.py` (111; 64 of them fail on a0ef72b8). +Before/after renders: session scratchpad `round4fix/` +(`before_item*.png`, `after_item*.png`, `old120_item*.png`). + +| Item | Confirmed | Cause; fix | +|-|-|-| +| 1. Panel labels on the shared legend (regression) | yes: 6 of 12 seeds in 3-D and 6 of 12 in 2-D put a label on the legend, a panel title or the suptitle; 1.2.0: 0 on the legend | The declutter only knew the other labels, and it runs after the layout that made room for the labels at their usual place. `_label_obstacles_pt` (matplotlib_backend.py): every legend (axes and figure), every colorbar axes with its tick labels, every axes title, every figure text, in points, widened to whole points. `declutter_labels` moves a label that lies on one; a candidate place on one is a last resort (it costs the label's whole box plus `_LABEL_OBSTACLE_WEIGHT` = 4 times the covered area, as an off-canvas place costs the whole box); they are part of the memo key. One path: static draw and `freeze_label_places`. | +| 2. Labels on title text (1.2.0 too) | yes | Same rule. A single label is looked at too (it used to return early with fewer than two labels). Tiny figure (3 x 2.5 in, size 18 texts, 30 labels): labels on texts 9 -> 0, on the legend 1 -> 0 (matplotlib 3.10 and 3.11), label pairs on each other 15 -> 29 (3.11: 23 -> 33): there is no room, and labels lie on each other rather than on the texts. First version (furniture cost = label cost) left 1 label on the title on 3.10 and 2 on the legend on 3.11, although with every label at its usual place none is on furniture; hence the last-resort cost. | +| 3. 2-D `legend_kwargs={'loc': ...}` | yes, static and animated, 1.2.0 too | Not a stray `bbox_to_anchor`: the 2-D axes fills the canvas and the frame is a square drawn inside it (`frame_2d`), so the corner of the axes is outside the frame. `frame_2d` records the square (`ax._hyp_frame_box`, data coordinates) and `legend_call_kwargs(ax=)` anchors a NAMED `loc` to it (`bbox_to_anchor` = the square, `bbox_transform=ax.transData`). Not touched: a caller's `bbox_to_anchor`/`bbox_transform`, a coordinate pair as `loc`, `axis_scale='data'` (no square), 3-D (the legend is inside the axes and `_keep_cube_clear` shrinks the cube), `panels=` (documented: `loc` names the side of the grid). | +| 4. Two head markers with categorical `hue=` | yes | Each category run is its own line with its own marker artist, and a run the reveal had passed kept its marker at its end. `_head_holders`: per input dataset (the `ownership`), only the last reached run places its marker; the others are emptied. Color is the run's, so the category's. | +| 5. Serial frame 0 empty | yes (2-D, 3-D, panels) | `serial_reveal_counts` is 0 everywhere on frame 0. Not changed (an existing contract with tests); `_serial_head_holders` gives the first dataset the marker on frame 0 and it is placed on `data[:1]`. With a continuous `hue=` it wears row 0's color (`_follow_head`). | +| 6. `head_marker=` dict keys | yes | Aliases `ms`, `mec`, `mew`, `mfc`, `mfcalt`, `c`, and `facecolor`/`facecoloralt`; keys `markerfacecolor`, `markerfacecoloralt`. One option under two names raises. Found by the new test: a bad face color was not refused by `_check_style_values` (a `Line2D` takes it and fails in the draw); now checked like the edge color. | +| 7a. `trail_alpha=` warning under `'window'` | yes | Own message for `animate='window'` (it draws no trail whatever is passed). | +| 7b. `hold=0.01` | yes | DECIDED: the rule stays `round(hold * frame_rate)` and a positive hold that rounds to no frame WARNS, naming `1 / frame_rate`. The coordinator's default was "at least one frame"; not taken because `tests/test_issue299_animation_arguments.py::test_hold_zero_is_the_animation_it_always_was` asserts `hold=0.04` at 10 fps adds no frame, and existing tests are not to be changed. Switching is `max(1, ...)` in `_validate_hold` plus that assertion. | +| 8. Undocumented definitions | yes | Docstrings for `hide_labels`, `update_position`, `_HalfFilledMarkers.draw`, `_HalfFilledMarkers3D.draw`. | +| 9. LSL tests under load | failure NOT reproduced | Measured on 12 cores: discovery by name 6 ms idle, a steady 1.0 s with 144 CPU-bound processes (load average 118); first sample 20 ms either way; the file passed (27) with 48 burners in 197 s. So I don't know the exact cause; the quantized 1.0 s points at missed resolve queries, and a few more of them use up 5 s. Tests only: discovery `timeout=5.0` -> `30.0` (returns as soon as the outlet answers) in test_lsl_streaming.py, test_io_audit_lsl.py, test_io_audit_final.py; the stall test's `timeout=2.0` -> `10.0` (it is also the wait for the first sample). No assertion changed. `hypertools/io/lsl.py` untouched. | + +Tried and dropped: + +- Obstacle boxes measured on the label metrics renderer at 100 dpi + (`Text.get_window_extent(dpi=)`): it resets the figure's dpi inside a + draw and is wrong during a `bbox_inches='tight'` save. The boxes are + measured on the draw's renderer and widened to whole points instead. + UNCERTAIN: a place that is free at one dpi and covered by a fraction + of a point at another could still differ between a PNG and a PDF; the + round 2 cross-renderer tests pass. +- Changing `serial_reveal_counts` so frame 0 reveals one row: it moves + every serial animation's first frame and its `revealed_counts`. + +Not done: a `companion=` panel and other panels of a grid are not label +obstacles (labels may reach over a neighboring panel, as before). A +per-frame title or caption is an obstacle at its frame 0 extent only. + +Checks run for round 4 (machine load average 120 to 430 throughout, from +other suites running at the same time): new file 111 passed (also 111 +under matplotlib 3.11.2); review rounds 1 to 3: 343 passed, 1 skipped; +test_issue297_layout 32; test_issue299_animation_arguments 122; the 73 +other files named label/legend/hue/panel/caption/title/animat/docstring/ +gate/signature/changelog/lsl: 2687 passed, 9 skipped, 5 failed, then all +5 passed on a rerun of their files (363 passed, 8 skipped with the +docstring, gate, signature, changelog and new files). Of the 5: one was +mine (`test_panel_rosters_cover_every_documented_per_dataset_argument` +reads the phrase "per dataset" in a docstring as a per-dataset argument; +the `head_marker` text was reworded). Three were time bounds in +tests/test_animation_export.py (kill within 20 s / 30 s) and one was +`test_io_audit_lsl.py::test_multiple_matching_streams_warn` ("DID NOT +WARN": with `minimum=2` and 30 s only one of two outlets was heard) at +load average about 400; not reproduced on the rerun, cause not +established beyond the load. `ruff check .` clean. + +## 1.2.1 round 5: per-frame labels (owner decision 2026-11-23) + +Branch `post-1.2.0`, after a11c09e9; not pushed. The owner rejected the +design of 82933121 (an animation's labels decluttered once and held, +`freeze_label_places`). The decision, word for word: + +> for axis labels, they should move with the rotations so they remain +> aligned with the axes. same for labels of individual datapoints (e.g., +> in every frame the labels should have correct positioning). for static +> text like legends, titles, and other annotations: compute placement +> once based on the *worst case* rotations of the axes, and then place +> once so that the static text (and other static content) remains stable +> across frames. + +Added while the work was under way (relayed by the coordinator), also the +owner's words: + +> slight shifts between frames are OK but not if they are wobbling back +> and forth so that it looks glitchy. movement needs to be in a +> consistent direction + +So a frame's picture is a function of (the animation, the frame index), +not of the frame alone and never of the render order. + +### What was built (hypertools/plot/matplotlib_backend.py, plot.py) + +- `_arrange_labels(places, left, anchors, sizes, pads, canvas, obstacles, ...)`: + the placement rule, taken out of `declutter_labels` unchanged. ONE + function places a static figure's labels (`declutter_labels`, from where + the labels hang) and every frame of an animation (`solve_label_tracks`, + from where the frame before left them). The animation passes four + things a static draw does not: `ahead` (the anchors of the coming + frames: of equally clear places the one that stays clear longest is + taken), `avoid` (places left a short while ago), `resting` (a label that + has just moved is not moved again for another label) and `strict` (a + label at its usual place that leaves the canvas moves too). +- `solve_label_tracks(ax)`: runs the frame function for every frame + (updater only, nothing rendered, no `on_frame=` call), records each + label's anchor in points and whether it is shown, then goes through the + frames in order. A loop without a seam (`_labels_loop`: same labels on + the first and last frame, and their points no further apart than between + other neighboring frames) is gone round until a round repeats the round + before, at most 16 times (fewer above 40 labels: 640 // labels, at + least 3). `_settle_short_stays` then removes every stay shorter than + three glides (the label keeps the place before, or goes straight to the + one after, where that keeps it on the canvas and off static content); + this is what guarantees no out-and-back. `_ease_label_tracks` turns the + steps into glides (Hann weights, 0.5 s, 5 to 15 frames, finished at the + frame the label had to move at). A glide that would cross static content + whose both ends are clear of becomes a jump (`'forced'` in the table). +- The table (`label_tracks(ax)`: `offsets` (frames, labels, 2) in points + from the point to the middle of the text, `places`, `shown`, `forced`, + `periodic`, `ease_frames`, `rounds`) is kept in a module + `WeakKeyDictionary`, not on the axes: it holds the frame function, and + an attribute on the axes broke `pickle.dumps(fig)` + (tests/test_review_round2_1_2_1.py::test_an_animated_figure_still_pickles). +- `_sync_anim_labels` (every animation style's updater) calls + `_apply_label_tracks(ax, num)`; a table whose signature (canvas size in + points, axes box, label ids) no longer matches is worked out again + there. `declutter_labels` on such an axes only reprojects and applies + the row. `label.update_positions(renderer)` was dropped from + `_sync_anim_labels`: the draw does it, and it cost about 1 ms a label on + every frame. +- Static content, C: `_keep_cube_clear` measured the cube's corners only + (every 3 degrees of the turn, which is sufficient for the cube: its + reach is smooth in the angle, so between two samples it exceeds the + larger by at most 1 - cos(1.5 degrees) = 0.03%). The AXIS LABELS were + not measured at all: on a 5 x 5 inch spin "the z axis" was up to 61 px + off the canvas, and with legend + title + caption + suptitle the axis + labels crossed static content on 6 of 60 frames (scratch + `axes_check.py`). Now the axis texts are measured at EVERY frame's + camera angle (`frame_azimuths`, read by running each frame's updater; + which edge a label hangs from changes discretely with the view, so a + sample is not provably enough) by drawing the three axis objects alone + (`axis_text_boxes_px`), and the cube is zoomed out until each is on the + canvas and off `_label_obstacles_pt`. Grids keep `_fit_panel_cubes` + (axis labels sampled every 30 degrees); checked on every frame of a + 2 x 2 labeled grid with and without legend/titles/caption: nothing off + the canvas, on static content or on another panel's label + (`test_a_grids_axis_labels_stay_on_the_canvas_and_apart_every_frame`). +- `_label_obstacles_pt` gained two kinds of obstacle, for static figures + too: every OTHER axes of the figure (a label that reached into the next + panel of a grid was painted over by that panel's background; seen on the + first panels contact sheet), and a 3-D axes' own axis texts. +- Plotly, F: `labels=` are layout annotations in data coordinates + (`_build_point_annotations`), added once to the base layout. They follow + their points as the scene turns (plotly projects them), at one fixed + offset, are never decluttered and are shown on every frame, also for + points not revealed yet. Not changed (placement happens in the browser). + +### Measured + +Turn-backs (an offset component goes more than 1 pt one way and more than +1 pt back within one glide's time on either side), largest step between +two frames in points, and changes of place, 60 frames at 15 fps; "alone" = +every frame placed on its own from the usual places (`_independent=True`): + +|case|turn-backs table|turn-backs alone|max step table|max step alone|changes table|changes alone| +|-|-|-|-|-|-|-| +|spin, 8 labels|0|29|33.2|107.8|3|95| +|spin, 12 labels, legend, title, suptitle, caption|0|46|12.6|188.5|3|139| +|spin, 30 labels, legend, title, caption|0|164|47.1|188.6|31|720| +|window, 3-D, 30 labels|0|59|0.0|188.5|0|223| +|window, 2-D, two lines|0|0|0.0|57.5|0|8| +|serial, 2-D|0|2|0.0|188.5|0|15| +|2 x 2 panels, 48 labels|0|251|33.9|166.3|22|700| + +In a 2-D animation the points do not move on screen (only a 3-D camera +turns), so labels there appear and disappear and need no glide. + +Timings, 3-D spin of 200 points, 60 frames, CPU seconds (`time.process_time`, +best of 3; the machine's load average was 90 to 180 throughout, so wall +times were useless: the same frame measured 107 ms and 598 ms minutes +apart). Before = a11c09e9 (scratch `round5fix/head`), scratch `bench_cpu.py`: + +|labels|plot() before|plot() after|frame before|frame after| +|-|-|-|-|-| +|0|0.008 s|0.008 s|2.9 ms|2.9 ms| +|20|0.054 s|0.46 s|37.4 ms|37.0 ms| +|60|0.138 s|1.89 s|106.7 ms|106.4 ms| +|200|0.481 s|5.39 s|365.1 ms|324.4 ms| + +A frame costs what drawing the label boxes costs (about 1.7 ms a label); +applying the table is a lookup. `plot()` pays for the table: one updater +call per frame plus up to 16 rounds of the loop (3 rounds at 200 +labels). No cap was added. + +### Tests + +New: tests/test_review_round5_1_2_1.py (50 tests). Rewritten, because +they pinned the rejected design (every other assertion kept or made +stricter): + +- tests/test_review_round1_1_2_1.py: + `test_animated_labels_hold_their_places` -> + `test_animated_labels_follow_one_table`; + `test_animated_labels_are_placed_for_the_first_view` -> + `test_animated_labels_are_placed_for_every_view`; + `test_animated_panels_hold_their_label_places` -> + `test_animated_panels_show_a_frame_the_same_way_every_time`. +- tests/test_review_round2_1_2_1.py: + `test_an_axes_reused_after_an_animation_places_labels_again` (reads + `label_tracks(ax)` instead of `_hyp_labels_frozen`); + `test_labels_added_to_an_animations_axes_are_placed_once_and_held` -> + `test_labels_added_to_an_animations_axes_join_its_table`; + `test_an_animated_grid_places_its_labels_without_a_draw_per_panel` + (same attribute change); + `test_an_animations_labels_are_placed_as_a_draw_would_place_them` + (a row of the table placed on its own against a real static draw). +- tests/test_review_round4_1_2_1.py: + `test_animated_panel_labels_are_placed_off_the_legend_and_texts` (off + legend, titles and figure texts on EVERY frame, and a frame shown again + has its labels where they were). + +### Known limits + +- With many labels on a small cube labels still overlap each other (30 + labels on the default figure). Static content and the canvas edge are + kept clear on every frame of every tested case. +- A label is allowed to overlap another for up to three glides (1.5 s) + rather than move twice in a row: that is the price of no wobble. +- A dynamic (per-frame) title is measured as it stands when the table is + worked out, not per frame. +- Looping animations whose rounds do not repeat within the round limit + keep the last round; `_settle_short_stays` still removes short stays + round the seam. +- The table costs time in `plot()` (see timings), most of it in the + rounds of a loop. + +Contact sheets and GIFs: scratch `round5fix/sheet_*.png`, `anim_*.gif`. + +## LSL discovery failure in full-suite runs + +2026-11-23. `tests/test_lsl_streaming.py::test_lsl_stream_name_takes_precedence_over_type` +failed in two full-suite runs ("no LSL stream found (name='HypertoolsTestStreamB-...')", +at 5 s with four more tests of the file, then alone at 30 s). The machine crashed +at about 17:45 during this work; everything below marked "after the restart" was +measured again on the fresh boot, the rest could not be repeated. + +What was established: + +- Why that test: liblsl's unicast discovery query (127.0.0.1:16571) reaches only + the oldest socket bound to the port, so only one outlet on the machine can be + found that way. The test's second outlet is the one case in the file that needs + a multicast query to arrive. (Unicast to the oldest socket only: plain sockets, + 10 of 10 against 0 of 10.) +- A race in liblsl 1.17.7 on macOS 26 (after the restart too): the resolver sends + each multicast query on loopback and then switches the same socket to en0 + (`resolve_attempt_udp::send_next_query`); a loopback datagram followed at once + by that switch is lost (plain sockets: 0 of 30 with no delay, 30 of 30 with + 1 ms, 30 of 30 without the switch), and nothing sent on en0 is looped back (0 + of 30). Per 20 query waves 18 / 8 / 4 delivered the 224.0.0.1 / 224.0.0.183 / + 239.255.172.215 datagram. After the restart, default configuration: the second + of two outlets found at once in 8 of 12 resolves, after 0.5, 0.5, 1.0, 2.5 s in + the rest. This alone costs seconds, not 30 s. +- Before the restart the kernel dropped loopback UDP for minutes at a time, on any + port: a fresh socket got 0 of 20 datagrams; "dropped due to full socket buffers" + (`netstat -s -p udp`) +3,096 in 10 s (1,006,018 at 16:42, 1,699,882 at 17:39); + `netstat -m` 360,106 KB allocated to network, 94.7% in use, 2,034 requests + denied, 41,615 mbufs of ancillary data; the `com.apple.content-filter` kernel + control socket's receive queue full (523,880 of 524,288 bytes; Malwarebytes and + GlobalProtect network extensions are installed). In milder phases only multicast + to sockets already on 16571 stopped, 16 to 143 s after resolvers started and + until they ended. After the restart: 21,559 KB, 2.8% in use, unicast 20 of 20. + A 30 s failure needs this state; the race does not produce one. +- NOT established: what filled the network buffers (the content filter's queue is + the lead, unproven), whether that state existed at 12:53 and 15:20 when the two + suite runs failed (the drop counter was already 1,006,018 at 16:42), and whether + this work's own experiments (long resolvers, two LSL test runs at once, a + 400-process CPU burner for 75 s) made it worse or contributed to the crash. + Do not repeat them on a loaded machine. +- Ruled out: leaked outlets or sockets in the pytest process (liblsl leaks 3 file + descriptors per outlet, a kqueue and a pipe pair, no sockets); port-range + exhaustion (26 of 33 UDP ports busy with two resolvers, none leaked); order + dependence (test_io_audit_final.py through test_lsl_streaming.py, 23 files in + one process: all passed); a stalled pusher thread; a member leaving a multicast + group silencing the others; an undrained full socket silencing the others. +- Corrected along the way: 14 to 15 s durations of the two-outlet tests before the + restart were outlet destruction (7 s per outlet then; a pair took 5.8 to 14 s + after the restart in a bare script), not lost discovery. + +What changed: + +- `tests/lsl_loopback.cfg` (`[lab] KnownPeers = {127.0.0.1}`): liblsl also sends + each query straight to every port of its range, where each outlet has its own + socket. `tests/conftest.py` points `LSLAPICFG` at it on macOS only, unless the + caller set one. Before the restart, same outlets, same minutes: default + resolver 13 of 13 misses, two KnownPeers resolvers 138 of 138 and 154 of 154 + found. After the restart: second outlet within 0.51 s in 12 of 12. It does + nothing while unicast is dropped too (9 of 9 discovery tests failed then). +- New test `test_every_discovery_wave_queries_each_outlet_port_directly` (real + socket on a port of the range, real resolve): 0 queries without the setting, + 7 with. +- Timeouts stay at 30 s (discovery) and 10 s (stall test), as in a11c09e9: with + 5 s restored, 9 discovery tests failed in a degraded phase. The comment that + explained them was rewritten; "Discovery" in the test module's docstring has + the measurements. `tests/test_io_audit_final.py` has one more 30 s; untouched. +- `[multicast] Interfaces = {127.0.0.1}` removes the race (20 of 20 waves) and + was dropped: it did not prevent the multicast outage, and a test that counted + multicast deliveries failed once in nine runs with it in place. + +Library: `hypertools/io/lsl.py` is unchanged and uses liblsl's defaults, so a +user on macOS with two outlets on one machine (or one outlet next to another LSL +program) has the same race: a few query waves, covered by the default +`timeout=10`. The outage is the machine's. A sentence in the LSL tutorial about +`KnownPeers` for same-machine outlets is a candidate; not written (user-facing +advice, for Jeremy to decide). Linux and Windows CI runners do not get the +configuration (`sys.platform == 'darwin'`); the setting is plain unicast to +127.0.0.1 and should be harmless there, which was not tested. + +Verified after the restart (load average 45 to 95): `.venv/bin/ruff check tests +hypertools/io` clean; `pytest tests/test_io_audit_lsl.py tests/test_lsl_streaming.py +tests/test_io_audit_final.py tests/test_notebook_install_gate.py`: 73 passed, 3 +skipped in 114 s; the new test alone with the setting commented out: 1 failed +("assert 0 >= 6"). No full-suite run was made. + +### Checks (after the machine crash of about 17:45; code as in checkpoint d9058dff) + +The machine crashed while the timings were being written up; the +coordinator checkpointed the working tree as d9058dff. Every earlier test +result was lost with the scratch folder, so all runs were made again on +that code (load average 25 to 85): + +- tests/test_review_round5_1_2_1.py: 50 passed (matplotlib 3.10); 50 + passed with matplotlib 3.11.2 (installed into a scratch target folder + and put first on `PYTHONPATH`; the earlier `mpl311` venv was lost). +- tests/test_review_round1_1_2_1.py + round2: 311 passed, 1 skipped. +- round3 + round4 + tests/test_issue297_layout.py + + tests/test_issue299_animation_arguments.py: 297 passed. +- The 71 other files named label/legend/hue/panel/caption/title/animat/ + docstring/gate/signature/changelog (not the LSL files): 2661 passed, 8 + skipped, 0 failed. (Before the crash one time bound failed once in + tests/plot/test_forecast_animated_regrouped.py, the slow-forecast notice + at load 180, and its file passed on a rerun, 15 passed.) +- `ruff check .`: clean. The whole suite was not run (the coordinator + runs it). + +Contact sheets and GIFs were made again after the crash: +`/round5fix/sheet_{spin30_legend_title_caption,spin12_axis_labels,window2d,panels2x2}.png` +and `anim_*.gif` of the same names; all four sheets were looked at. + +### Round 5, second pass: every label planned over the whole animation (2026-11-23 evening) + +Coordinator feedback on the first table: labels overlapped EACH OTHER in +most sampled frames (the table kept labels still at the price of leaving +them stacked, "allowed up to 1.5 s"). The frame-by-frame hysteresis solver +(`avoid`, `resting`, `ahead`, loop rounds, `_settle_short_stays`) is gone; +`_arrange_labels` is again only the static rule (plus `strict`). + +What `solve_label_tracks` does now (matplotlib_backend.py): + +- Each label gets a PLAN for all frames: the cheapest path + (`_cheapest_places`, exact dynamic programming over place and frames + spent there) through 72 places (`_LABEL_TRACK_CANDIDATES`: 16 directions, + reaches 20 to 130 pt). Costs: off canvas / on static content / on the + cube's turning axis labels 1e7 a frame (with the static 3 pt clearance); + on another label's DRAWN box 1e3 a frame (1 pt clearance); far out + 0.4 per usual distance per second; pointing into the cloud 1.0 per + second; a change of place 3 + 0.5 per usual distance, none longer than + 240 pt. At least `_LABEL_REST_EASES` (3) glides at a place: that is what + gives 0 turn-backs. Glide 0.35 s (5 frames at 15 fps). +- Labels in the given order; then a glide that crosses something bars that + change on the frames it would cross (`_bar`) and the label is planned + again (`_LABEL_TRACK_REPLANS` 4 at 30 labels, up to 12 with fewer, 1 + above 120); then up to 3 rounds in which labels still not clear, and the + labels they lie on, are planned again among ALL others (1 round above 40 + labels, none above 80). The effort limits are in the docstring. +- A glide that would still cross static content or the canvas edge becomes + a jump, made as early as the place left stops being clear. +- A loop is planned round the loop (three rounds, then once more pinned in + the middle of the longest stay). +- The other animated axes of the figure that are planned already count as + labels to keep off (`tracks['boxes']`): grid panels. + +Tried and dropped: a shorter rest for covered labels (lazy barring of +reversals, or accepting a short-rest plan with no measured turn-back): next +to no gain on 30 labels for 2 to 3 times the time, and turn-backs when it +was used to get off static content. + +Measured (matplotlib 3.10; full table in the scratch `pairs_per_frame.txt`), +overlapping pairs per frame, mean / max / frames with a pair of 60: + +| case | still rule per frame | table of 66c33a32 | now | +|-|-|-|-| +| spin, 8 labels | 0 / 0 / 0 | 0.67 / 3 / 30 | 0 / 0 / 0 | +| spin, 12 labels, dressed | 0 / 0 / 0 | 0.55 / 4 / 20 | 0 / 0 / 0 | +| spin, 30 labels, dressed | 5.58 / 10 / 60 | 10.88 / 20 / 60 | 0.75 / 3 / 30 | +| window, 3-D | 0.05 / 2 / 2 | 0.68 / 3 / 28 | 0 / 0 / 0 | +| 2 x 2 panels, 12 each | 0 / 0 / 0 | 2.88 / 7 / 55 | 0.07 / 1 / 4 | + +Turn-backs now 0 in all five (still rule: 29, 46, 164, 59, 251). With +matplotlib 3.11 (wider text) 30 labels give 1.5 / 4 / 45 and the grid +0.2 / 2 / 11; 8 and 12 labels stay at 0. + +plot() CPU seconds, 200 points, 3-D spin, 60 frames, labels 0/20/60/200: +0.01 / 0.41 / 1.46 / 2.42 (table of 66c33a32, same run: 0.01 / 0.53 / 2.29 +/ 5.33; placed once, a11c09e9: 0.008 / 0.054 / 0.138 / 0.481). The test +spins cost more than the benchmark at equal count because their labels are +crowded: 30 labels 1.8 to 2.2 s (1.56 before), the grid 2.7 s (2.6). + +Not achieved: with 30 labels on a default cube a pair still overlaps on +half the frames (some at rest: no place stays clear for a second in a cube +that turns in four), and leader lines are long (mean offset about 118 pt +against 77 for the still rule) and many cross the cube. The outward +preference only breaks ties; what keeps a label still for a second is a far +place. + +Tests (tests/test_review_round5_1_2_1.py, now 58): added +`test_no_two_labels_overlap_on_any_frame` (5 cases, all labels of the +figure together), `test_a_grids_labels_overlap_on_few_frames`, +`test_thirty_labels_overlap_less_than_stills_of_each_frame`; the +turn-back test runs on all 7 animations; `PASSING` is now the two cases in +which labels do change place (30 labels, grid); the 30-label share against +the usual place is 0.25 (was 0.6). + +### Round 5, third pass: four defects from a source review of the planner (2026-11-23 night) + +Head 185202a1 passed the full suite and was pushed by the coordinator. A +source-only review reported four defects; all four REPRODUCED with real +code (scratch `round5fix3/repro.py`) before anything was changed, and the +8 tests written for them fail against 185202a1. + +| item | reproduced | fix | +|-|-|-| +| 1 memory and time | 400 labels x 600 frames: 13.9 MB table (58 B a label and frame); 60 labels x 600 frames: 94.7 CPU s | above 300 labels (now counted in total, not per frame) no frame is run and the table has one row (11 kB); otherwise at most `_LABEL_TRACK_BUDGET` = 3600 labels x frames are planned (evenly spaced frames, at least 40, `tracks['frames']`), frames between are interpolated in `_apply_label_tracks`; table float32/int16, 28 B a label and planned frame | +| 2 leak | closed animated figures never freed (`_LABEL_STATES` value held the frame function); also the last static labeled figure (module global `labels_and_points`) | state holds the frame function weakly (`weakref.ref` / `WeakMethod`); the animation owns it (`line_ani._hyp_label_frames`); the global now holds weak proxies (tests/test_plotly_labels.py and test_plot_save_audit_fixes.py read it, so it stays) | +| 3 pickle | `pickle.loads(pickle.dumps(anim.figure)).canvas.draw()` and `copy.deepcopy` raised TypeError | `_label_planned`: a planned label with no plan stays where the frame had it (not arranged, not sent home) | +| 4 stale plan | `fig.text` on a label, `set_fontsize`, `set_text`: no re-plan | signature also has every label's size and pad and the obstacle boxes (0.27 ms a frame); re-plan once; a figure changing every frame is planned at the first two changes and once when it stops | + +Planning time, 60 labels (all 60 points labeled, crowded), CPU s: 60 frames +8.5, 600 frames 10.2 (was 94.7), 3000 frames 10.3; 12 labels x 3000 frames +8.6. Edge inputs (no labels, one label, None entries, one and two frames, +NaN point, panels with unequal counts, two saves) did not raise before +either; they now have tests. Known limit: with planned frames far apart (a +long animation with many labels) a glide lasts at least 5 planned frames, +so it is slower than 0.35 s, and labels are only checked on planned frames. + +## Round 5, fourth pass: matplotlib 3.11 failures on CI (2026-11-23) + +CI on 185202a1 failed on every Python 3.11+ job (matplotlib 3.11); 3.10 jobs +passed. Reproduced locally with `PYTHONPATH=/mpl311site` +(matplotlib 3.11.2). Both failures are older than round 5 (they fail the same +way on a11c09e9 under 3.11). + +- `test_issue297_layout.py::test_animated_cube_stays_off_a_corner_legend` + `[upper left]`, `[upper right]`: matplotlib 3.11 gives a line of text its + font's full line height (Noto Sans 8 pt: 15.1 px a line against 11.0 under + 3.10), so the ten-entry legend is 210 px tall, not 169. The cube needs 0.62 + (left) and 0.61 (right) of its size to clear it, and the floor + `_LEGEND_CLEAR_CUBE_SHARE` was 0.7: the cube stopped at 0.7 and was drawn + under the legend on 8 of 36 frames. Floor lowered to 0.55. A legend inside + the axes moves with the axes, so moving the cube instead was not an option. + `test_cube_is_not_shrunk_without_limit_for_a_huge_legend` asserted the + floor's value (0.7): now 0.55. CHANGELOG says 55%. OWNER DECISION to + confirm: the floor's value. +- `test_review_round2_1_2_1.py::test_the_arrangement_is_the_same_at_every_dpi_and_in_every_format` + `[2]`, `[3]`: `_label_size_pt` measured a label on its own 100 dpi renderer, + but matplotlib 3.11's `Text.get_window_extent` lays the text out at the + FIGURE's dpi whatever renderer it is given, so during `savefig(dpi=72)` the + size in points differed and so did the arrangement. Now called with + `dpi=_LABEL_METRICS_DPI`. +- Third-pass test bounds loosened for 3.11, now recorded as bounds: + `test_a_label_made_larger_is_planned_for[text]` had its suffix shortened + from `', a longer name'` to `' (b)'`; the long suffix is back as a third + case `[long text]` with the measured bound (at most 1 pair on 1 frame of 60; + 3.10 gives 0, 3.11 gives 1: one glide passes over a resting label). + `test_edge_inputs_are_planned_and_drawn[panels with unequal label counts]` + had no pair bound: now max <= 3 (3.10: max 2 on 5 frames of 30; 3.11: max 3 + on 22 of 30). The library does not reach 0 under 3.11 for either. +- Timing: the "8.5 s for 60 labels" of the third pass was measured with + `tracemalloc` tracing on (the memory script), not a slower planner. One + benchmark, plot() CPU seconds, 3-D spin, 60 frames, 200 points: + + |labels|185202a1|HEAD| + |-|-|-| + |20|0.51|0.50| + |60|1.66|1.77| + |200|2.92|1.77| + |60 points all labeled, 30 fps|1.42|1.47| + |60 points all labeled, 15 fps|1.81|1.82| +- The third pass's CHANGELOG and test docstring carried the traced timings + (95 s on 600 frames, 8.5 s on 60, 10 s after). Measured again without + tracing, 60 points all labeled, 30 fps: 185202a1 1.56 s on 60 frames and + 29.7 s on 600; HEAD 1.58 s on 60, 2.26 s on 600, 2.37 s on 3000. Both + corrected. + +## 1.2.1 streaming labels (owner decision 2026-11-23) + +The owner's words on text in animations: "for axis labels, they should +move with the rotations so they remain aligned with the axes. same for +labels of individual datapoints (e.g., in every frame the labels should +have correct positioning). for static text like legends, titles, and other +annotations: compute placement once based on the *worst case* rotations of +the axes, and then place once so that the static text (and other static +content) remains stable across frames." And: "slight shifts between frames +are OK but not if they are wobbling back and forth so that it looks +glitchy. movement needs to be in a consistent direction". Asked "What +about streaming animations?" and offered options, the owner chose: add +streaming labels to 1.2.1. + +Built on `post-1.2.0` (from 00abdca2), matplotlib, 2-D and 3-D. + +- API. A stream has no known length, so `labels=` is a callable + `labels(index, sample)` or any iterable consumed in step with the + samples (list, tuple, array, Series, iterator, generator; None after it + runs out). None, NaN or a blank string is no label. A bare string or a + non-iterable raises `TypeError` before a sample is consumed. + `label_alpha=` is forwarded too. `fig.stream_info['labels']` keeps the + label of every consumed sample. The stream code has NO channel of its + own for labels: `row_to_vector` drops the non-numeric fields of a dict + sample. Nothing was invented; the callable gets the sample as yielded, + so `labels=lambda i, row: row['title']` covers it. +- Where. `hypertools/io/streaming.py`: `_stream_label_source`, and + `plot_stream` adds labels in the head and in `_consume` and calls + `tracker.step(first shown index)` in `_redraw`, once per emitted frame, + before the frame is grabbed. `hypertools/plot/matplotlib_backend.py`: + `StreamLabels` (state per label: place, place last left and when, shown + offset, glide, held-until). Placement is `_arrange_labels`, the one + rule, with three optional arguments that only a stream passes: `held` + (labels not looked at: gliding, resting, or stuck with no clear place), + `barred` (the place last left is taken only when nothing else is clear) + and `fresh` (a label not drawn yet takes its usual place only with + `_LABEL_CLEARANCE_PT` round it). Stream labels are drawn through + `_set_label_offset`, so `declutter_labels` at draw time treats them as + planned and only points 3-D anchors at the camera of the draw. Nothing + is stepped by a draw. +- Constants: glide 0.4 s of updates (at least 3), rest 3 glides + (`_LABEL_REST_EASES`), no return for 6 glides, at most 300 visible + labels arranged (`_STREAM_LABEL_MAX`, the oldest; one warning). +- Item 3 findings. The display box and the axis limits are FROZEN from + the first `stream_init` samples (`to_box`); later samples outside it are + drawn clamped to its surface, and a label is attached to that drawn + position. The view never changes by itself, so in a plain stream no + label that is shown ever moves: the only events are a label entering + (at a free place) and leaving (with the window). Labels do move when + the figure is resized or the camera turned while the stream runs; that + is what the glide, the rest and the no-return rule are for, and the test + turns the camera twice. The 3-D stream cube draws no axis or tick + labels (stream samples have no column names), the title is laid out by + the static `hyp.plot` of the head, and neither is clipped or covered in + the contact sheets on matplotlib 3.10 and 3.11. Nothing in the fit code + needed changing. +- Found on the way and fixed: with `'-o'` the head was drawn as a line + with `markevery=[]` plus a markers-only copy that was never updated, so + streamed samples had no markers and the head's markers stayed forever. + And the streamed line was looked up as the first line of the figure's + first axes, wrong for a caller's `ax=` with other lines. `hold=` on a + stream raises "hold= requires an animated plot" (it is validated before + the stream dispatch); left as it is and pinned by a test. +- Measured (3.10, Agg, this machine). Label step per update, a new label + on every update: 2-D 0.42 / 0.92 / 3.1 ms and 3-D 0.59 / 1.06 / 2.7 ms + median for 10 / 50 / 200 visible labels; 0.13 ms median when most + updates add no label. Twelve labels arriving next to each other: 0 + overlapping pairs on every frame, 0 turn-backs, no label moves (2-D and + 3-D, 3.10 and 3.11). Camera turned twice mid-stream: 4 pairs on the + frame of the second turn, 0 within one glide, 0 turn-backs, largest + step 7.2 pt per frame. Memory over 2000 updates with `stream_window=50` + and every sample labeled: the number of live objects is flat (0 more + annotations after 1000 further updates); traced memory grows about 0.57 + KiB per update more than the unlabeled stream with a different text on + every label, which is matplotlib's own text layout cache filling (it is + bounded at 4096 entries) plus the strings kept in + `stream_info['labels']`. Without a window every label stays: about 10 + KiB per label. +- Not built, by decision: `legend=`, `caption=`, `suptitle=`, + `head_marker=`, `tail_linewidth=`, `trail_alpha=`, `hold=` on streams. +- Tests: `tests/test_stream_labels_1_2_1.py`. + +## 1.2.1 gallery review follow-ups (2026-11-24, on 7a5f997e; not pushed) + +Two points from the 1.2.1 against 1.2.0 gallery comparison +(`~/hypertools-review-1.2.1`). + +- **Market clip: the "Market" legend key was thin.** Library defect, not + the example. `legend_colors=[(label, color), ...]` builds proxy handles + (`matplotlib_backend._legend_proxy_handles`) and every one was a fixed + 2-point solid line (or 8-point marker), whatever `linewidth=`, + `linestyle=`, `marker=`, `markersize=`, `alpha=` or a per-dataset `fmt` + said. Same in 1.2.0 and 1.1.0 (checked on a `v1.2.0` worktree: the new + tests fail there, 18 of 20); the 1.2.0 example hid it by drawing its + own legend (`lw=2` sectors, `lw=3.4` market). The legend hypertools + builds from the drawn artists (`legend=[...]`) was already right in + static, animated and panels plots. +- Fix: with exactly one pair per drawn dataset, each key takes its + dataset's `fmt` and given styling (`legend_entry_styles` -> + `_legend_key_style`). `plot()` pairs them from `kwargs_list` before the + animated drawing pops `linewidth`; a `panels=` grid pairs them from the + grid's own kwargs (`_panel_legend_entry_styles`, handed to each panel + as the internal `_legend_entry_styles`), since a panel sees one + dataset. plotly keys take the line width. Unpaired lists, calls without + per-dataset styling and matrix-hue swatches are drawn as before. The + example is unchanged; its sector keys are now 1.1 points like their + paths, the market key 3.4. +- Looked at: `scratchpad/legendfix/market_mpl310_frame0000.png`, + `..._frame1000.png` and the `mpl311` pair (fixture data). +- NOT done: `docs/tutorials/market_sectors.mp4` (and the gallery clip) + still show the thin key until the tutorial is re-executed + (`scripts/execute_tutorial.py`, a 1200-frame render with live data). + The notebook's source needs no change. +- Found on the way and fixed: an animation passed the format string AND + `linestyle=`/`marker=` to `ax.plot`, so matplotlib warned "redundantly + defined" once per dataset (`_plot_with_fmt` splits the format when a + keyword names the same property; the static path already did). +- **Three static figures differed from 1.2.0 in 2 to 7 pixels** + (`plot_missing_data` 001: 7 px, e.g. (182,205), (371,262); 002: 2 px at + (170,210), (171,210); `plot_multiindex` 001: 6 px, e.g. (271,227), + (193,259); x, y from the top left, one color level each, all on + antialiased edges of the data lines). Cause: be7244a7 (GH #297 cube + fit). `_keep_cube_clear` runs on every static 3-D plot and + `_StaticCubeZoom.draw` called `set_box_aspect(aspect, zoom=1.0)`; + matplotlib rescales the aspect it is given, so it came back one unit in + the last place off. Unintended. `draw` now returns when the zoom is the + one in effect; the three figures are byte-for-byte 1.2.0 again + (rendered from this tree on 3.10 and compared with `/before`: 0 pixels). + Known limit: a cube zoomed out and back to exactly 1.0 would still be + one unit off. +- Tests: `tests/test_legend_key_styles.py` (26), + `tests/test_static_cube_untouched.py` (6); both matplotlib versions. + + +## 1.2.1 streaming legend, caption, suptitle (owner decision 2026-11-24) + +The owner's dialog answer: "Add the three now". `legend=`, `caption=` and +`suptitle=` (with `legend_kwargs=`, `legend_colors=`, `caption_kwargs=`, +`suptitle_kwargs=`) are forwarded by the stream dispatch in +`hypertools/plot/plot.py` to `plot_stream`, which passes them with its +other `plot_kwargs` to the static `hyp.plot` of the head. Nothing else was +needed: the static path lays them out once, the display box is frozen from +`stream_init`, and `_label_obstacles_pt` already keeps stream labels off +legends and figure texts. All three styling arguments came for free. +A callable caption raises `TypeError` in the dispatch (`_dynamic_caption` +set by `_validate_caption`), before a sample is consumed. With `ax=`, +`caption=`/`suptitle=` raise the non-stream `ValueError` (validated before +the dispatch). `head_marker=`, `tail_linewidth=`, `trail_alpha=` still +warn as ignored; `hold=` still raises. Tests: +`tests/test_stream_text_1_2_1.py`. diff --git a/pyproject.toml b/pyproject.toml index a3843ff7..b871f025 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,13 +5,13 @@ build-backend = "setuptools.build_meta" [project] name = "hypertools" -# 1.2.0 is a feature release on the 1.x line: animated panel grids, -# `caption=`, and panel grids that share colors, one legend and one colorbar -# and are sized by the grid (CHANGELOG 1.2.0, "Added" and "Changed"), plus the -# fixes first drafted as a 1.1.1 patch release that was never published. The +# 1.2.1 follows the 1.2.0 feature release (animated panel grids, `caption=`, +# shared colors / one legend / one colorbar in panel grids): it carries the +# animated-trail fix and options of GH #299 and the gallery layout points of +# GH #297 (CHANGELOG 1.2.1). The # version and the top CHANGELOG heading are held equal by # tests/test_release_readiness_gate.py::test_changelog_top_version_matches_pyproject. -version = "1.2.0" +version = "1.2.1" description = "A python package for visualizing and manipulating high-dimensional data" readme = "readme.md" # PEP 639 SPDX expression (the `license = { text = ... }` table form is diff --git a/readme.md b/readme.md index 38b4e9f2..4b9b3b82 100644 --- a/readme.md +++ b/readme.md @@ -1,4 +1,4 @@ -![Hypertools logo](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/hypercube.png) +![Hypertools logo](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.1/images/hypercube.png) [![Tests](https://img.shields.io/github/actions/workflow/status/ContextLab/hypertools/test.yml?label=tests)](https://github.com/ContextLab/hypertools/actions/workflows/test.yml) [![Documentation Status](https://readthedocs.org/projects/hypertools/badge/?version=latest)](https://hypertools.readthedocs.io/en/latest/?badge=latest) @@ -7,7 +7,7 @@ "_To deal with hyper-planes in a 14 dimensional space, visualize a 3D space and say 'fourteen' very loudly. Everyone does it._" - Geoff Hinton -![Hypertools example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/story_trajectories.gif) +![Hypertools example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.1/images/story_trajectories.gif) ## Overview @@ -52,7 +52,7 @@ the link under a clip for the full code and the full-length animation. Six stock-market sectors, each reduced to 3-D on its own and then hyperaligned into a shared space, with a heavier path for the market as a whole. -![Market sectors example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/tour_market_sectors.gif) +![Market sectors example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.1/images/tour_market_sectors.gif) [Tutorial: market sectors](https://hypertools.readthedocs.io/en/latest/tutorials/market_sectors.html) @@ -62,7 +62,7 @@ Give `hyp.plot` a list of strings and it embeds them, projects them into 2-D or 3-D, and plots the result. Here a paragraph about each of five paintings becomes its own cloud, drawn in a color pulled from the canvas itself. -![Painting embeddings example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/tour_painting_embeddings.gif) +![Painting embeddings example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.1/images/tour_painting_embeddings.gif) [Tutorial: painting embeddings](https://hypertools.readthedocs.io/en/latest/tutorials/painting_embeddings.html) @@ -72,7 +72,7 @@ becomes its own cloud, drawn in a color pulled from the canvas itself. Tea-Party from *Alice's Adventures in Wonderland*: each segment is one turn of the conversation, colored by speaker and placed by what is being said. -![Conversation example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/tour_conversation_shape.gif) +![Conversation example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.1/images/tour_conversation_shape.gif) [Tutorial: the shape of a conversation](https://hypertools.readthedocs.io/en/latest/tutorials/conversation_shape.html) @@ -81,7 +81,7 @@ the conversation, colored by speaker and placed by what is being said. Monthly temperatures in 20 cities around the globe, from 1875 to 2013, drawn as a single path and colored by the average temperature that month. -![Weather example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/tour_weather_decades.gif) +![Weather example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.1/images/tour_weather_decades.gif) [Tutorial: weather across the decades](https://hypertools.readthedocs.io/en/latest/tutorials/weather_decades.html) @@ -97,7 +97,7 @@ shapes = [hyp.load(n) for n in names] hyp.plot(shapes, '.', color='k', animate='morph', title=names) ``` -![Morph example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/tour_morph_shapes_zoo.gif) +![Morph example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.1/images/tour_morph_shapes_zoo.gif) [Tutorial: morphing the shapes zoo](https://hypertools.readthedocs.io/en/latest/tutorials/morph_shapes_zoo.html) @@ -256,7 +256,7 @@ list_of_labels = ['A'] * 300 + ['B'] * 300 # one label per observation hyp.plot(list_of_arrays, animate=True, hue=list_of_labels) ``` -![Plot example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/plot.gif) +![Plot example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.1/images/plot.gif) ## Align @@ -275,11 +275,11 @@ hyp.plot(list_of_arrays, align='hyper') ### BEFORE -![Align before example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/align_before.gif) +![Align before example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.1/images/align_before.gif) ### AFTER -![Align after example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/align_after.gif) +![Align after example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.1/images/align_after.gif) ## Cluster @@ -299,7 +299,7 @@ array = np.vstack([rng.standard_normal((100, 3)) + offset hyp.plot(array, 'o', cluster='GaussianMixture', n_clusters=3) ``` -![Cluster Example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/cluster_example.png) +![Cluster Example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.1/images/cluster_example.png) ## Surfaces @@ -317,7 +317,7 @@ blob_b = rng.standard_normal((100, 3)) + [4, 0, 0] hyp.plot([blob_a, blob_b], '.', surface=True) ``` -![Surface Example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/surface_example.png) +![Surface Example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.1/images/surface_example.png) ## Describe @@ -332,4 +332,4 @@ list_of_arrays = [np.cumsum(rng.standard_normal((200, 20)), axis=0) hyp.describe(list_of_arrays, reduce='PCA', max_dims=14) ``` -![Describe Example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/describe_example.png) +![Describe Example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.1/images/describe_example.png) diff --git a/scripts/generate_tutorial_notebook.py b/scripts/generate_tutorial_notebook.py index 33f42189..b6a636dc 100644 --- a/scripts/generate_tutorial_notebook.py +++ b/scripts/generate_tutorial_notebook.py @@ -46,7 +46,7 @@ 'market_sectors': ('animate_market_sectors', 100, [ ('## 1. Imports, a disk cache, and the universe', 'Six sectors of four or five tickers each -- unequal on purpose -- ' - 'with fixed sector colours, the animation length, a whitened PCA so ' + 'with fixed sector colors, the animation length, a whitened PCA so ' "a sector's common growth does not flatten its path onto one line, " 'and the colormap that tints the date red or green.', None), ('## 2. Prices and share counts, with a synthetic fallback', @@ -66,8 +66,8 @@ 'return', 'What is plotted is each stock\'s cumulative log return since the ' 'first month (a growth curve), one matrix per sector. Each sector\'s ' - 'share of the basket\'s capitalisation, month by month, becomes the ' - 'colour weights of the market path, and the cap-weighted trailing ' + 'share of the basket\'s capitalization, month by month, becomes the ' + 'color weights of the market path, and the cap-weighted trailing ' 'twelve-month return tints the title. `load_market` is the real ' 'path; `fixture_data` is the same payload from the seeded basket.', 'assemble'), @@ -75,7 +75,7 @@ 'Three library calls: `hyp.reduce` per sector (its own stocks, its ' 'own space), `hyp.align(..., model=\'HyperAlign\')` into one shared ' 'space, and `hyp.plot` on the six aligned paths plus their mean, ' - 'coloured through the mixture hue. The `on_frame` hook only sets ' + 'colored through the mixture hue. The `on_frame` hook only sets ' 'the title: the date under the head, tinted by the basket\'s ' 'return.', 'construct_artifact'), ]), @@ -102,15 +102,15 @@ 'painting_embeddings': ('animate_painting_embeddings', 100, [ ('## 1. Imports, a disk cache, and the five paintings', 'The descriptions are bundled inline with each painting\'s artist, ' - 'year, Wikimedia file and a hand-picked fallback colour. The ' + 'year, Wikimedia file and a hand-picked fallback color. The ' 'layout constants place the text column and the thumbnails.', None), - ('## 2. Windows, canvases and colours', + ('## 2. Windows, canvases and colors', 'Each description is cut into overlapping ten-word windows. The ' 'canvas is downloaded once (the only network access here) and ' - '`image_palette` picks its most salient legible colour; offline, ' - 'the fallback colour and a flat swatch stand in. `fixture_data` is ' - "the test-suite's path: it takes every colour from a thumbnail " + '`image_palette` picks its most salient legible color; offline, ' + 'the fallback color and a flat swatch stand in. `fixture_data` is ' + "the test-suite's path: it takes every color from a thumbnail " 'committed next to the example script (`examples/data/`, not ' 'shipped with this notebook, so it is not called here) and embeds ' 'with TF-IDF, so no test fetches a canvas or a model.', 'Paintings'), @@ -118,12 +118,12 @@ 'Raw text in, five clouds out, spun by `animate=\'spin\'`. ' 'Everything after the call is annotation of the same figure: the ' 'name with artist and year, the embedded description, and a ' - 'thumbnail centred on it.', 'construct_artifact'), + 'thumbnail centered on it.', 'construct_artifact'), ]), 'conversation_shape': ('animate_conversation', 100, [ ('## 1. Imports, the speakers, and the turns', 'The Mad Tea-Party turns, spoken text only, with each speaker\'s ' - 'colour, the recency-fade constants, the title wrap width and the ' + 'color, the recency-fade constants, the title wrap width and the ' 'tail length.', None), ('## 2. Windows and the payload', 'Each turn becomes a list of sliding word windows; the payload ' @@ -136,10 +136,10 @@ 'hand-written form of `dataset_fade={\'floor\': FLOOR, ' '\'decay\': DECAY}`, which gives exactly these alphas in one ' 'keyword. The title needs no hook: `title_color=` tints each ' - 'turn\'s title with its speaker\'s colour, and the library reserves ' + 'turn\'s title with its speaker\'s color, and the library reserves ' 'the wrapped title\'s margin.', 'turn_alpha'), ('## 4. One call', - 'Raw dialogue in, one disjoint trajectory per turn, coloured by ' + 'Raw dialogue in, one disjoint trajectory per turn, colored by ' 'speaker, revealed one turn at a time over thirty seconds and two ' 'camera rotations.', 'construct_artifact'), ]), @@ -150,7 +150,7 @@ ('## 2. The shapes zoo, sampled and loop-closed, with parametric ' 'stand-ins', '`hyp.load` fetches each shape once into `~/hypertools_data`; the ' - 'clouds are normalised into the unit cube, sampled, and the first ' + 'clouds are normalized into the unit cube, sampled, and the first ' 'is repeated at the end so a looping player never hard-cuts. On a ' 'cold cache with no network, five parametric clouds stand in.', 'Shapes'), diff --git a/tests/conftest.py b/tests/conftest.py index 9d61dd4c..812039cf 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,5 +1,6 @@ """Session-wide test settings.""" import os +import sys # plot(..., backend='plotly', show=True) outside a notebook calls fig.show(), # and plotly's default renderer outside a notebook is the desktop browser: @@ -7,3 +8,13 @@ # (2026-09-11). Keep every run headless unless the caller chose a renderer. # Set before any test module imports plotly, which reads it at import. os.environ.setdefault('PLOTLY_RENDERER', 'json') + +# LSL tests: on macOS, liblsl also sends its discovery queries straight to +# every outlet port on this machine (tests/lsl_loopback.cfg; the reason and +# the measurements are under "Discovery" in the docstring of +# tests/test_lsl_streaming.py). liblsl reads LSLAPICFG once, at its first use +# in the process, so this is set before any test module imports pylsl; a +# caller's own LSLAPICFG is kept. +if sys.platform == 'darwin': + os.environ.setdefault('LSLAPICFG', os.path.join( + os.path.dirname(os.path.abspath(__file__)), 'lsl_loopback.cfg')) diff --git a/tests/lsl_loopback.cfg b/tests/lsl_loopback.cfg new file mode 100644 index 00000000..1a6fc6cd --- /dev/null +++ b/tests/lsl_loopback.cfg @@ -0,0 +1,11 @@ +; liblsl configuration for the test session on macOS (tests/conftest.py points +; LSLAPICFG here unless the caller already set it). Every outlet and resolver +; of the test suite is on this machine; "Discovery" in the docstring of +; tests/test_lsl_streaming.py has the measurements behind the setting. + +; Send each discovery query straight to every port an outlet on this machine +; can listen on (16572 and up), as well as to the shared discovery port 16571, +; so that finding an outlet does not depend on multicast delivery to that +; port. +[lab] +KnownPeers = {127.0.0.1} diff --git a/tests/test_datatype_gate.py b/tests/test_datatype_gate.py index bb5fc38a..4e09cb4d 100644 --- a/tests/test_datatype_gate.py +++ b/tests/test_datatype_gate.py @@ -110,6 +110,9 @@ "animate= per-dataset morph tags given as an array (an option)"), ("isinstance(_lim, (list, tuple, np.ndarray))", "an axis-limit option: a (lo, hi) pair vs None/scalar"), + ("isinstance(value, np.ndarray)", + "a chemtrails=/precog=/bullettime= flag given as an array, " + "unwrapped to a list (as in trails.py)"), ], 'hypertools/plot/trails.py': [ ("isinstance(flag, (list, tuple, np.ndarray))", diff --git a/tests/test_io_audit_final.py b/tests/test_io_audit_final.py index 1815b5e0..43d27d52 100644 --- a/tests/test_io_audit_final.py +++ b/tests/test_io_audit_final.py @@ -439,7 +439,7 @@ def test_lsl_multimatch_warning_admits_best_effort(): outlets = [pylsl.StreamOutlet(i) for i in infos] try: with pytest.warns(RuntimeWarning, match='best-effort'): - stream = hyp.io.lsl_stream(type=stream_type, timeout=5.0, + stream = hyp.io.lsl_stream(type=stream_type, timeout=30.0, minimum=2) stream.close() finally: diff --git a/tests/test_io_audit_lsl.py b/tests/test_io_audit_lsl.py index 2d0a1e06..aa0d7fc0 100644 --- a/tests/test_io_audit_lsl.py +++ b/tests/test_io_audit_lsl.py @@ -40,7 +40,7 @@ def test_string_channel_stream_rejected_at_resolve(): outlet = pylsl.StreamOutlet(info) # real outlet, alive during resolve try: with pytest.raises(HypertoolsIOError, match='string'): - hyp.io.lsl_stream(name=name, timeout=5.0) + hyp.io.lsl_stream(name=name, timeout=30.0) finally: del outlet @@ -60,7 +60,7 @@ def test_multiple_matching_streams_warn(): outlets = [pylsl.StreamOutlet(i) for i in infos] try: with pytest.warns(RuntimeWarning, match='using the first'): - stream = hyp.io.lsl_stream(type=stream_type, timeout=5.0, + stream = hyp.io.lsl_stream(type=stream_type, timeout=30.0, minimum=2) stream.close() finally: @@ -77,7 +77,7 @@ def test_single_matching_stream_does_not_warn(): try: with _warnings.catch_warnings(record=True) as caught: _warnings.simplefilter('always') - stream = hyp.io.lsl_stream(name=name, timeout=5.0) + stream = hyp.io.lsl_stream(name=name, timeout=30.0) stream.close() assert not [w for w in caught if 'using the first' in str(w.message)] finally: diff --git a/tests/test_issue297_layout.py b/tests/test_issue297_layout.py new file mode 100644 index 00000000..449db172 --- /dev/null +++ b/tests/test_issue297_layout.py @@ -0,0 +1,505 @@ +"""GH #297: layout points found in the gallery figures. + +A. A single animated 3-D plot's cube stays inside the canvas at every + camera angle. On a square figure it reached (and passed) the left and + right canvas edges when seen corner-on. +B. ...and stays off a legend placed in a corner of its axes + (``legend_kwargs={'loc': 'upper left'}``), static or animated. +C. Observation labels (``labels=``) are not drawn on top of each other. +D. An animated markers-only plot with a continuous ``hue=`` is revealed + frame by frame like every other animation. It drew every observation + on every frame. + +Real figures and real frames, rendered headless. Nothing is mocked. No +assertion depends on a font's absolute metrics: boxes are measured where +they were drawn and compared with each other and with the canvas. +""" +import matplotlib +matplotlib.use('Agg') + +import matplotlib.pyplot as plt # noqa: E402 +import numpy as np # noqa: E402 +import pytest # noqa: E402 + +import hypertools as hyp # noqa: E402 + + +def _walk(seed, rows=60, cols=3): + return np.random.default_rng(seed).normal(size=(rows, cols)).cumsum(0) + + +X = _walk(0) +DATA = [_walk(seed) for seed in range(5)] + + +@pytest.fixture(autouse=True) +def _close_figures(): + yield + plt.close('all') + + +def _ink(fig): + """Boolean image (row 0 at the TOP) of the pixels `fig` draws on.""" + fig.canvas.draw() + rgba = np.asarray(fig.canvas.buffer_rgba()) + return (rgba[..., :3] < 250).any(axis=-1) + + +def _ink_margins(fig): + """(left, right, bottom, top) blank margins around what is drawn, px.""" + ink = _ink(fig) + cols = np.flatnonzero(ink.any(axis=0)) + rows = np.flatnonzero(ink.any(axis=1)) + height, width = ink.shape + return (cols[0], width - 1 - cols[-1], height - 1 - rows[-1], rows[0]) + + +def _box_px(artist, fig): + return artist.get_window_extent(fig.canvas.get_renderer()) + + +# -------------------------------------------------------------------------- +# A. the cube and the canvas edge +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('size', [(8, 8), (5, 8), (6, 6)]) +def test_animated_cube_stays_inside_a_square_or_portrait_canvas(size): + anim = hyp.plot(X, '-', animate=True, duration=3, frame_rate=12, + size=size, elev=16, show=False) + fig = anim.figure + width = fig.bbox.width + least = np.inf + for frame in range(anim.n_frames): + anim.draw_frame(frame) + left, right, _bottom, _top = _ink_margins(fig) + least = min(least, left, right) + # the cube keeps a visible margin (2% of the canvas is asked for; the + # frame's line width and the frame sampling take a little of it) + assert least >= 0.01 * width, ( + f'the cube comes within {least} px of the side of a ' + f'{width:.0f} px canvas') + + +def test_default_landscape_animation_is_not_zoomed_out(): + """The cube already clears a landscape canvas: nothing changes.""" + anim = hyp.plot(X, '-', animate=True, duration=2, frame_rate=10, + show=False) + assert anim.animation._hyp_zoom_scale == [1.0] + + +def test_cube_fills_the_width_it_is_given(): + """The fit takes no more than it needs: at its widest view the cube + reaches to within the margin of one side of the canvas.""" + anim = hyp.plot(X, '-', animate=True, duration=3, frame_rate=12, + size=(8, 8), show=False) + fig = anim.figure + least = np.inf + for frame in range(anim.n_frames): + anim.draw_frame(frame) + least = min(least, *_ink_margins(fig)[:2]) + assert least <= 0.035 * fig.bbox.width + + +def test_an_explicit_zoom_in_is_honored(): + """`zoom=` above 1 asks for a closer view: the cube is not shrunk + back to the canvas.""" + anim = hyp.plot(X, '-', animate=True, duration=2, frame_rate=10, + size=(8, 8), zoom=3, show=False) + assert anim.animation._hyp_zoom_scale == [1.0] + + +def test_cube_fit_does_not_run_the_users_hook(): + """Fitting the cube draws frame 0 through the updater alone.""" + calls = [] + anim = hyp.plot(X, '-', animate=True, duration=2, frame_rate=10, + size=(8, 8), on_frame=lambda ctx: calls.append(ctx.frame), + show=False) + assert calls == [] + anim.draw_frame(3) + assert calls == [3] + + +# -------------------------------------------------------------------------- +# B. the cube and a legend inside the axes +# -------------------------------------------------------------------------- + +def _legend_area_ink(fig, legend): + """How many pixels are drawn where `legend` goes, with the legend + itself hidden: the cube or the data reaching under it.""" + box = _box_px(legend, fig) + legend.set_visible(False) + try: + ink = _ink(fig) + finally: + legend.set_visible(True) + height = ink.shape[0] + rows = slice(max(0, int(height - box.y1)), int(np.ceil(height - box.y0))) + cols = slice(max(0, int(box.x0)), int(np.ceil(box.x1))) + return int(ink[rows, cols].sum()) + + +#: ten entries: tall enough, in a corner of an 8 x 8 in figure, to reach +#: the cube as it was drawn (measured: the cube has to come down to about +#: three quarters of its size to clear it) +KEYED = [_walk(seed) for seed in range(10)] +LEGEND = [f'A rather long name for dataset {i}' for i in range(len(KEYED))] + + +@pytest.mark.parametrize('loc', ['upper left', 'upper right', 'lower left']) +def test_animated_cube_stays_off_a_corner_legend(loc): + anim = hyp.plot(KEYED, '-', animate=True, duration=3, frame_rate=12, + size=(8, 8), legend=LEGEND, + legend_kwargs={'loc': loc, 'fontsize': 8}, show=False) + fig = anim.figure + legend = fig.axes[0].get_legend() + assert legend is not None + for frame in range(anim.n_frames): + anim.draw_frame(frame) + assert _legend_area_ink(fig, legend) == 0, ( + f'frame {frame}: the cube is drawn under the {loc} legend') + # the legend, not the canvas edge, is what set the cube's size here + edge_only = hyp.plot(KEYED, '-', animate=True, duration=3, frame_rate=12, + size=(8, 8), show=False) + assert (anim.animation._hyp_zoom_scale[0] + < 0.95 * edge_only.animation._hyp_zoom_scale[0]) + + +def test_animated_cube_stays_off_the_default_legend(): + """The default legend sits right of the plot, where the cube's right + corner reached into its box at the widest view.""" + anim = hyp.plot(DATA, '-', animate=True, duration=3, frame_rate=12, + legend=LEGEND[:len(DATA)], show=False) + fig = anim.figure + legend = fig.axes[0].get_legend() + for frame in range(anim.n_frames): + anim.draw_frame(frame) + assert _legend_area_ink(fig, legend) == 0, f'frame {frame}' + # the legend is still whole, on the canvas + box = _box_px(legend, fig) + assert box.x0 >= 0 and box.x1 <= fig.bbox.width + + +def test_animated_cube_stays_off_its_colorbar(): + anim = hyp.plot(X, '-', hue=np.arange(len(X)), colorbar=True, + animate=True, duration=3, frame_rate=12, show=False) + fig = anim.figure + plot_ax, bar_ax = fig.axes + bar = bar_ax.get_position() + edge = bar.x0 * fig.bbox.width + bar_ax.set_visible(False) + for frame in range(anim.n_frames): + anim.draw_frame(frame) + ink = _ink(fig) + columns = np.flatnonzero(ink.any(axis=0)) + assert columns[-1] < edge, f'frame {frame}' + + +def test_cube_is_not_shrunk_without_limit_for_a_huge_legend(): + """A legend that would leave the cube under 55% of its size is not + cleared: the cube stays at that share. (70% until review round 5: + under matplotlib 3.11's taller lines the ten-entry legend of + `test_animated_cube_stays_off_a_corner_legend` needs 61%.)""" + data = [_walk(seed) for seed in range(24)] + anim = hyp.plot(data, '-', animate=True, duration=2, frame_rate=10, + size=(8, 8), legend=[f'A long name for dataset {i}' + for i in range(len(data))], + legend_kwargs={'loc': 'upper left', 'fontsize': 8}, + show=False) + assert anim.animation._hyp_zoom_scale[0] == pytest.approx(0.55, abs=0.01) + + +def test_static_cube_stays_off_a_corner_legend(): + fig = hyp.plot(DATA, '-', size=(5, 5), legend=LEGEND[:len(DATA)], + legend_kwargs={'loc': 'upper left', 'fontsize': 8}, + show=False) + legend = fig.axes[0].get_legend() + assert _legend_area_ink(fig, legend) == 0 + + +def test_static_plot_without_a_corner_legend_keeps_its_cube(): + """The default (outside, right) legend and no legend at all leave a + static cube at matplotlib's own size.""" + plain = hyp.plot(DATA, '-', show=False) + keyed = hyp.plot(KEYED, '-', legend=LEGEND, show=False) + reference = plt.figure().add_subplot(projection='3d').get_box_aspect() + for fig in (plain, keyed): + np.testing.assert_allclose(fig.axes[0].get_box_aspect(), reference) + + +# -------------------------------------------------------------------------- +# C. observation labels +# -------------------------------------------------------------------------- + +def _label_boxes(fig): + """Display boxes (round frame included) of the visible labels.""" + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + return [text.get_bbox_patch().get_window_extent(renderer) + for ax in fig.axes for text in ax.texts + if text.get_visible() and text.get_text() + and text.get_bbox_patch() is not None] + + +def _overlapping_pairs(boxes): + return [(i, j) for i in range(len(boxes)) for j in range(i + 1, len(boxes)) + if boxes[i].overlaps(boxes[j])] + + +def _crowded(n=4, cols=3): + """`n` datasets whose FIRST rows nearly coincide: their labels, all + hung on the same side, land on each other.""" + out = [] + for seed in range(n): + walk = _walk(seed, rows=30, cols=cols) + out.append(walk - walk[0] + 0.02 * seed) + return out + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_labels_of_neighboring_points_do_not_overlap(ndims): + names = ['Subject 0', 'Subject 1', 'Subject 2', 'Subject 3'] + fig = hyp.plot(_crowded(), '.', labels=names, ndims=ndims, show=False) + boxes = _label_boxes(fig) + assert len(boxes) == len(names) + assert _overlapping_pairs(boxes) == [] + # ...and every one of them is still on the canvas + for box in boxes: + assert box.x0 >= 0 and box.y0 >= 0 + assert box.x1 <= fig.bbox.width and box.y1 <= fig.bbox.height + + +def test_labels_that_are_clear_of_each_other_stay_where_they_were(): + """A label that covers no other keeps its place up and to the left + of its point, so such a figure is drawn as it always was.""" + apart = [np.array([[-1.0, -1.0, -1.0], [0.0, 0.0, 0.0]]), + np.array([[1.0, 1.0, 1.0], [0.0, 0.1, 0.0]])] + fig = hyp.plot(apart, '.', labels=['low', 'high'], show=False) + fig.canvas.draw() + labels = [t for t in fig.axes[0].texts if t.get_text()] + assert len(labels) == 2 + for label in labels: + assert tuple(label.xyann) == (-20.0, 20.0) + assert label.get_ha() == 'right' and label.get_va() == 'bottom' + + +def test_first_label_keeps_its_place_and_later_ones_move(): + fig = hyp.plot(_crowded(), '.', labels=['a' * 9, 'b' * 9, 'c' * 9, + 'd' * 9], show=False) + fig.canvas.draw() + labels = [t for t in fig.axes[0].texts if t.get_text()] + assert tuple(labels[0].xyann) == (-20.0, 20.0) + assert any(tuple(label.xyann) != (-20.0, 20.0) for label in labels[1:]) + + +def test_label_placement_is_the_same_on_every_draw(): + fig = hyp.plot(_crowded(), '.', labels=list('abcd'), show=False) + first = [tuple(np.round(box.extents, 3)) for box in _label_boxes(fig)] + again = [tuple(np.round(box.extents, 3)) for box in _label_boxes(fig)] + assert first == again + + +def test_labels_are_placed_for_the_layout_the_figure_ends_up_with(): + """The placement is made at draw time: resizing the figure after the + call (which moves the points, not the labels' offsets) still leaves + the labels clear of each other.""" + fig = hyp.plot(_crowded(), '.', labels=['Subject 0', 'Subject 1', + 'Subject 2', 'Subject 3'], + show=False) + fig.set_size_inches(3.5, 3.0) + assert _overlapping_pairs(_label_boxes(fig)) == [] + + +def test_a_label_the_reader_moved_is_left_alone(): + fig = hyp.plot(_crowded(cols=2), '.', labels=list('abcd'), ndims=2, + show=False) + fig.canvas.draw() + label = [t for t in fig.axes[0].texts if t.get_text()][1] + label.xyann = (55.0, -35.0) # what a drag does + fig.canvas.draw() + fig.canvas.draw() + assert tuple(label.xyann) == (55.0, -35.0) + + +def test_animated_labels_do_not_overlap_on_any_frame(): + data = _crowded(3) + anim = hyp.plot(data, '-', labels=['first', 'second', 'third'], + animate='spin', duration=2, frame_rate=10, show=False) + fig = anim.figure + seen = 0 + for frame in range(anim.n_frames): + anim.draw_frame(frame) + boxes = _label_boxes(fig) + seen = max(seen, len(boxes)) + assert _overlapping_pairs(boxes) == [], f'frame {frame}' + assert seen == 3 + + +def test_an_animation_frame_places_its_labels_the_same_whenever_drawn(): + """Frames are idempotent: the placement depends on the frame alone, + not on the frames drawn before it.""" + anim = hyp.plot(_crowded(3), '-', labels=['first', 'second', 'third'], + animate='spin', duration=2, frame_rate=10, show=False) + fig = anim.figure + + def boxes(frame): + anim.draw_frame(frame) + return [tuple(np.round(b.extents, 2)) for b in _label_boxes(fig)] + + forward = boxes(5) + boxes(15) + boxes(0) + assert boxes(5) == forward + + +# -------------------------------------------------------------------------- +# D. animated markers with a continuous hue +# -------------------------------------------------------------------------- + +HUE = np.linspace(0.0, 1.0, len(X)) + + +def _scatters(ax): + """The per-point-colored scatters of the data (not the cube frame).""" + from matplotlib.collections import PathCollection + return [c for c in ax.collections if isinstance(c, PathCollection)] + + +def _offsets(coll, ndims): + if ndims == 3: + return np.column_stack([np.asarray(v) for v in coll._offsets3d]) + return np.asarray(coll.get_offsets()) + + +def _static_points_and_colors(ndims): + """Where a STATIC plot of the same call puts each observation, and + the color it gives it.""" + fig = hyp.plot(X, 'o', hue=HUE, ndims=ndims, show=False) + (coll,) = _scatters(fig.axes[0]) + # the colors depend on hue= alone; they are read off the 2-D scatter, + # which keeps them in row order (a 3-D one sorts them by depth) + flat = hyp.plot(X, 'o', hue=HUE, ndims=2, show=False) + (flat_coll,) = _scatters(flat.axes[0]) + colors = np.asarray(flat_coll.get_facecolors()) + assert len(colors) == len(X) + return _offsets(coll, ndims), colors + + +def _drawn_colors(coll, fig): + """The RGB rows `coll` is drawn with, sorted (a 3-D scatter hands its + colors back in depth order, as of its last draw).""" + fig.canvas.draw() + colors = np.round(np.asarray(coll.get_facecolors())[:, :3], 9) + return colors[np.lexsort(colors.T)] + + +def _sorted_rows(colors): + colors = np.round(np.asarray(colors)[:, :3], 9) + return colors[np.lexsort(colors.T)] + + +def _rows_of(points, reference): + """Which rows of `reference` the rows of `points` are.""" + rows = [] + for point in points: + distance = np.abs(reference - point).sum(axis=1) + assert distance.min() < 1e-9 + rows.append(int(distance.argmin())) + return rows + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_animated_marker_hue_is_revealed_frame_by_frame(ndims): + reference, colors = _static_points_and_colors(ndims) + anim = hyp.plot(X, 'o', hue=HUE, ndims=ndims, animate=True, duration=3, + frame_rate=10, show=False) + plain = hyp.plot(X, 'o', ndims=ndims, animate=True, duration=3, + frame_rate=10, show=False) + ax = anim.figure.axes[0] + (head,) = _scatters(ax) + shown = [] + for frame in (0, anim.n_frames // 2, anim.n_frames - 1): + anim.draw_frame(frame) + plain.draw_frame(frame) + assert head.get_visible() + rows = _rows_of(_offsets(head, ndims), reference) + # the window of the same animation without hue= + line = plain.figure.axes[0].lines[0] + expected = len(line.get_data_3d()[0] if ndims == 3 + else line.get_xdata()) + assert len(rows) == expected + # consecutive observations, each in its own color + assert rows == list(range(rows[0], rows[0] + len(rows))) + np.testing.assert_allclose(_drawn_colors(head, anim.figure), + _sorted_rows(colors[rows]), atol=1e-8) + shown.append(rows) + assert shown[0] != shown[1] != shown[2] + assert len(shown[0]) < len(X) + + +def test_animated_marker_hue_frames_differ_in_2d(): + """Every frame of the 2-D animation was the same picture.""" + anim = hyp.plot(X, 'o', hue=HUE, ndims=2, animate=True, duration=3, + frame_rate=10, show=False) + fig = anim.figure + pictures = [] + for frame in (0, anim.n_frames // 2, anim.n_frames - 1): + anim.draw_frame(frame) + pictures.append(_ink(fig).copy()) + assert (pictures[0] != pictures[1]).any() + assert (pictures[1] != pictures[2]).any() + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_animated_marker_hue_draws_its_chemtrail(ndims): + reference, colors = _static_points_and_colors(ndims) + anim = hyp.plot(X, 'o', hue=HUE, ndims=ndims, animate=True, duration=3, + frame_rate=10, chemtrails=True, tail_duration=0.5, + trail_alpha=0.4, show=False) + ax = anim.figure.axes[0] + head, trail = _scatters(ax) + assert trail._hyp_trace_role == 'trail' + anim.draw_frame(anim.n_frames - 1) + assert head.get_visible() and trail.get_visible() + head_rows = _rows_of(_offsets(head, ndims), reference) + trail_rows = _rows_of(_offsets(trail, ndims), reference) + # the trail holds what the head has left behind, from the first row + assert trail_rows[0] == 0 + assert len(trail_rows) > len(head_rows) + assert head_rows[-1] == len(X) - 1 + assert trail.get_alpha() == pytest.approx(0.4) + np.testing.assert_allclose(_drawn_colors(trail, anim.figure), + _sorted_rows(colors[trail_rows]), atol=1e-8) + + +def test_animated_marker_hue_keeps_its_colorbar_and_marker(): + anim = hyp.plot(X, 's', hue=HUE, ndims=2, animate=True, duration=2, + frame_rate=10, markersize=9, colorbar=True, show=False) + fig = anim.figure + assert len(fig.axes) == 2 # the plot and its colorbar + (head,) = _scatters(fig.axes[0]) + anim.draw_frame(anim.n_frames - 1) + np.testing.assert_allclose(head.get_sizes(), [81.0]) + square = matplotlib.markers.MarkerStyle('s') + np.testing.assert_allclose( + head.get_paths()[0].vertices, + square.get_path().transformed(square.get_transform()).vertices) + + +def test_spinning_marker_hue_still_shows_every_observation(): + """'spin' moves the camera only: all the points, on every frame.""" + anim = hyp.plot(X, 'o', hue=HUE, animate='spin', duration=2, + frame_rate=10, show=False) + (coll,) = _scatters(anim.figure.axes[0]) + for frame in (0, anim.n_frames - 1): + anim.draw_frame(frame) + assert len(_offsets(coll, 3)) == len(X) + + +def test_on_frame_receives_the_drawn_marker_scatter(): + seen = [] + anim = hyp.plot(X, 'o', hue=HUE, ndims=2, animate=True, duration=2, + frame_rate=10, show=False, + on_frame=lambda ctx: seen.append(list(ctx.artists))) + anim.draw_frame(4) + (head,) = _scatters(anim.figure.axes[0]) + assert seen and seen[-1][0] is head diff --git a/tests/test_issue299_animation_arguments.py b/tests/test_issue299_animation_arguments.py new file mode 100644 index 00000000..edfdf6b7 --- /dev/null +++ b/tests/test_issue299_animation_arguments.py @@ -0,0 +1,968 @@ +"""GH #299: trails for line+marker formats, and the animation arguments +that came with it. + +A. ``hyp.plot(x, '-o', animate=True, chemtrails=True)`` drew no chemtrail: + the trail artists were only created for a PURE line format. Every + format now gets its trail, drawn as its head is. +B. ``head_marker=``, ``tail_linewidth=``, ``trail_alpha=``, ``hold=``, + ``caption_kwargs=`` and ``suptitle=``/``suptitle_kwargs=``. + +Real figures and real frames, rendered headless; saved files are read +back. Nothing is mocked, and no assertion depends on a font's absolute +metrics: text is measured where it was drawn and compared with what is +around it. +""" +import shutil +import subprocess +import warnings + +import matplotlib +matplotlib.use('Agg') + +import matplotlib.pyplot as plt +import numpy as np +import pytest +from matplotlib.colors import to_rgba +from PIL import Image + +import hypertools as hyp +from hypertools.plot.plot import CAPTION_GID, SUPTITLE_GID + +HAS_FFMPEG = (shutil.which('ffmpeg') is not None + and shutil.which('ffprobe') is not None) + + +def _walk(seed, rows=60, cols=3): + return np.random.default_rng(seed).normal(size=(rows, cols)).cumsum(0) + + +X = _walk(0) +DATA = [_walk(seed) for seed in range(4)] +ANIM = dict(animate=True, tail_duration=0.5, duration=2, frame_rate=10, + show=False) + + +@pytest.fixture(autouse=True) +def _close_figures(): + yield + plt.close('all') + + +def _plot(data=None, fmt='-', **kwargs): + call = dict(ANIM) + call.update(kwargs) + return hyp.plot(X if data is None else data, fmt, **call) + + +def _lines(anim, axes=0): + return list(anim.figure.axes[axes].lines) + + +def _trails(anim, axes=0): + """The trail artists of one axes: the lines drawn below full alpha + that are not head markers.""" + return [line for line in _lines(anim, axes) + if line.get_alpha() is not None + and getattr(line, '_hyp_trace_role', None) != 'head_marker'] + + +def _heads(anim, axes=0): + return [line for line in _lines(anim, axes) + if line.get_alpha() is None + and getattr(line, '_hyp_trace_role', None) != 'head_marker'] + + +def _head_markers(anim, axes=0): + return [line for line in _lines(anim, axes) + if getattr(line, '_hyp_trace_role', None) == 'head_marker'] + + +def _n_vertices(line): + return len(line.get_xdata()) + + +def _rendered(fig): + fig.canvas.draw() + return np.asarray(fig.canvas.buffer_rgba()).copy() + + +def _extent(fig, artist): + """`artist`'s drawn box in FIGURE fractions, from a real draw.""" + fig.canvas.draw() + box = artist.get_window_extent(fig.canvas.get_renderer()) + return box.transformed(fig.transFigure.inverted()) + + +def _figure_text(fig, gid): + found = fig.findobj(lambda a: a.get_gid() == gid) + assert len(found) == 1, f'{len(found)} texts with gid {gid!r}' + return found[0] + + +def _content_top(fig, skip=()): + """The highest point (figure fraction) of everything drawn except the + texts in `skip`.""" + hidden = [(artist, artist.get_visible()) for artist in skip] + for artist, _ in hidden: + artist.set_visible(False) + try: + fig.canvas.draw() + box = fig.get_tightbbox(fig.canvas.get_renderer()) + return box.y1 / fig.get_size_inches()[1] + finally: + for artist, visible in hidden: + artist.set_visible(visible) + + +def _content_bottom(fig, skip=()): + hidden = [(artist, artist.get_visible()) for artist in skip] + for artist, _ in hidden: + artist.set_visible(False) + try: + fig.canvas.draw() + box = fig.get_tightbbox(fig.canvas.get_renderer()) + return box.y0 / fig.get_size_inches()[1] + finally: + for artist, visible in hidden: + artist.set_visible(visible) + + +# --------------------------------------------------------------------------- +# A. the bug: a line+marker format gets its trail +# --------------------------------------------------------------------------- + +LINE_MARKER_FORMATS = ['-o', 'o-', '.-', '--s', ':^', '-.d'] + + +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('fmt', LINE_MARKER_FORMATS) +def test_line_marker_format_draws_its_chemtrail(fmt, ndims): + reference = _plot(fmt='-', chemtrails=True, ndims=ndims).draw_frame(15) + anim = _plot(fmt=fmt, chemtrails=True, ndims=ndims).draw_frame(15) + (head,), (trail,) = _heads(anim), _trails(anim) + (ref_head,), (ref_trail,) = _heads(reference), _trails(reference) + # the trail is the head's own format, faded + assert trail.get_linestyle() == head.get_linestyle() != 'None' + assert trail.get_marker() == head.get_marker() != 'None' + assert trail.get_alpha() == pytest.approx(0.3) + assert to_rgba(trail.get_color()) == to_rgba(head.get_color()) + # ...over exactly the rows the pure line's trail covers + assert _n_vertices(trail) == _n_vertices(ref_trail) > 2 + assert _n_vertices(head) == _n_vertices(ref_head) + np.testing.assert_allclose(trail.get_xdata(), ref_trail.get_xdata()) + # its markers sit on observations, as the head's do: far fewer than + # the smoothed curve has vertices + assert 0 < len(trail.get_markevery()) < _n_vertices(trail) / 2 + assert trail.get_label().startswith('_') # no legend entry + + +@pytest.mark.parametrize('flag', ['precog', 'bullettime']) +def test_line_marker_format_draws_precog_and_bullettime(flag): + reference = _plot(fmt='-', **{flag: True}).draw_frame(8) + anim = _plot(fmt='-o', **{flag: True}).draw_frame(8) + (trail,), (ref_trail,) = _trails(anim), _trails(reference) + assert trail.get_marker() == 'o' and trail.get_linestyle() == '-' + assert _n_vertices(trail) == _n_vertices(ref_trail) > 2 + + +def test_issue_snippet_reports_two_artists_for_both_formats(): + """The issue's own reproduction.""" + seen = {} + for fmt in ('-', '-o'): + anim = _plot(fmt=fmt, chemtrails=True).draw_frame(15) + seen[fmt] = [(line.get_linestyle(), line.get_marker(), + line.get_alpha()) for line in _lines(anim)] + assert seen['-'] == [('-', 'None', None), ('-', 'None', 0.3)] + assert seen['-o'] == [('-', 'o', None), ('-', 'o', 0.3)] + + +def test_per_dataset_formats_each_get_their_trail(): + anim = _plot(DATA[:3], fmt=['-o', '-', 'o'], chemtrails=True, + ndims=2).draw_frame(15) + trails = _trails(anim) + assert [(t.get_linestyle(), t.get_marker()) for t in trails] == [ + ('-', 'o'), ('-', 'None'), ('None', 'o')] + assert all(_n_vertices(t) > 2 for t in trails) + + +def test_per_dataset_flags_only_trail_the_flagged_dataset(): + anim = _plot(DATA[:2], fmt='-o', chemtrails=[False, True]).draw_frame(15) + (trail,) = _trails(anim) + assert to_rgba(trail.get_color()) == to_rgba(_heads(anim)[1].get_color()) + + +def test_markers_only_format_draws_a_trail_of_faded_markers(): + """A markers-only trail is its faded markers, as the plotly backend + draws it -- on its own, not only beside a pure line dataset -- so no + trail flag is ever dropped without a word.""" + with warnings.catch_warnings(): + warnings.simplefilter('error') + anim = _plot(fmt='o', chemtrails=True).draw_frame(15) + (head,), (trail,) = _heads(anim), _trails(anim) + assert trail.get_linestyle() == 'None' and trail.get_marker() == 'o' + assert trail.get_alpha() == pytest.approx(0.3) + # raw rows: the past the head window has left behind + assert _n_vertices(trail) > _n_vertices(head) > 0 + + +def test_line_marker_trail_reaches_the_pixels(): + """What the figure shows: the frame with the chemtrail has ink where + the frame without one has none, in the dataset's color, faded.""" + plain = _plot(fmt='-o', ndims=2, markersize=4).draw_frame(15) + trailed = _plot(fmt='-o', ndims=2, markersize=4, + chemtrails=True).draw_frame(15) + a, b = _rendered(plain.figure), _rendered(trailed.figure) + assert a.shape == b.shape + changed = np.abs(a[..., :3].astype(int) - b[..., :3].astype(int)).max(-1) > 8 + assert changed.sum() > 200 + # the added ink is paler than the head's own color (alpha 0.3 on white) + head_rgb = np.array(to_rgba(_heads(trailed)[0].get_color())[:3]) * 255 + added = b[changed][:, :3].astype(float) + assert added.mean() > head_rgb.mean() + 20 + + +def test_serial_reveal_trails_a_line_marker_format(): + anim = _plot(DATA[:2], fmt='-o', animate='serial', + chemtrails=True).draw_frame(5) + trails = _trails(anim) + assert len(trails) == 2 + # the dataset being revealed traces its past; the other has not begun + assert _n_vertices(trails[0]) > 2 and _n_vertices(trails[1]) == 0 + + +def test_hue_colored_line_marker_format_gets_a_trail_collection(): + anim = _plot(fmt='-o', chemtrails=True, hue=np.arange(len(X)), + ndims=2).draw_frame(15) + roles = {} + for coll in anim.figure.axes[0].collections: + role = getattr(coll, '_hyp_trace_role', None) + if role is not None: + roles[role] = coll + assert set(roles) == {'head', 'trail'} + assert len(roles['trail'].get_segments()) > 2 + assert roles['trail'].get_alpha() == pytest.approx(0.3) + + +def test_animated_panel_grid_trails_a_line_marker_format(): + anim = hyp.plot(DATA, '-o', panels=(2, 2), chemtrails=True, **ANIM) + anim.draw_frame(15) + for index in range(4): + (trail,) = _trails(anim, index) + assert trail.get_marker() == 'o' and trail.get_linestyle() == '-' + assert _n_vertices(trail) > 2 + + +@pytest.mark.parametrize('fmt', ['-o', 'o-', '--s', 'o']) +def test_plotly_backend_trails_every_format(fmt): + fig = _plot(fmt=fmt, chemtrails=True, backend='plotly') + frame = fig.frames[15] + head, trail = frame.data + assert len(trail.x) > len(head.x) > 0 + # the trail trace itself: the head's mode, at 0.3 opacity + trace = fig.data[frame.traces[1]] + assert trace.mode == fig.data[frame.traces[0]].mode + assert trace.opacity == pytest.approx(0.3) + + +# --------------------------------------------------------------------------- +# B1. head_marker= +# --------------------------------------------------------------------------- + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_head_marker_sits_on_the_reveal_head_every_frame(ndims): + anim = _plot(DATA[:2], chemtrails=True, head_marker='o', ndims=ndims) + for frame in (0, 7, 19): + anim.draw_frame(frame) + heads, markers = _heads(anim), _head_markers(anim) + assert len(markers) == 2 + for head, marker in zip(heads, markers): + assert marker.get_linestyle() == 'None' + assert marker.get_marker() == 'o' + assert _n_vertices(marker) == 1 + assert marker.get_xdata()[0] == pytest.approx(head.get_xdata()[-1]) + assert marker.get_ydata()[0] == pytest.approx(head.get_ydata()[-1]) + if ndims == 3: + assert marker.get_data_3d()[2][0] == pytest.approx( + head.get_data_3d()[2][-1]) + # the dataset's color, and never a legend entry + assert to_rgba(marker.get_color()) == to_rgba(head.get_color()) + assert marker.get_label().startswith('_') + + +def test_head_marker_true_is_a_circle_and_none_draws_nothing(): + assert _head_markers(_plot(head_marker=True))[0].get_marker() == 'o' + assert _head_markers(_plot(head_marker=None)) == [] + assert _head_markers(_plot(head_marker=False)) == [] + assert _head_markers(_plot()) == [] + + +def test_head_marker_dict_styles_it(): + anim = _plot(ndims=2, head_marker={'marker': 'D', 'size': 13, + 'color': 'k', 'edgecolor': 'w', + 'edgewidth': 2}).draw_frame(10) + (marker,) = _head_markers(anim) + assert marker.get_marker() == 'D' + assert marker.get_markersize() == 13 + assert to_rgba(marker.get_color()) == to_rgba('k') + assert to_rgba(marker.get_markeredgecolor()) == to_rgba('w') + assert marker.get_markeredgewidth() == 2 + + +def test_head_marker_size_follows_the_dataset_and_the_tail_width(): + default = _head_markers(_plot(head_marker='o'))[0].get_markersize() + assert default == pytest.approx(plt.rcParams['lines.markersize']) + sized = _head_markers(_plot(head_marker='o', markersize=11))[0] + assert sized.get_markersize() == 11 + # never lost under a thick tail + thick = _head_markers(_plot(head_marker='o', tail_linewidth=8))[0] + assert thick.get_markersize() >= 2 * 8 + + +def test_head_marker_reaches_the_pixels(): + """A black diamond at the reveal head: black ink at the head's own + pixel, where the same frame without the marker has none.""" + kwargs = dict(ndims=2, linewidth=1) + plain = _plot(**kwargs).draw_frame(10) + marked = _plot(head_marker={'marker': 'D', 'size': 14, 'color': 'k'}, + **kwargs).draw_frame(10) + head = _heads(marked)[0] + ax = marked.figure.axes[0] + image = _rendered(marked.figure) + px, py = ax.transData.transform( + (head.get_xdata()[-1], head.get_ydata()[-1])) + row, col = int(round(image.shape[0] - py)), int(round(px)) + assert image[row, col, :3].max() < 60 # black + assert _rendered(plain.figure)[row, col, :3].max() > 60 + + +def test_head_marker_follows_the_hue_color_at_the_head(): + hue = np.arange(len(X)) + anim = _plot(hue=hue, head_marker='o', ndims=2) + colors = [] + for frame in (2, 18): + anim.draw_frame(frame) + colors.append(to_rgba(_head_markers(anim)[0].get_color())) + assert colors[0] != colors[1] + pinned = _plot(hue=hue, ndims=2, head_marker={'color': 'k'}) + pinned.draw_frame(18) + assert to_rgba(_head_markers(pinned)[0].get_color()) == to_rgba('k') + + +def test_head_marker_in_a_serial_reveal(): + anim = _plot(DATA[:2], animate='serial', head_marker='o').draw_frame(4) + first, second = _head_markers(anim) + assert _n_vertices(first) == 1 # being revealed + assert _n_vertices(second) == 0 # not started: nothing to mark + + +def test_head_marker_in_an_animated_panel_grid(): + anim = hyp.plot(DATA, '-', panels=(2, 2), head_marker='*', **ANIM) + anim.draw_frame(9) + for index in range(4): + (marker,) = _head_markers(anim, index) + (head,) = _heads(anim, index) + assert marker.get_marker() == '*' + assert marker.get_xdata()[0] == pytest.approx(head.get_xdata()[-1]) + + +@pytest.mark.parametrize('bad', ['not-a-marker', {'marker': 'o', 'colour': 'k'}, + {'marker': 'None'}, '']) +def test_head_marker_refuses_what_it_cannot_draw(bad): + with pytest.raises(ValueError, match='head_marker'): + _plot(head_marker=bad) + + +@pytest.mark.parametrize('style', ['spin', 'morph']) +def test_head_marker_says_so_where_there_is_no_reveal_head(style): + with pytest.warns(UserWarning, match='head_marker'): + anim = hyp.plot(DATA[:2], 'o' if style == 'morph' else '-', + animate=style, duration=2, frame_rate=10, + show=False, head_marker='o') + assert _head_markers(anim) == [] + + +def test_animation_styling_says_so_on_a_static_plot(): + with pytest.warns(UserWarning, + match='head_marker/tail_linewidth/trail_alpha only ' + 'affect ANIMATED plots'): + fig = hyp.plot(X, '-', show=False, head_marker='o', + tail_linewidth=3, trail_alpha=0.5) + assert len(fig.axes[0].lines) == 1 + + +# --------------------------------------------------------------------------- +# B2. tail_linewidth= +# --------------------------------------------------------------------------- + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_tail_linewidth_thickens_the_tail_not_the_trail(ndims): + anim = _plot(chemtrails=True, linewidth=1.5, tail_linewidth=5, + ndims=ndims).draw_frame(15) + (head,), (trail,) = _heads(anim), _trails(anim) + assert head.get_linewidth() == 5 + assert trail.get_linewidth() == 1.5 + + +def test_tail_linewidth_default_leaves_both_at_linewidth(): + anim = _plot(chemtrails=True, linewidth=2.5).draw_frame(15) + assert _heads(anim)[0].get_linewidth() == 2.5 + assert _trails(anim)[0].get_linewidth() == 2.5 + + +def test_tail_linewidth_reaches_the_pixels(): + thin = _plot(ndims=2, chemtrails=True, linewidth=1).draw_frame(15) + thick = _plot(ndims=2, chemtrails=True, linewidth=1, + tail_linewidth=7).draw_frame(15) + + def ink(anim): + image = _rendered(anim.figure) + return int((image[..., :3].min(-1) < 200).sum()) + assert ink(thick) > 1.5 * ink(thin) + + +def test_tail_linewidth_in_a_serial_reveal_is_the_comet_head_only(): + anim = _plot(DATA[:2], animate='serial', chemtrails=True, linewidth=1, + tail_linewidth=6) + anim.draw_frame(4) # dataset 0 is being revealed + assert _heads(anim)[0].get_linewidth() == 6 + anim.draw_frame(19) # both finished: drawn in full + assert [h.get_linewidth() for h in _heads(anim)] == [1, 1] + + +def test_tail_linewidth_with_a_continuous_hue(): + anim = _plot(hue=np.arange(len(X)), chemtrails=True, linewidth=1.5, + tail_linewidth=6, ndims=2).draw_frame(15) + widths = {getattr(c, '_hyp_trace_role', None): c.get_linewidth()[0] + for c in anim.figure.axes[0].collections} + assert widths['head'] == 6 and widths['trail'] == 1.5 + + +@pytest.mark.parametrize('bad', [0, -1, 'thick', True, float('nan')]) +def test_tail_linewidth_must_be_a_positive_number(bad): + with pytest.raises(ValueError, match='tail_linewidth'): + _plot(tail_linewidth=bad) + + +# --------------------------------------------------------------------------- +# B3. trail_alpha= +# --------------------------------------------------------------------------- + +@pytest.mark.parametrize('flag', ['chemtrails', 'precog', 'bullettime']) +def test_trail_alpha_sets_the_trail_opacity(flag): + anim = _plot(trail_alpha=0.65, **{flag: True}).draw_frame(8) + assert _trails(anim)[0].get_alpha() == pytest.approx(0.65) + + +def test_trail_alpha_multiplies_the_dataset_alpha(): + anim = _plot(chemtrails=True, alpha=0.5, trail_alpha=0.8).draw_frame(8) + trail = [line for line in _lines(anim) + if line.get_alpha() == pytest.approx(0.4)] + assert len(trail) == 1 + default = _plot(chemtrails=True, alpha=0.5).draw_frame(8) + assert any(line.get_alpha() == pytest.approx(0.15) + for line in _lines(default)) + + +def test_trail_alpha_with_a_continuous_hue(): + anim = _plot(hue=np.arange(len(X)), chemtrails=True, trail_alpha=0.7, + ndims=2).draw_frame(15) + (trail,) = [c for c in anim.figure.axes[0].collections + if getattr(c, '_hyp_trace_role', None) == 'trail'] + assert trail.get_alpha() == pytest.approx(0.7) + + +def test_trail_alpha_reaches_the_pixels(): + def ink(alpha): + anim = _plot(ndims=2, chemtrails=True, linewidth=3, + trail_alpha=alpha, color='k').draw_frame(19) + image = _rendered(anim.figure)[..., :3].astype(int).max(-1) + # (black pixels, pixels of black at 20% on white) + return int((image < 60).sum()), int((abs(image - 204) < 12).sum()) + opaque, faint = ink(1.0), ink(0.2) + # an opaque trail is black where the faint one is light gray + assert opaque[0] > faint[0] + 1500 + assert faint[1] > opaque[1] + 1500 + + +def test_trail_alpha_on_plotly(): + fig = _plot(chemtrails=True, trail_alpha=0.65, backend='plotly') + trace = fig.data[fig.frames[8].traces[1]] + assert trace.opacity == pytest.approx(0.65) + default = _plot(chemtrails=True, backend='plotly') + assert default.data[default.frames[8].traces[1]].opacity == \ + pytest.approx(0.3) + + +@pytest.mark.parametrize('bad', [-0.1, 1.5, 'faint', True]) +def test_trail_alpha_must_be_between_0_and_1(bad): + with pytest.raises(ValueError, match='trail_alpha'): + _plot(chemtrails=True, trail_alpha=bad) + + +def test_trail_alpha_says_so_without_a_trail(): + with pytest.warns(UserWarning, match='trail_alpha'): + _plot(trail_alpha=0.5) + + +# --------------------------------------------------------------------------- +# B4. hold= +# --------------------------------------------------------------------------- + +def test_hold_appends_frames_that_repeat_the_last_one(): + plain = _plot(chemtrails=True) + held = _plot(chemtrails=True, hold=1.5) + assert plain.n_frames == 20 + assert held.n_frames == 20 + 15 + last = _rendered(held.draw_frame(19).figure) + for frame in (20, 27, 34): + assert np.array_equal(_rendered(held.draw_frame(frame).figure), last) + with pytest.raises(IndexError): + held.draw_frame(35) + + +def test_hold_zero_is_the_animation_it_always_was(): + assert _plot(hold=0).n_frames == _plot().n_frames == 20 + # a hold shorter than half a frame rounds to no frames + assert _plot(hold=0.04).n_frames == 20 + + +def test_hold_keeps_the_frame_context_on_the_last_frame(tmp_path): + """Per-frame texts and callbacks see the LAST index during the hold: + read from a real save, which is what drives every frame.""" + seen = [] + anim = _plot(ndims=2, hold=0.5, + title=lambda ctx: f'title {ctx.frame}', + caption=lambda ctx: f'caption {ctx.frame} {ctx.progress}', + on_frame=lambda ctx: seen.append( + (ctx.frame, ctx.n_frames, ctx.progress))) + anim.save(str(tmp_path / 'held.gif')) + drawn = [entry for entry in seen] + assert len(drawn) >= 25 + assert drawn[-5:] == [(19, 20, 1.0)] * 5 + assert drawn[-6] == (19, 20, 1.0) and drawn[-7][0] == 18 + assert anim.figure.axes[0].get_title() == 'title 19' + assert _figure_text(anim.figure, CAPTION_GID).get_text() == \ + 'caption 19 1.0' + + +def test_hold_is_in_the_saved_gif(tmp_path): + def playback(path): + with Image.open(path) as im: + total = 0 + for index in range(getattr(im, 'n_frames', 1)): + im.seek(index) + total += im.info.get('duration', 0) + return total / 1000.0 + plain, held = str(tmp_path / 'plain.gif'), str(tmp_path / 'held.gif') + _plot(ndims=2, save_path=plain) + _plot(ndims=2, save_path=held, hold=1.5) + assert playback(plain) == pytest.approx(2.0, abs=0.15) + assert playback(held) == pytest.approx(3.5, abs=0.15) + + +def _video_frames(path): + out = subprocess.run( + ['ffprobe', '-v', 'error', '-select_streams', 'v:0', + '-count_frames', '-show_entries', 'stream=nb_read_frames', + '-of', 'csv=p=0', str(path)], + capture_output=True, text=True, check=True) + return int(out.stdout.strip().split(',')[0]) + + +@pytest.mark.skipif(not HAS_FFMPEG, reason='ffmpeg/ffprobe not installed') +def test_hold_is_in_the_saved_mp4(tmp_path): + plain, held = tmp_path / 'plain.mp4', tmp_path / 'held.mp4' + _plot(save_path=str(plain), rotations=1) + _plot(save_path=str(held), rotations=1, hold=1) + assert _video_frames(plain) == 20 + assert _video_frames(held) == 30 + + +def test_hold_stops_the_camera_with_rotations(): + anim = _plot(rotations=2, hold=1) + ax = anim.figure.axes[0] + anim.draw_frame(19) + last = ax.azim + anim.draw_frame(25) + assert ax.azim == pytest.approx(last) + anim.draw_frame(10) + assert ax.azim != pytest.approx(last) + + +def test_hold_adds_to_duration_at_the_frame_rate(): + anim = hyp.plot(X, '-', animate=True, duration=3, frame_rate=8, + hold=2, show=False) + assert anim.n_frames == 3 * 8 + 2 * 8 + + +def test_hold_composes_with_a_looping_morph(): + clouds = [np.random.default_rng(s).normal(size=(40, 3)) for s in range(3)] + call = dict(animate='morph', loop=True, duration=2, frame_rate=10, + show=False) + plain = hyp.plot(clouds, 'o', **call) + held = hyp.plot(clouds, 'o', hold=1, **call) + assert held.n_frames == plain.n_frames + 10 + assert held.n_segments == plain.n_segments + last = _rendered(held.draw_frame(plain.n_frames - 1).figure) + assert np.array_equal( + _rendered(held.draw_frame(held.n_frames - 1).figure), last) + + +@pytest.mark.parametrize('style', ['spin', 'serial', 'window']) +def test_hold_on_every_style(style): + anim = hyp.plot(DATA[:2], '-', animate=style, duration=2, frame_rate=10, + hold=0.5, show=False) + assert anim.n_frames == 25 + anim.draw_frame(24) + + +def test_hold_inside_the_animate_dict(): + anim = hyp.plot(X, '-', show=False, animate={ + 'style': 'parallel', 'duration': 2, 'frame_rate': 10, 'hold': 1, + 'head_marker': 'o', 'tail_linewidth': 3, 'chemtrails': True, + 'trail_alpha': 0.5}) + assert anim.n_frames == 30 + anim.draw_frame(29) + assert len(_head_markers(anim)) == 1 + assert _heads(anim)[0].get_linewidth() == 3 + assert _trails(anim)[0].get_alpha() == pytest.approx(0.5) + + +def test_hold_on_an_animated_panel_grid(tmp_path): + seen = [] + anim = hyp.plot(DATA, '-', panels=(2, 2), hold=0.5, + caption=lambda ctx: f'frame {ctx.frame + 1}', + on_frame=lambda ctx: seen.append(ctx.frame), **ANIM) + assert anim.n_frames == 25 + anim.save(str(tmp_path / 'grid.gif')) + assert seen[-6:] == [19] * 6 + assert _figure_text(anim.figure, CAPTION_GID).get_text() == 'frame 20' + + +def test_hold_drawn_extent_and_sampling_still_work(): + anim = _plot(hold=1, title=lambda ctx: f'frame {ctx.frame}', + caption=lambda ctx: f'frame {ctx.frame}') + box = anim.drawn_extent(frames=[0, 29]) + assert 0 <= box.x0 < box.x1 <= 1 + + +@pytest.mark.parametrize('bad', [-1, 'long', True, float('inf')]) +def test_hold_must_be_seconds(bad): + with pytest.raises(ValueError, match='hold'): + _plot(hold=bad) + + +def test_hold_requires_an_animation(): + with pytest.raises(ValueError, match='hold= requires an animated plot'): + hyp.plot(X, '-', show=False, hold=1) + with pytest.raises(ValueError, match='hold= requires an animated plot'): + hyp.plot(DATA, '-', panels=(2, 2), show=False, hold=1) + + +@pytest.mark.parametrize('kwargs', [dict(head_marker='o'), + dict(tail_linewidth=3), dict(hold=1)]) +def test_frame_driven_arguments_are_refused_on_plotly(kwargs): + (name,) = kwargs + with pytest.raises(NotImplementedError, + match=f'{name}= is matplotlib-only'): + _plot(backend='plotly', **kwargs) + + +# --------------------------------------------------------------------------- +# B5. caption_kwargs= +# --------------------------------------------------------------------------- + +def _inside_canvas(box, slack=1e-6): + return (box.x0 >= -slack and box.x1 <= 1 + slack + and box.y0 >= -slack and box.y1 <= 1 + slack) + + +CAPTION = 'a caption for the whole figure' + + +@pytest.mark.parametrize('size', [6, 12, 28, 44]) +@pytest.mark.parametrize('animated', [False, True]) +def test_caption_of_any_size_is_measured_into_the_canvas(size, animated): + call = dict(caption=CAPTION, caption_kwargs={'size': size}, show=False) + if animated: + call.update(animate=True, duration=1, frame_rate=8) + result = hyp.plot(X, '-', **call) + fig = result.figure if animated else result + caption = _figure_text(fig, CAPTION_GID) + assert caption.get_fontsize() == size + box = _extent(fig, caption) + assert _inside_canvas(box) + # below everything else the figure draws + assert box.y1 <= _content_bottom(fig, skip=[caption]) + 1e-6 + + +def test_larger_caption_gets_more_room(): + heights = [] + for size in (8, 30): + fig = hyp.plot(X, '-', animate=True, duration=1, frame_rate=8, + show=False, caption=CAPTION, + caption_kwargs={'size': size}).figure + heights.append(fig.get_size_inches()[1]) + assert heights[1] > heights[0] + + +def test_caption_style_is_applied(): + fig = hyp.plot(X, '-', show=False, caption=CAPTION, caption_kwargs={ + 'color': 'crimson', 'weight': 'bold', 'style': 'italic', + 'alpha': 0.5, 'family': 'monospace'}) + caption = _figure_text(fig, CAPTION_GID) + assert to_rgba(caption.get_color()) == to_rgba('crimson') + assert caption.get_fontweight() == 'bold' + assert caption.get_fontstyle() == 'italic' + assert caption.get_alpha() == 0.5 + assert caption.get_fontfamily() == ['monospace'] + + +@pytest.mark.parametrize('animated', [False, True]) +def test_caption_at_the_top_sits_above_everything(animated): + call = dict(title='the axes title', caption=CAPTION, show=False, + caption_kwargs={'position': 'top', 'size': 20}) + if animated: + call.update(animate=True, duration=1, frame_rate=8) + result = hyp.plot(X, '-', **call) + fig = result.figure if animated else result + caption = _figure_text(fig, CAPTION_GID) + box = _extent(fig, caption) + assert _inside_canvas(box) + assert box.y0 >= _content_top(fig, skip=[caption]) - 1e-6 + title = _extent(fig, fig.axes[0].title) + assert box.y0 >= title.y1 + + +def test_caption_alignment(): + boxes = {} + for loc in ('left', 'center', 'right'): + fig = hyp.plot(X, '-', show=False, caption='short', + caption_kwargs={'loc': loc}) + boxes[loc] = _extent(fig, _figure_text(fig, CAPTION_GID)) + assert _inside_canvas(boxes[loc]) + assert boxes['left'].x0 < 0.05 and boxes['left'].x1 < 0.5 + assert boxes['right'].x1 > 0.95 and boxes['right'].x0 > 0.5 + assert (boxes['center'].x0 + boxes['center'].x1) / 2 == \ + pytest.approx(0.5, abs=0.01) + + +def test_long_styled_caption_wraps_inside_the_canvas(): + fig = hyp.plot(X, '-', show=False, caption='word ' * 60, + caption_kwargs={'size': 22, 'loc': 'left'}) + caption = _figure_text(fig, CAPTION_GID) + assert caption.get_text().count('\n') >= 2 + assert _inside_canvas(_extent(fig, caption)) + + +def test_per_frame_caption_at_the_top_of_an_animation(): + anim = hyp.plot(X, '-', animate=True, duration=1, frame_rate=8, + show=False, title=lambda ctx: f'title {ctx.frame}', + caption=lambda ctx: f'caption {ctx.frame}', + caption_kwargs={'position': 'top', 'size': 18}) + caption = _figure_text(anim.figure, CAPTION_GID) + for frame in (0, 4, 7): + anim.draw_frame(frame) + assert caption.get_text() == f'caption {frame}' + box = _extent(anim.figure, caption) + assert _inside_canvas(box) + assert box.y0 >= _extent(anim.figure, anim.figure.axes[0].title).y1 + + +@pytest.mark.parametrize('bad, error', [ + ({'colour': 'red'}, ValueError), + ({'position': 'middle'}, ValueError), + ({'loc': 'top'}, ValueError), + ('big', TypeError), +]) +def test_caption_kwargs_are_validated(bad, error): + with pytest.raises(error, match='caption_kwargs'): + hyp.plot(X, '-', show=False, caption=CAPTION, caption_kwargs=bad) + + +def test_caption_kwargs_without_a_caption_are_refused(): + with pytest.raises(ValueError, match='no caption= was given'): + hyp.plot(X, '-', show=False, caption_kwargs={'size': 12}) + with pytest.raises(ValueError, match='no caption= was given'): + hyp.plot(DATA, '-', panels=(2, 2), show=False, + caption_kwargs={'size': 12}) + + +# --------------------------------------------------------------------------- +# B6. suptitle=: a figure-level title +# --------------------------------------------------------------------------- + +PANEL_TITLES = ['one', 'two', 'three', 'four'] +SUPTITLE = 'Four walks, one figure' + + +def _grid(animated, **kwargs): + call = dict(panels=(2, 2), title=PANEL_TITLES, show=False, + legend=['a', 'b', 'c', 'd'], suptitle=SUPTITLE) + if animated: + call.update(animate=True, duration=1, frame_rate=8, chemtrails=True) + call.update(kwargs) + result = hyp.plot(DATA, '-', **call) + return result, (result.figure if animated else result) + + +def test_single_string_title_still_names_every_panel(): + """`title=` on a grid is per panel (documented), which is why the + figure-level title is its own argument.""" + fig = hyp.plot(DATA, '-', panels=(2, 2), title='same', show=False) + assert [ax.get_title() for ax in fig.axes[:4]] == ['same'] * 4 + assert fig.findobj(lambda a: a.get_gid() == SUPTITLE_GID) == [] + + +@pytest.mark.parametrize('animated', [False, True]) +@pytest.mark.parametrize('style', [None, {'size': 30, 'color': 'navy'}]) +def test_grid_suptitle_is_above_everything_and_inside_the_canvas( + animated, style): + result, fig = _grid(animated, suptitle_kwargs=style) + suptitle = _figure_text(fig, SUPTITLE_GID) + assert suptitle.get_text() == SUPTITLE + frames = (0, 4, 7) if animated else (None,) + for frame in frames: + if frame is not None: + result.draw_frame(frame) + box = _extent(fig, suptitle) + assert _inside_canvas(box) + # clear of every panel title... + for ax in fig.axes[:4]: + assert ax.get_title() in PANEL_TITLES + assert box.y0 >= _extent(fig, ax.title).y1 + # ...of the shared legend, and of everything else drawn + for legend in list(fig.legends) + [ + ax.get_legend() for ax in fig.axes if ax.get_legend()]: + assert box.y0 >= _extent(fig, legend).y1 + assert box.y0 >= _content_top(fig, skip=[suptitle]) - 1e-6 + if style: + assert suptitle.get_fontsize() == 30 + assert to_rgba(suptitle.get_color()) == to_rgba('navy') + + +def test_grid_suptitle_adds_its_own_room(): + """Nothing already laid out is squeezed: the figure grows by the + title's strip, and a larger title grows it more.""" + _, bare = _grid(False, suptitle=None) + _, titled = _grid(False) + _, large = _grid(False, suptitle_kwargs={'size': 40}) + heights = [f.get_size_inches()[1] for f in (bare, titled, large)] + assert heights[0] < heights[1] < heights[2] + widths = [f.get_size_inches()[0] for f in (bare, titled, large)] + assert widths[0] == pytest.approx(widths[1]) == pytest.approx(widths[2]) + for before, after in zip(bare.axes[:4], titled.axes[:4]): + b, a = before.get_position(), after.get_position() + assert b.height * heights[0] == pytest.approx(a.height * heights[1]) + assert b.width == pytest.approx(a.width) + + +@pytest.mark.parametrize('animated', [False, True]) +def test_grid_suptitle_with_a_colorbar(animated): + hue = [np.arange(len(d)) for d in DATA] + result, fig = _grid(animated, legend=None, hue=hue, + colorbar={'label': 'time'}) + suptitle = _figure_text(fig, SUPTITLE_GID) + box = _extent(fig, suptitle) + assert _inside_canvas(box) + assert len(fig.axes) > 4 # the colorbar's axes + for ax in fig.axes: + assert box.y0 >= _extent(fig, ax).y1 - 1e-6 + assert box.y0 >= _content_top(fig, skip=[suptitle]) - 1e-6 + + +@pytest.mark.parametrize('animated', [False, True]) +def test_suptitle_sits_above_a_top_caption_and_a_bottom_one_stays_put( + animated): + result, fig = _grid(animated, caption=CAPTION, + caption_kwargs={'position': 'top'}) + suptitle = _figure_text(fig, SUPTITLE_GID) + caption = _figure_text(fig, CAPTION_GID) + assert _extent(fig, suptitle).y0 >= _extent(fig, caption).y1 + assert _extent(fig, caption).y0 >= _content_top( + fig, skip=[suptitle, caption]) - 1e-6 + + result, fig = _grid(animated, caption=CAPTION, + caption_kwargs={'size': 20}) + suptitle = _figure_text(fig, SUPTITLE_GID) + caption = _figure_text(fig, CAPTION_GID) + box = _extent(fig, caption) + assert _inside_canvas(box) and _inside_canvas(_extent(fig, suptitle)) + assert box.y1 <= _content_bottom(fig, skip=[caption]) + 1e-6 + + +def test_animated_grid_suptitle_clears_per_frame_panel_titles(): + """A per-frame panel title is taller on some frames than on frame 0: + the figure title's room is measured over the sampled frames.""" + def title(ctx): + return 'short' if ctx.frame < 4 else 'two\nlines' + anim = hyp.plot(DATA, '-', panels=(2, 2), title=title, ndims=2, + suptitle=SUPTITLE, animate=True, duration=1, + frame_rate=8, show=False) + suptitle = _figure_text(anim.figure, SUPTITLE_GID) + for frame in (0, 7): + anim.draw_frame(frame) + box = _extent(anim.figure, suptitle) + assert _inside_canvas(box) + for ax in anim.figure.axes[:4]: + assert box.y0 >= _extent(anim.figure, ax.title).y1 + + +@pytest.mark.parametrize('animated', [False, True]) +def test_suptitle_on_a_single_plot(animated): + call = dict(title='the axes title', suptitle=SUPTITLE, show=False) + if animated: + call.update(animate=True, duration=1, frame_rate=8) + result = hyp.plot(X, '-', **call) + fig = result.figure if animated else result + suptitle = _figure_text(fig, SUPTITLE_GID) + box = _extent(fig, suptitle) + assert _inside_canvas(box) + assert box.y0 >= _extent(fig, fig.axes[0].title).y1 + assert fig.axes[0].get_title() == 'the axes title' + + +def test_suptitle_survives_a_saved_still(tmp_path): + """Read back from the saved PNG: the strip above the panels has ink + that the same grid without a title does not have.""" + paths = [] + for name, suptitle in (('bare.png', None), ('titled.png', SUPTITLE)): + paths.append(str(tmp_path / name)) + hyp.plot(DATA, '-', panels=(2, 2), show=False, suptitle=suptitle, + suptitle_kwargs=({'color': 'k', 'size': 24} + if suptitle else None), + save_path=paths[-1]) + bare, titled = (np.asarray(Image.open(p).convert('RGB')) for p in paths) + extra = titled.shape[0] - bare.shape[0] + assert extra > 0 + strip = titled[:extra] + assert (strip.max(-1) < 80).sum() > 100 # the title's ink + # the panels below are what they were (to within the antialiasing of + # a strip that is not a whole number of pixels tall) + below = titled[extra:].astype(int) + assert (np.abs(below - bare.astype(int)).max(-1) > 128).mean() < 0.01 + assert (strip.max(-1) < 80).sum() > 20 * ( + bare[:extra].max(-1) < 80).sum() + + +def test_suptitle_validation(): + with pytest.raises(TypeError, match='suptitle= must be a string'): + hyp.plot(X, '-', show=False, suptitle=['a', 'b']) + with pytest.raises(ValueError, match='no suptitle= was given'): + hyp.plot(X, '-', show=False, suptitle_kwargs={'size': 20}) + with pytest.raises(ValueError, match='suptitle_kwargs'): + hyp.plot(X, '-', show=False, suptitle='t', + suptitle_kwargs={'position': 'bottom'}) + fig, ax = plt.subplots() + with pytest.raises(ValueError, match='caller-supplied ax='): + hyp.plot(X, '-', show=False, suptitle='t', ax=ax, ndims=2) + with pytest.raises(NotImplementedError, + match='suptitle= is matplotlib-only'): + hyp.plot(X, '-', show=False, suptitle='t', backend='plotly') + with pytest.raises(NotImplementedError, + match='suptitle= is matplotlib-only'): + hyp.plot(DATA, '-', panels=(2, 2), show=False, suptitle='t', + backend='plotly') + # an empty title is no title + fig = hyp.plot(X, '-', show=False, suptitle=' ') + assert fig.findobj(lambda a: a.get_gid() == SUPTITLE_GID) == [] diff --git a/tests/test_legend_key_styles.py b/tests/test_legend_key_styles.py new file mode 100644 index 00000000..8f4a241d --- /dev/null +++ b/tests/test_legend_key_styles.py @@ -0,0 +1,268 @@ +"""A legend key looks like the dataset it stands for. + +1.2.1 gallery review: `examples/animate_market_sectors.py` draws six +sector paths 1.1 points wide and a seventh, the market, 3.4 points wide, +and names them with ``legend_colors=[(label, color), ...]``. Every key of +that legend was the same 2-point line, so the heavy path had a thin key +(the library's pair-list legend has drawn one fixed swatch since 1.1.0; +the 1.2.0 example drew its own legend by hand). With one pair per drawn +dataset, each key now takes its dataset's own format and given line +width, line style, marker, marker size and alpha -- on a static plot, an +animation and a `panels=` grid, which share the one legend path. + +Real figures only: the handles' properties are read back, and the keys +are measured in the rendered pixels. +""" +import importlib.util +import os + +import matplotlib +matplotlib.use('Agg') +import matplotlib.colors as mcolors # noqa: E402 +import matplotlib.pyplot as plt # noqa: E402 +import numpy as np # noqa: E402 +import pytest # noqa: E402 + +import hypertools as hyp # noqa: E402 + +PAIRS = [('thin', '#d62728'), ('medium', '#2ca02c'), ('thick', '#1f77b4')] +WIDTHS = [1.0, 2.5, 6.0] +DASHES = ['-', '--', ':'] +ALPHAS = [1.0, 0.6, 0.3] + + +def _data(ndims, k=3): + rng = np.random.default_rng(7) + return [rng.normal(size=(30, ndims)).cumsum(axis=0) for _ in range(k)] + + +def _figure(result): + return getattr(result, 'figure', result) + + +def _legend(fig): + """The figure's one legend: on its axes, or the grid's shared one.""" + legends = [ax.get_legend() for ax in fig.axes + if ax.get_legend() is not None] + list(fig.legends) + assert len(legends) == 1, f'expected one legend, found {len(legends)}' + return legends[0] + + +def _keys(fig): + legend = _legend(fig) + return {text.get_text(): handle for handle, text + in zip(legend.legend_handles, legend.get_texts())} + + +def _key_pixels(fig, handle): + """The rendered pixels of one legend key: a boolean mask (rows x + columns of the key's own box, padded by 10 px above and below) of the + pixels that are not the white canvas.""" + fig.canvas.draw() + image = np.asarray(fig.canvas.buffer_rgba()).astype(int) + box = handle.get_window_extent(fig.canvas.get_renderer()) + height = image.shape[0] + x0, x1 = int(np.floor(box.x0)), int(np.ceil(box.x1)) + middle = height - (box.y0 + box.y1) / 2 + y0, y1 = int(np.floor(middle - 10)), int(np.ceil(middle + 10)) + crop = image[y0:y1, x0:x1, :3] + return (255 - crop).max(axis=2) > 24 + + +def _line_thickness_px(fig, handle): + """How many pixel rows the key's line covers, at its densest column + (a dashed key has gaps; the densest column is inside a dash).""" + return int(_key_pixels(fig, handle).sum(axis=0).max()) + + +def _modes(): + return [ + ('static', {}), + ('animated', {'animate': True, 'duration': 2, 'frame_rate': 5}), + ('panels', {'panels': True}), + ('animated panels', {'panels': True, 'animate': True, 'duration': 2, + 'frame_rate': 5}), + ] + + +@pytest.fixture(autouse=True) +def _close_figures(): + yield + plt.close('all') + + +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('mode', [m[0] for m in _modes()]) +def test_pair_legend_keys_take_each_datasets_line_styling(mode, ndims): + """`legend_colors=` pairs, one per dataset: every key has ITS + dataset's width, dash pattern and alpha, in the handle and on the + canvas.""" + extra = dict(_modes())[mode] + fig = _figure(hyp.plot( + _data(ndims), '-', linewidth=WIDTHS, linestyle=DASHES, alpha=ALPHAS, + legend_colors=PAIRS, show=False, **extra)) + keys = _keys(fig) + assert list(keys) == [label for label, _ in PAIRS] + for (label, color), width, dash, alpha in zip(PAIRS, WIDTHS, DASHES, + ALPHAS): + handle = keys[label] + assert handle.get_linewidth() == pytest.approx(width), label + assert handle.get_linestyle() == dash, label + assert handle.get_alpha() == pytest.approx(alpha), label + assert mcolors.to_hex(handle.get_color()) == color, label + + # the pixels: a key is as thick as its line, lw points at fig.dpi + for label, width in zip(keys, WIDTHS): + expected = width * fig.dpi / 72 + measured = _line_thickness_px(fig, keys[label]) + assert abs(measured - expected) <= 2.0, ( + f'{mode} {ndims}-D: the {label!r} key is {measured} px thick ' + f'on the canvas, its {width}-point line is {expected:.1f} px') + assert (_line_thickness_px(fig, keys['thick']) + >= 2 * _line_thickness_px(fig, keys['thin'])) + # the dashed keys have gaps along their length; the solid one has none + covered = {label: _key_pixels(fig, keys[label]).any(axis=0) + for label in keys} + assert covered['thin'].mean() > 0.9 + assert covered['medium'].mean() < 0.9 + assert covered['thick'].mean() < 0.9 + + +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('animate', [False, True]) +def test_pair_legend_keys_take_each_datasets_marker(animate, ndims): + """A markers-only plot: each key is its dataset's marker, at its + size.""" + sizes, markers = [4, 9, 16], ['o', 's', '^'] + extra = ({'animate': True, 'duration': 2, 'frame_rate': 5} + if animate else {}) + fig = _figure(hyp.plot( + _data(ndims), 'o', markersize=sizes, marker=markers, + legend_colors=PAIRS, show=False, **extra)) + keys = _keys(fig) + areas = [] + for (label, _), size, marker in zip(PAIRS, sizes, markers): + handle = keys[label] + assert handle.get_marker() == marker, label + assert handle.get_markersize() == pytest.approx(size), label + assert handle.get_linestyle() == 'None', label + areas.append(int(_key_pixels(fig, handle).sum())) + # the drawn glyphs grow with the marker size + assert areas[0] < areas[1] < areas[2] + assert areas[2] > 4 * areas[0] + + +def test_pair_legend_keys_follow_a_per_dataset_fmt_list(): + """`fmt=` given per dataset: a line, markers, and a line with + markers each get the key of their own kind.""" + fig = hyp.plot(_data(2), ['-', 'o', 's--'], legend_colors=PAIRS, + show=False) + keys = _keys(fig) + assert (keys['thin'].get_linestyle(), keys['thin'].get_marker()) \ + == ('-', 'None') + assert (keys['medium'].get_linestyle(), keys['medium'].get_marker()) \ + == ('None', 'o') + assert (keys['thick'].get_linestyle(), keys['thick'].get_marker()) \ + == ('--', 's') + + +def test_pair_legend_without_styling_keeps_the_plain_swatch(): + """Nothing styled per dataset: the keys are the 2-point swatches they + have always been.""" + fig = hyp.plot(_data(3), '-', legend_colors=PAIRS, show=False) + for handle in _keys(fig).values(): + assert handle.get_linewidth() == 2 + assert handle.get_linestyle() == '-' + assert handle.get_alpha() is None + + +def test_pairs_that_do_not_pair_up_with_the_datasets_stay_plain(): + """Two entries for three datasets name no dataset in particular: the + keys stay plain swatches, whatever the datasets' widths.""" + fig = hyp.plot(_data(3), '-', linewidth=WIDTHS, legend_colors=PAIRS[:2], + show=False) + for handle in _keys(fig).values(): + assert handle.get_linewidth() == 2 + # ...and a matrix hue's palette swatches (one per hue COLUMN) are not + # the datasets either, even when there are as many of them + hue = [np.tile(np.eye(3)[i], (30, 1)) for i in range(3)] + fig = hyp.plot(_data(3), '-', linewidth=WIDTHS, hue=hue, + hue_mode='mixture', palette=[c for _, c in PAIRS], + legend=True, colorbar=False, show=False) + for handle in _keys(fig).values(): + assert handle.get_linewidth() == 2 + + +@pytest.mark.parametrize('panels', [False, True]) +@pytest.mark.parametrize('ndims', [2, 3]) +def test_plotly_pair_legend_keys_take_each_datasets_width(ndims, panels): + pytest.importorskip('plotly') + fig = hyp.plot(_data(ndims), '-', linewidth=WIDTHS, legend_colors=PAIRS, + backend='plotly', show=False, + **({'panels': True} if panels else {})) + widths = {trace.name: trace.line.width for trace in fig.data + if trace.showlegend} + assert widths == {label: width for (label, _), width + in zip(PAIRS, WIDTHS)} + + +def _load_market_example(): + path = os.path.join(os.path.dirname(__file__), os.pardir, 'examples', + 'animate_market_sectors.py') + spec = importlib.util.spec_from_file_location('animate_market_sectors', + path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_market_example_key_for_the_market_path_is_as_heavy_as_the_path(): + """The gallery example the review flagged: the 'Market' key is 3.4 + points like the market path, the six sector keys 1.1 like theirs, in + the handle and on the first and a late frame.""" + example = _load_market_example() + anim = example.construct_artifact(example.fixture_data()) + fig = anim.figure + keys = _keys(fig) + assert list(keys) == list(example.SECTORS) + [ + 'Market (average across sectors)'] + market = keys['Market (average across sectors)'] + assert market.get_linewidth() == pytest.approx(3.4) + assert mcolors.to_hex(market.get_color()) == '#666666' + for name in example.SECTORS: + assert keys[name].get_linewidth() == pytest.approx(1.1) + + for frame in (0, anim.n_frames - 300): + anim.draw_frame(frame) + thick = _line_thickness_px(fig, market) + thin = max(_line_thickness_px(fig, keys[name]) + for name in example.SECTORS) + assert abs(thick - 3.4 * fig.dpi / 72) <= 2.0, (frame, thick) + assert thick >= thin + 2, (frame, thick, thin) + + +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('fmt, style', [ + ('-', {'linestyle': ['-', '--', ':']}), + ('o', {'marker': ['o', 's', '^']}), + ('-o', {'marker': ['o', 's', '^'], 'linestyle': ['-', '--', ':']}), +]) +def test_animated_fmt_with_style_keywords_does_not_warn(fmt, style, ndims): + """Found while testing the keys: an animation passed matplotlib the + format string AND the dataset's `linestyle=`/`marker=`, so matplotlib + warned that the property "is redundantly defined" once per dataset + (the static plot of the same call is silent). The keyword wins, as + before, and nothing is warned.""" + import warnings + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + anim = hyp.plot(_data(ndims), fmt, animate=True, chemtrails=True, + duration=2, frame_rate=5, show=False, **style) + anim.draw_frame(anim.n_frames - 1) + redundant = [str(w.message) for w in caught + if 'redundantly defined' in str(w.message)] + assert redundant == [] + lines = anim.figure.axes[0].lines + for key, values in style.items(): + drawn = {getattr(line, f'get_{key}')() for line in lines} + assert set(values) <= drawn, (key, drawn) diff --git a/tests/test_lsl_streaming.py b/tests/test_lsl_streaming.py index 54a1ecf6..394aedeb 100644 --- a/tests/test_lsl_streaming.py +++ b/tests/test_lsl_streaming.py @@ -43,6 +43,62 @@ branches of `test_lsl_stream_resolves_any_stream` pass in their respective environments. +**Discovery (why the session uses tests/lsl_loopback.cfg on macOS).** liblsl +finds an outlet by sending a query datagram to port 16571, which every outlet +on the machine binds with address reuse: once to 127.0.0.1 as plain unicast, +once to the broadcast address, and once to each multicast group (224.0.0.1, +224.0.0.183, 239.255.172.215), the whole list repeated on every network +interface through ONE socket whose outbound interface is switched in between +(`resolve_attempt_udp::send_next_query`, liblsl 1.17.7). Measured 2026-11-23 +on macOS 26 (Darwin 25.6), pylsl 1.18.2, with plain sockets and with real +outlets, before and after a restart of the machine: + +* The unicast query reaches exactly one of the sockets bound to the port (the + oldest), so only one outlet on the whole machine can be found that way. + Every other outlet depends on multicast: the second outlet of + `test_lsl_stream_name_takes_precedence_over_type`, and any outlet at all + while another process on the machine holds one. +* Nothing sent on the Ethernet/Wi-Fi interface was looped back (0 of 30). +* A multicast datagram sent on the loopback interface is delivered (30 of + 30) unless the same socket is switched to another interface right after, + in which case it is lost (0 of 30 with no delay, 30 of 30 with 1 ms). + liblsl switches a few microseconds after its last loopback send, so of 20 + query waves 18 delivered the 224.0.0.1 datagram, 8 the 224.0.0.183 one + and 4 the 239.255.172.215 one (11 to 13, 8 to 11 and 3 to 7 with 400 more + CPU-bound processes). On the freshly restarted machine the second of two + outlets was found at once in 8 of 12 resolves and after 0.5, 0.5, 1.0 and + 2.5 s in the others. +* With ``[lab] KnownPeers = {127.0.0.1}`` liblsl also sends every query + straight to each port of its port range (16572 and up), where every outlet + has a socket of its own, 0.5 s into the resolve and every 1.25 s after. + The second of two outlets was then found within 0.51 s in 12 of 12 + resolves (and in 25 of 25 before the restart). +* Separately, before the restart the kernel was dropping UDP on the loopback + interface for minutes at a time, on any port: a fresh socket received 0 of + 20 datagrams sent to it, the count of datagrams "dropped due to full + socket buffers" (`netstat -s -p udp`) rose by 3,096 in 10 s, `netstat -m` + showed 94.7% of the memory allocated to the network in use with 2,034 + requests denied, and the receive queue of the ``com.apple.content-filter`` + kernel control socket was full (523,880 of 524,288 bytes; a network + content filter is installed on that machine). In milder phases only + multicast to sockets already bound to port 16571 stopped (two real + outlets, a resolver on the default configuration: the second outlet found + for 37 s, then in none of 13 resolves of 8 s each, while two resolvers + with KnownPeers found it in 138 of 138 and 154 of 154). After the restart + 1.7% was in use and none of it happened. What fills those buffers was NOT + established; no liblsl setting helps while unicast is dropped too. + +The full-suite failure "no LSL stream found +(name='HypertoolsTestStreamB-...') within timeout=30.0s" is the second +outlet of that test not being heard: the one case in this file that cannot +be served by the unicast query. tests/lsl_loopback.cfg sets KnownPeers, +tests/conftest.py points ``LSLAPICFG`` at that file on macOS unless the +caller set one (as in the paragraph above), and liblsl reads it once per +process. `test_every_discovery_wave_queries_each_outlet_port_directly` pins +it. The library itself leaves liblsl's configuration alone: a second outlet +on a Mac (or one outlet while another LSL program runs) can take several +query waves to appear in `hyp.io.lsl_stream`, as in any LSL client. + **Machines that cannot create an outlet at all.** Binding liblsl's service ports can fail outright (``All local ports were found occupied`` -> ``RuntimeError: could not create stream outlet``), which would otherwise @@ -62,6 +118,8 @@ """ import os +import select +import socket import subprocess import sys import textwrap @@ -158,6 +216,15 @@ def _require_outlets(): pytest.skip(message) +# Discovery timeouts (`lsl_stream(..., timeout=30.0)` throughout): the +# resolve returns as soon as the named outlet answers, so a long timeout +# costs nothing when the outlet is found. With tests/lsl_loopback.cfg that +# is at once or 0.5 s into the resolve (module docstring, *Discovery*). The +# 30 s is for the phases in which the kernel drops loopback UDP (same +# section): at 5 s five tests of this file failed in one full-suite run and +# at 30 s one did, and with both in place nine of nine discovery tests +# failed at 5 s while that was going on. + #: How long a test waits for `_start_outlet`'s thread to END after `stop` is #: set. The thread's closure holds the only reference to the outlet, so its #: exit includes `StreamOutlet.__del__` -> liblsl's `lsl_destroy_outlet`, and @@ -241,13 +308,13 @@ def test_ci_has_pylsl(): @requires_pylsl def test_is_stream_true_for_lsl_stream(outlet_stream): - stream = hyp.io.lsl_stream(name=outlet_stream, timeout=5.0) + stream = hyp.io.lsl_stream(name=outlet_stream, timeout=30.0) assert is_stream(stream) @requires_pylsl def test_lsl_stream_receives_pushed_samples_by_name(outlet_stream): - stream = hyp.io.lsl_stream(name=outlet_stream, timeout=5.0) + stream = hyp.io.lsl_stream(name=outlet_stream, timeout=30.0) received = [next(stream) for _ in range(10)] @@ -276,7 +343,7 @@ def test_lsl_stream_resolves_by_type(): thread, stop = _start_outlet( f'HypertoolsTestStream-bytype-{time.time_ns()}', stream_type=stream_type) try: - with hyp.io.lsl_stream(type=stream_type, timeout=5.0) as stream: + with hyp.io.lsl_stream(type=stream_type, timeout=30.0) as stream: sample = next(stream) assert len(sample) == N_CHANNELS finally: @@ -297,7 +364,7 @@ def test_lsl_stream_name_takes_precedence_over_type(): outlet_b = hyp.io.lsl.synthetic_outlet(name_b, n_channels=N_CHANNELS, stream_type='EEG') try: - stream = hyp.io.lsl_stream(name=name_b, type='EEG', timeout=5.0) + stream = hyp.io.lsl_stream(name=name_b, type='EEG', timeout=30.0) sample = next(stream) assert len(sample) == N_CHANNELS finally: @@ -306,6 +373,70 @@ def test_lsl_stream_name_takes_precedence_over_type(): assert not outlet_a.thread.is_alive() and not outlet_b.thread.is_alive() +#: the liblsl configuration tests/conftest.py selects on macOS +_LOOPBACK_CFG = os.path.join(os.path.dirname(os.path.abspath(__file__)), + 'lsl_loopback.cfg') + + +def _require_loopback_cfg(): + """Skip unless liblsl runs on tests/lsl_loopback.cfg in this session.""" + if os.environ.get('LSLAPICFG') != _LOOPBACK_CFG: + pytest.skip('liblsl is not running on tests/lsl_loopback.cfg here ' + '(tests/conftest.py selects it on macOS only, and keeps ' + f'a caller\'s LSLAPICFG): {os.environ.get("LSLAPICFG")!r}') + + +@requires_pylsl +def test_every_discovery_wave_queries_each_outlet_port_directly(): + """A resolve must send its query straight to every port an outlet can + listen on, so that finding an outlet does not depend on multicast + delivery to the shared discovery port -- which stopped altogether for + minutes at a time on the machine where `test_lsl_stream_name_takes_ + precedence_over_type` found no stream in 30 s (*Discovery* in the + module docstring). Binds a real UDP socket to a free port of liblsl's + range, exactly where an outlet's own server would be, and counts the + queries a real 9 s `pylsl.resolve_byprop` sends to it (7 are due, one + every 1.25 s from 0.5 s on; liblsl's default configuration sends + none).""" + _require_loopback_cfg() + name = f'HypertoolsNobody-{time.time_ns()}' + listener = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + queries = [] + done = threading.Event() + + def _listen(): + while not done.is_set(): + if select.select([listener], [], [], 0.05)[0]: + data = listener.recvfrom(4096)[0] + if name.encode() in data: # else: another process's query + queries.append(data) + + try: + for port in range(16572, 16604): + try: + listener.bind(('', port)) + except OSError: + continue # an outlet or a resolver has this one + break + else: + pytest.skip('every port of liblsl\'s range 16572-16603 is in ' + 'use on this machine, so there is none to listen on') + thread = threading.Thread(target=_listen, daemon=True) + thread.start() + try: + assert pylsl.resolve_byprop('name', name, timeout=9.0) == [] + time.sleep(0.3) # let the last query arrive + finally: + done.set() + thread.join(timeout=10.0) + assert not thread.is_alive() + finally: + listener.close() + # 7 are due; 6 leaves room for a late timer on a loaded machine + assert len(queries) >= 6, len(queries) + assert all(q.startswith(b'LSL:shortinfo') for q in queries) + + # ------------------------------------------- hyp.io.lsl.synthetic_outlet() @@ -333,7 +464,7 @@ def test_synthetic_outlet_is_discoverable_by_lsl_stream(): name = f'HypertoolsSyntheticTest-{time.time_ns()}' outlet = hyp.io.lsl.synthetic_outlet(name) try: - stream = hyp.io.lsl_stream(name=name, timeout=5.0) + stream = hyp.io.lsl_stream(name=name, timeout=30.0) assert is_stream(stream) stream.close() finally: @@ -347,7 +478,7 @@ def test_synthetic_outlet_samples_have_n_channels(): name = f'HypertoolsSyntheticTest-{time.time_ns()}' outlet = hyp.io.lsl.synthetic_outlet(name, n_channels=6) try: - stream = hyp.io.lsl_stream(name=name, timeout=5.0) + stream = hyp.io.lsl_stream(name=name, timeout=30.0) sample = next(stream) assert len(sample) == 6 stream.close() @@ -403,7 +534,7 @@ def test_timeout_raises_hypertools_io_error(): @requires_pylsl def test_plot_stream_end_to_end(outlet_stream): - stream = hyp.io.lsl_stream(name=outlet_stream, timeout=5.0) + stream = hyp.io.lsl_stream(name=outlet_stream, timeout=30.0) # _sample_for_index is a monotonically increasing ramp, so every # post-head sample is guaranteed outside the display box fitted on the # first stream_init samples -- the clamped-samples notice must fire @@ -756,7 +887,11 @@ def test_lsl_stream_raises_when_source_stops_delivering(): _require_outlets() outlet = hyp.io.lsl.synthetic_outlet(name, n_channels=N_CHANNELS) try: - stream = hyp.io.lsl_stream(name=name, timeout=2.0) + # (10 s, not 2: `timeout=` is also how long the first sample + # may take, and on a machine under load the 2 s ran out before + # it came; the stall below is then detected after 10 s of + # silence, well inside the 30 s the test allows) + stream = hyp.io.lsl_stream(name=name, timeout=10.0) # receive at least one real sample while the outlet is alive assert len(next(stream)) == N_CHANNELS finally: @@ -793,7 +928,7 @@ def _inlet_ref(stream): @requires_pylsl def test_close_destroys_the_inlet_and_is_idempotent(outlet_stream): - stream = hyp.io.lsl_stream(name=outlet_stream, timeout=5.0) + stream = hyp.io.lsl_stream(name=outlet_stream, timeout=30.0) assert len(next(stream)) == N_CHANNELS assert not stream.closed ref = _inlet_ref(stream) @@ -814,7 +949,7 @@ def test_close_destroys_the_inlet_and_is_idempotent(outlet_stream): @requires_pylsl def test_context_manager_closes_the_inlet(outlet_stream): - with hyp.io.lsl_stream(name=outlet_stream, timeout=5.0) as stream: + with hyp.io.lsl_stream(name=outlet_stream, timeout=30.0) as stream: assert is_stream(stream) assert len(next(stream)) == N_CHANNELS ref = _inlet_ref(stream) @@ -825,7 +960,7 @@ def test_context_manager_closes_the_inlet(outlet_stream): @requires_pylsl def test_dropping_the_last_reference_destroys_the_inlet(outlet_stream): import gc - stream = hyp.io.lsl_stream(name=outlet_stream, timeout=5.0) + stream = hyp.io.lsl_stream(name=outlet_stream, timeout=30.0) assert len(next(stream)) == N_CHANNELS ref = _inlet_ref(stream) del stream @@ -838,7 +973,7 @@ def test_plot_stream_leaves_the_stream_open_for_reuse(outlet_stream): # hyp.plot stops PULLING at stream_max; it does not own the stream, so # the caller decides when the inlet goes (the tutorial closes it # explicitly, before tearing down its outlet) - stream = hyp.io.lsl_stream(name=outlet_stream, timeout=5.0) + stream = hyp.io.lsl_stream(name=outlet_stream, timeout=30.0) with pytest.warns(RuntimeWarning, match='outside the display box'): hyp.plot(stream, show=False, stream_init=20, stream_chunk=10, stream_max=40) @@ -858,7 +993,7 @@ def test_plot_stream_leaves_the_stream_open_for_reuse(outlet_stream): NAME = 'HypertoolsTeardownTest-%d' % time.time_ns() outlet = hyp.io.lsl.synthetic_outlet(NAME, n_channels=6) - stream = hyp.io.lsl_stream(name=NAME, timeout=5.0) + stream = hyp.io.lsl_stream(name=NAME, timeout=30.0) fig = hyp.plot(stream, stream_init=40, stream_chunk=20, stream_max=120, show=False) assert fig.stream_info['n_samples'] >= 120, fig.stream_info @@ -925,7 +1060,7 @@ def _hog(): threading.Thread(target=_hog, daemon=True).start() for k in range(CYCLES): - stream = hyp.io.lsl_stream(name=NAME, timeout=5.0) + stream = hyp.io.lsl_stream(name=NAME, timeout=30.0) fig = hyp.plot(stream, stream_init=200, stream_chunk=20, stream_max=600, save_path=SAVE_PATH, frame_rate=5, show=False) diff --git a/tests/test_multibyte.py b/tests/test_multibyte.py index 46ecc8c9..d2960c06 100644 --- a/tests/test_multibyte.py +++ b/tests/test_multibyte.py @@ -1084,17 +1084,25 @@ def _descendants(pid): def _alive(started): - """The entries of `started` (``{pid: command line}``) still running - the same command.""" + """The entries of `started` (``{pid: [command lines seen]}``) still in + the process table under one of the command lines that process was seen + with, as ``{pid: its command line now}``. Every command line seen + counts, so a process cannot drop out of this check by changing how + ``ps`` describes it (a fork that then `exec`s, a bare "(sleep)" under + load, "" once it has exited and awaits its parent).""" table = _process_table() - return {pid: command for pid, command in started.items() - if pid in table and table[pid][1] == command} + return {pid: table[pid][1] for pid, commands in started.items() + if pid in table and table[pid][1] in commands} def _run_render_watching_its_processes(out_path, env, tmp_path): """`_run_render`, also returning every process the render script was - seen to start while it ran (``{pid: command line}``, polled from the - real process table twice a second).""" + seen to start while it ran, polled from the real process table twice a + second: ``{pid: [every command line it was seen with, in order]}``. The + history is kept because one process is described differently over its + life: on 2026-11-22 a macOS job's last snapshot caught the stand-in + browser already ended (""), and keeping only the latest + description erased the "sleep 600" seen before it.""" full = dict(os.environ) full.update(env or {}) started = {} @@ -1106,7 +1114,10 @@ def _run_render_watching_its_processes(out_path, env, tmp_path): limit = time.monotonic() + _KALEIDO_TIMEOUT_S try: while proc.poll() is None: - started.update(_descendants(proc.pid)) + for pid, command in _descendants(proc.pid).items(): + seen = started.setdefault(pid, []) + if command not in seen: + seen.append(command) if time.monotonic() > limit: proc.kill() proc.wait() @@ -1159,7 +1170,8 @@ def test_render_script_exits_NO_BROWSER_when_the_browser_never_answers( # "sleep 600"; only the wrapper's arguments name the script, and # under load `ps` reports a bare "(sleep)" with no arguments at all assert any('silent-browser' in command or 'sleep' in command - for command in started.values()), ( + for commands in started.values() + for command in commands), ( f'the stand-in browser was never seen running: {started}') deadline = time.monotonic() + 10 alive = _alive(started) diff --git a/tests/test_review_round1_1_2_1.py b/tests/test_review_round1_1_2_1.py new file mode 100644 index 00000000..d61d921a --- /dev/null +++ b/tests/test_review_round1_1_2_1.py @@ -0,0 +1,833 @@ +"""1.2.1 review round 1: defects two reviews found in the GH #299 animation +arguments and the GH #297 layout fixes. + +A. Observation labels are placed STABLY. An animation's labels follow + a table worked out for the whole animation (review round 5), so a + frame is the same picture whatever was drawn before it and no label + hops back and forth; a static figure saves the + same picture every time, and a label of a figure turned by hand stays + where it is until its box is covered. +B. Continuous ``hue=`` in an animation: markers of a line-and-marker + format on tail and trail, serial trails that are empty when they + should be, the dataset's own opacity, mixed formats. +C. Arguments: ``tail_linewidth=`` warnings, values inside + ``head_marker=``/``caption_kwargs=``/``suptitle_kwargs=``, static + plotly, ``hold=`` in a saved gif, the cube's margin, a suptitle over a + caption that grows. + +Real figures and real frames, rendered headless; saved files are read +back. Nothing is mocked, and no assertion depends on a font's absolute +metrics: boxes are measured where they were drawn and compared with each +other. +""" +import itertools +import warnings + +import matplotlib +matplotlib.use('Agg') + +import matplotlib.pyplot as plt # noqa: E402 +import numpy as np # noqa: E402 +import pytest # noqa: E402 +from matplotlib.animation import PillowWriter # noqa: E402 +from matplotlib.collections import PathCollection # noqa: E402 +from mpl_toolkits.mplot3d import proj3d # noqa: E402 +from PIL import Image # noqa: E402 + +import hypertools as hyp # noqa: E402 +from hypertools.plot.matplotlib_backend import label_tracks # noqa: E402 +from hypertools.plot.plot import CAPTION_GID, SUPTITLE_GID # noqa: E402 + + +def _walk(seed, rows=40, cols=3): + return np.random.default_rng(seed).normal(size=(rows, cols)).cumsum(0) + + +X, Y = _walk(0), _walk(1) +HUE = np.linspace(0.0, 1.0, len(X)) +CLOUD = np.random.default_rng(3).standard_normal((30, 3)) +NAMES = [f'Subject {i}' for i in range(len(CLOUD))] + + +@pytest.fixture(autouse=True) +def _close_figures(): + yield + plt.close('all') + + +# -------------------------------------------------------------------------- +# A. stable label placement +# -------------------------------------------------------------------------- + +def _labels(fig): + return [entry[0] for entry in fig.axes[0]._hyp_labels_and_points] + + +def _label_history(anim): + """Per frame: each label's offset (None while it is hidden), and the + number of pairs of visible label boxes that overlap.""" + fig = anim.figure + labels = _labels(fig) + places, overlaps = [], [] + for frame in range(anim.n_frames): + anim.draw_frame(frame) + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + places.append([tuple(label.xyann) if label.get_visible() else None + for label in labels]) + boxes = [label.get_bbox_patch().get_window_extent(renderer) + for label in labels if label.get_visible()] + overlaps.append(sum(1 for one, other in itertools.combinations( + boxes, 2) if one.overlaps(other))) + return places, overlaps + + +def _switches(places): + """How many times a label changed place between two consecutive + frames it was visible on, and how many of those changes went BACK to + a place the label had left within the three frames before.""" + switches = returns = 0 + for track in zip(*places): + changed = [k for k in range(1, len(track)) + if track[k] is not None and track[k - 1] is not None + and track[k] != track[k - 1]] + switches += len(changed) + for k in changed: + if any(track[j] == track[k] and track[j] is not None + for j in range(max(0, k - 4), k - 1)): + returns += 1 + return switches, returns + + +def _pixels(fig): + fig.canvas.draw() + return np.asarray(fig.canvas.buffer_rgba()).copy() + + +class _KeepFrames(PillowWriter): + """Pillow's own gif writer, which also keeps the frames it was given + so they can be compared with frames drawn one at a time.""" + + def finish(self): + self.kept = [np.asarray(frame.convert('RGBA')).copy() + for frame in self._frames] + super().finish() + + +LABELED_ANIMATIONS = { + 'spin, 8 labels': dict(data=CLOUD[:8], labels=NAMES[:8], + animate='spin'), + 'spin, 30 labels': dict(data=CLOUD, labels=NAMES, animate='spin'), + 'window, 3-D': dict(data=CLOUD, labels=NAMES, animate='window'), + 'window, 2-D': dict(data=CLOUD[:, :2], labels=NAMES, animate='window'), + 'reveal': dict(data=CLOUD, labels=NAMES, animate=True), +} + + +def _labeled(name, **kwargs): + spec = dict(LABELED_ANIMATIONS[name]) + kwargs = {'duration': 4, 'frame_rate': 15, **kwargs} + return hyp.plot(spec.pop('data'), 'o', show=False, **spec, **kwargs) + + +def _tracks(fig): + return label_tracks(fig.axes[0]) + + +@pytest.mark.parametrize('name', list(LABELED_ANIMATIONS)) +def test_animated_labels_follow_one_table(name): + """An animation's labels follow a table worked out for the whole + animation (owner decision 2026-11-23; rewritten in review round 5 + from the test that pinned labels placed once and held). The first + draft of 1.2.1 placed them afresh on every draw (71 changes of place + in 60 frames with 8 labels, 777 with 30, 233 in a sliding window) + and they hopped back and forth: now no label goes BACK to a place it + left within the three frames before, a second pass through the + animation shows every label exactly where the first did, and the + placement is a real one: labels were moved off each other.""" + anim = _labeled(name) + assert anim.n_frames == 60 + places, _overlaps = _label_history(anim) + tracks = _tracks(anim.figure) + named = [[int(place) if shown else None + for place, shown in zip(row, visible)] + for row, visible in zip(tracks['places'], tracks['shown'])] + _changes, returns = _switches(named) + assert returns == 0 + home = tracks['places'][0, 0] if not tracks['shown'].any() else min( + tracks['places'][tracks['shown']]) + assert (tracks['places'][tracks['shown']] != home).any() + again, _overlaps = _label_history(anim) + assert again == places + + +@pytest.mark.parametrize('name', ['spin, 8 labels', 'window, 3-D']) +def test_animated_labels_are_placed_for_every_view(name): + """The labels are placed for each frame's own view (rewritten in + review round 5 from the test of one placement for the first view): + at the first frame, a quarter, a half and three quarters of the way + through, the labels shown overlap far less than they would at their + usual places in that view.""" + from hypertools.plot.matplotlib_backend import (_LABEL_CANDIDATES, + _LABEL_HOME, + _label_center_offsets, + _label_size_pt) + anim = _labeled(name) + fig = anim.figure + labels = _labels(fig) + tracks = _tracks(fig) + + def overlapping(frames): + total = 0 + for frame in frames: + anim.draw_frame(frame) + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + boxes = [label.get_bbox_patch().get_window_extent(renderer) + for label in labels if label.get_visible()] + total += sum(1 for one, other in itertools.combinations( + boxes, 2) if one.overlaps(other)) + return total + + frames = (0, 15, 30, 45, 59) + placed = overlapping(frames) + sizes = np.array([_label_size_pt(label) for label in labels]) + usual_places = np.full(tracks['places'].shape, + _LABEL_CANDIDATES.index(_LABEL_HOME)) + tracks['offsets'] = np.where( + tracks['shown'][..., None], + _label_center_offsets(usual_places, sizes), np.nan) + usual = overlapping(frames) + assert usual > 0 + assert placed <= usual / 4, (placed, usual) + + +@pytest.mark.parametrize('name', list(LABELED_ANIMATIONS)) +def test_a_frame_is_the_same_picture_whatever_was_drawn_before(name): + """`draw_frame(i)` gives the same pixels in order, in a shuffled + order and backwards.""" + anim = _labeled(name, duration=2, frame_rate=10) + fig = anim.figure + + def frame(i): + anim.draw_frame(int(i)) + return _pixels(fig) + + forward = [frame(i) for i in range(anim.n_frames)] + shuffled = np.random.default_rng(0).permutation(anim.n_frames) + for i in list(shuffled) + list(range(anim.n_frames))[::-1]: + assert np.array_equal(frame(i), forward[i]), i + + +@pytest.mark.parametrize('name', ['spin, 8 labels', 'window, 3-D']) +def test_a_saved_animation_is_its_frames_drawn_one_at_a_time(name, tmp_path): + """Saving after frames were drawn in another order, and the same + call made twice, give the same frames.""" + anim = _labeled(name, duration=2, frame_rate=10) + fig = anim.figure + forward = [] + for i in range(anim.n_frames): + anim.draw_frame(i) + forward.append(_pixels(fig)) + anim.draw_frame(anim.n_frames // 2) + writer = _KeepFrames(fps=10) + anim.animation.save(str(tmp_path / 'saved.gif'), writer=writer) + assert len(writer.kept) == anim.n_frames + for i, saved in enumerate(writer.kept): + assert np.array_equal(saved, forward[i]), i + twin = _labeled(name, duration=2, frame_rate=10) + for i in (anim.n_frames - 1, 0, anim.n_frames // 2): + twin.draw_frame(i) + assert np.array_equal(_pixels(twin.figure), forward[i]), i + + +def test_animated_panels_show_a_frame_the_same_way_every_time(): + """An animated grid's labels (rewritten in review round 5 from the + test that the labels hold one place): every panel's labels are + where they were whenever a frame is shown again, in any order.""" + data = [_walk(1), _walk(2)] + names = [[f'a{k}' if k % 8 == 0 else None for k in range(40)], + [f'b{k}' if k % 8 == 0 else None for k in range(40)]] + anim = hyp.plot(data, '-o', panels=True, labels=names, animate=True, + duration=2, frame_rate=10, show=False) + fig = anim.figure + labels = [entry[0] for ax in fig.axes + for entry in getattr(ax, '_hyp_labels_and_points', None) or []] + assert len(labels) == 10 + frames = (0, anim.n_frames - 1, 7, 3) + first, pictures = {}, {} + for i in frames: + anim.draw_frame(i) + pictures[i] = _pixels(fig) + first[i] = [tuple(label.xyann) if label.get_visible() else None + for label in labels] + for i in frames[::-1] + (7, 0): + anim.draw_frame(i) + assert np.array_equal(_pixels(fig), pictures[i]), i + assert [tuple(label.xyann) if label.get_visible() else None + for label in labels] == first[i] + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_the_same_static_call_saves_the_same_picture(ndims, tmp_path): + """`plot()` + `savefig` twice: identical pixels, labels placed off + each other (not all at the usual place).""" + pictures = [] + for k in range(2): + fig = hyp.plot(CLOUD[:, :ndims], 'o', labels=NAMES, show=False) + path = tmp_path / f'static{k}.png' + fig.savefig(path) + pictures.append(plt.imread(path)) + if k == 0: + assert any(tuple(label.xyann) != (-20.0, 20.0) + for label in _labels(fig)) + fig.savefig(path) # ...and a second save of it + assert np.array_equal(plt.imread(path), pictures[0]) + assert np.array_equal(pictures[0], pictures[1]) + + +def test_a_static_label_keeps_its_place_while_it_is_clear(): + """Hysteresis on a figure turned by hand (what a mouse drag does): a + label that was moved does not go back when its old place becomes + free, and a label that is clear is not touched.""" + fig = hyp.plot(CLOUD[:8], 'o', labels=NAMES[:8], show=False) + ax = fig.axes[0] + labels = _labels(fig) + fig.canvas.draw() + moved = 0 + for _step in range(1, 60): + before = [tuple(label.xyann) for label in labels] + ax.view_init(elev=ax.elev, azim=ax.azim + 6.0) + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + after = [tuple(label.xyann) for label in labels] + for k, label in enumerate(labels): + if before[k] == after[k]: + continue + moved += 1 + # the label moved: at its OLD place, in this view, its box + # would be on an earlier label's + now = label.get_bbox_patch().get_window_extent(renderer) + width, height = now.width, now.height + anchor = ax.transData.transform(label.xy) + scale = renderer.points_to_pixels(1.0) + # (the frame reaches `pad` beyond the text on every side) + pad = label.get_bbox_patch().get_boxstyle().pad \ + * label.get_size() * scale + dx, dy = before[k][0] * scale, before[k][1] * scale + x0 = anchor[0] + dx + (pad - width if dx < 0 else + -0.5 * width if dx == 0 else -pad) + y0 = anchor[1] + dy + (pad - height if dy < 0 else + -0.5 * height if dy == 0 else -pad) + # (...or it had been moved there and that place has left the + # canvas) + covered = (x0 < 2.0 or y0 < 2.0 + or x0 + width > fig.bbox.width - 2.0 + or y0 + height > fig.bbox.height - 2.0) + for other in labels[:k]: + box = other.get_bbox_patch().get_window_extent(renderer) + if (min(x0 + width, box.x1) - max(x0, box.x0) > -2.0 + and min(y0 + height, box.y1) + - max(y0, box.y0) > -2.0): + covered = True + assert covered, (_step, label.get_text(), before[k], after[k]) + assert moved # (the turn did move labels) + + +def test_static_labels_start_from_their_usual_place(): + """A static figure's labels are placed on the finished figure, not + left where a draw made during its layout put them: the label that + comes first is where it has always been, and two draws agree.""" + fig = hyp.plot(CLOUD, 'o', labels=NAMES, show=False) + fig.canvas.draw() + labels = _labels(fig) + assert tuple(labels[0].xyann) == (-20.0, 20.0) + first = [tuple(label.xyann) for label in labels] + fig.canvas.draw() + assert [tuple(label.xyann) for label in labels] == first + + +def test_hand_rotation_moves_only_covered_labels(): + """Turning a static 3-D plot (what a mouse drag does): between two + close views almost every label keeps its place.""" + fig = hyp.plot(CLOUD[:12], 'o', labels=NAMES[:12], show=False) + ax = fig.axes[0] + fig.canvas.draw() + labels = _labels(fig) + changes = 0 + for step in range(1, 31): + before = [tuple(label.xyann) for label in labels] + ax.view_init(elev=ax.elev, azim=ax.azim + 3.0) + fig.canvas.draw() + changes += sum(one != other for one, other in zip( + before, [tuple(label.xyann) for label in labels])) + assert changes <= 30, changes # 12 labels x 30 views = 360 + + +def test_label_arrows_point_at_their_points_after_the_cube_is_shrunk(): + """A static 3-D plot whose inside legend makes the cube smaller + (GH #297): the labels' anchors were left at the projection of the + cube's first size, up to 9 px from their points.""" + data = [_walk(seed, rows=60) for seed in range(5)] + names = [f'p{i}' if i % 20 == 0 else None for i in range(300)] + fig = hyp.plot(data, '-', labels=names, size=(5, 5), show=False, + legend=[f'A long name for dataset {k}' for k in range(5)], + legend_kwargs={'loc': 'upper left', 'fontsize': 8}) + ax = fig.axes[0] + reference = plt.figure().add_subplot(projection='3d').get_box_aspect() + assert ax.get_box_aspect()[0] < 0.97 * reference[0] # it was shrunk + fig.canvas.draw() + for label, x, y, z in ax._hyp_labels_and_points: + x2, y2, _ = proj3d.proj_transform(x, y, z, ax.get_proj()) + np.testing.assert_allclose( + ax.transData.transform(label.xy), + ax.transData.transform((x2, y2)), atol=0.5) + + +# -------------------------------------------------------------------------- +# B. continuous hue in an animation +# -------------------------------------------------------------------------- + +def _roles(ax): + return {coll._hyp_trace_role: coll for coll in ax.collections + if getattr(coll, '_hyp_trace_role', None)} + + +def _marker_scatters(ax): + return {coll._hyp_markers_of: coll for coll in ax.collections + if getattr(coll, '_hyp_markers_of', None)} + + +def _n_points(coll, ndims): + if not coll.get_visible(): + return 0 + if ndims == 3: + return len(np.asarray(coll._offsets3d[0])) + return len(coll.get_offsets()) + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_line_marker_format_with_hue_draws_markers_on_tail_and_trail(ndims): + """``'-o'`` + ``hue=`` + ``chemtrails=``: the animated plot drew the + colored line and no marker at all, where the static plot draws both.""" + anim = hyp.plot(X[:, :ndims], '-o', hue=HUE, animate=True, + chemtrails=True, tail_duration=1, duration=6, + frame_rate=10, show=False) + anim.draw_frame(35) + anim.figure.canvas.draw() + ax = anim.figure.axes[0] + dots = _marker_scatters(ax) + assert set(dots) == {(0, 'head'), (0, 'trail')} + assert all(isinstance(coll, PathCollection) for coll in dots.values()) + head, trail = _n_points(dots[0, 'head'], ndims), _n_points( + dots[0, 'trail'], ndims) + # one marker per revealed observation, none twice + assert head >= 2 and trail >= 2 + assert 20 <= head + trail <= 26 # row 35/60 of 40 + # ...each in its observation's color: several distinct colors + colors = np.asarray(dots[0, 'trail'].get_facecolors()) + assert len(np.unique(colors[:, :3].round(3), axis=0)) >= trail - 1 + # the trail's markers are as faint as the trail's line + assert dots[0, 'trail'].get_alpha() == pytest.approx(0.3) + assert _roles(ax)['trail'].get_alpha() == pytest.approx(0.3) + # and they are really drawn: ink in the colors of the palette + # disappears when the scatters are hidden + def ink(): + anim.figure.canvas.draw() + return int((np.asarray( + anim.figure.canvas.buffer_rgba())[..., :3] < 250).any(-1).sum()) + with_markers = ink() + for coll in dots.values(): + coll.set_visible(False) + assert ink() < with_markers + + +def test_line_marker_format_with_hue_in_an_animated_grid(): + anim = hyp.plot([X, Y], '-o', hue=[HUE, HUE], panels=True, + animate=True, chemtrails=True, tail_duration=1, + duration=6, frame_rate=10, show=False) + anim.draw_frame(35) + anim.figure.canvas.draw() + for ax in anim.figure.axes[:2]: + dots = _marker_scatters(ax) + assert len(dots) == 2 + assert all(_n_points(coll, 3) >= 2 for coll in dots.values()) + + +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('flag', ['chemtrails', 'precog', 'bullettime']) +def test_serial_marker_trails_with_hue_draw_every_frame(ndims, flag): + """``'o'`` + ``hue=`` + ``animate='serial'`` + a trail flag raised + AttributeError (`set_segments` on a scatter) on the first frame.""" + anim = hyp.plot([X[:, :ndims], Y[:, :ndims]], 'o', hue=[HUE, HUE], + animate='serial', duration=2, frame_rate=10, + show=False, **{flag: True}) + for frame in range(anim.n_frames): + anim.draw_frame(frame) + anim.figure.canvas.draw() + + +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('fmt', ['-o', '-', 'o']) +def test_serial_hue_trail_is_empty_where_the_plain_trail_is(ndims, fmt): + """A serial trail with ``hue=`` kept the geometry of the frame drawn + before: after a middle frame, frame 0 and the last frame (where every + trail is cleared) still showed it.""" + anim = hyp.plot([X[:, :ndims], Y[:, :ndims]], fmt, hue=[HUE, HUE], + animate='serial', chemtrails=True, duration=2, + frame_rate=10, show=False) + ax = anim.figure.axes[0] + trails = [coll for coll in ax.collections + if getattr(coll, '_hyp_trace_role', None) == 'trail'] + assert len(trails) == 2 + + def drawn(coll): + if isinstance(coll, PathCollection): + return _n_points(coll, ndims) + return len(coll._segments3d if ndims == 3 else coll.get_segments()) + + def markers(): + return [_n_points(coll, ndims) + for coll in _marker_scatters(ax).values() + if coll._hyp_markers_of[1] == 'trail'] + + anim.draw_frame(5) + assert drawn(trails[0]) > 0 + for frame in (0, anim.n_frames - 1): + anim.draw_frame(frame) + assert [drawn(coll) for coll in trails] == [0, 0], frame + assert not any(markers()), frame + + +@pytest.mark.parametrize('fmt', ['-', 'o', '-o']) +def test_hue_trail_opacity_is_trail_alpha_times_the_dataset_alpha(fmt): + """``alpha=0.2, trail_alpha=0.5``: the trail was drawn at 0.5 (more + opaque than its head) instead of 0.1, and an animated hue-colored + LINE ignored ``alpha=`` altogether.""" + anim = hyp.plot(X, fmt, hue=HUE, animate=True, chemtrails=True, + alpha=0.2, trail_alpha=0.5, duration=2, frame_rate=10, + show=False) + anim.draw_frame(15) + ax = anim.figure.axes[0] + roles = _roles(ax) + assert roles['head'].get_alpha() == pytest.approx(0.2) + assert roles['trail'].get_alpha() == pytest.approx(0.1) + for coll in _marker_scatters(ax).values(): + want = 0.2 if coll._hyp_markers_of[1] == 'head' else 0.1 + assert coll.get_alpha() == pytest.approx(want) + # the same call without hue= + plain = hyp.plot(X, fmt, animate=True, chemtrails=True, alpha=0.2, + trail_alpha=0.5, duration=2, frame_rate=10, show=False) + assert [line.get_alpha() for line in plain.figure.axes[0].lines[:2]] \ + == pytest.approx([0.2, 0.1]) + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_mixed_formats_with_hue_animate_each_dataset_as_asked(ndims): + """``['-', 'o']`` + ``hue=``: the line dataset was drawn as markers + as soon as one dataset had no line.""" + anim = hyp.plot([X[:, :ndims], Y[:, :ndims]], ['-', 'o'], + hue=[HUE, HUE], animate=True, chemtrails=True, + tail_duration=1, duration=4, frame_rate=10, show=False) + anim.draw_frame(25) + kinds = {(coll._hyp_trace_index, coll._hyp_trace_role): + isinstance(coll, PathCollection) + for coll in anim.figure.axes[0].collections + if getattr(coll, '_hyp_trace_role', None)} + assert kinds == {(0, 'head'): False, (0, 'trail'): False, + (1, 'head'): True, (1, 'trail'): True} + + +def test_mixed_formats_with_hue_static(): + fig = hyp.plot([X, Y], ['-', 's'], hue=[HUE, HUE], show=False) + ax = fig.axes[0] + lines = [coll for coll in ax.collections + if getattr(coll, '_hyp_trace_index', None) is not None] + scatters = [coll for coll in ax.collections + if isinstance(coll, PathCollection)] + assert [coll._hyp_trace_index for coll in lines] == [0] + assert len(scatters) == 1 + assert len(np.asarray(scatters[0]._offsets3d[0])) == len(Y) + # the dataset's own glyph, a square (four corners), not the default + square = matplotlib.markers.MarkerStyle('s') + np.testing.assert_allclose( + scatters[0].get_paths()[0].vertices, + square.get_path().transformed(square.get_transform()).vertices) + + +@pytest.mark.parametrize('hue', [None, 'continuous']) +def test_head_marker_fades_with_its_dataset(hue): + """`dataset_fade=` + `head_marker=`: with a continuous ``hue=`` the + finished dataset's line faded and its head marker stayed opaque.""" + anim = hyp.plot([X, Y], '-', hue=None if hue is None else [HUE, HUE], + animate='serial', head_marker='o', duration=2, + frame_rate=10, dataset_fade={'floor': 0.1, 'decay': 0.5}, + show=False) + anim.draw_frame(anim.n_frames - 2) + ax = anim.figure.axes[0] + markers = sorted((line for line in ax.lines + if getattr(line, '_hyp_trace_role', None) + == 'head_marker'), key=lambda m: m._hyp_trace_index) + assert [marker.get_alpha() for marker in markers] \ + == pytest.approx([0.55, 1.0]) + if hue is not None: + heads = sorted((coll for coll in ax.collections + if getattr(coll, '_hyp_trace_role', None) == 'head'), + key=lambda c: c._hyp_trace_index) + assert [coll.get_alpha() for coll in heads] \ + == pytest.approx([0.55, 1.0]) + + +def test_dataset_fade_reaches_the_right_trail_with_a_flag_list(): + """``chemtrails=[False, True]``: the one trail belongs to dataset 1, + and was faded as dataset 0's (it is the first trail).""" + anim = hyp.plot([X, Y], '-', animate='serial', duration=2, + frame_rate=10, chemtrails=[False, True], + dataset_fade={'floor': 0.1, 'decay': 0.5}, show=False) + anim.draw_frame(anim.n_frames - 4) # dataset 1 being revealed + ax = anim.figure.axes[0] + trail = [line for line in ax.lines + if getattr(line, '_hyp_trace_role', None) == 'trail'] + assert [line._hyp_trace_index for line in trail] == [1] + assert [line.get_alpha() for line in ax.lines[:2]] \ + == pytest.approx([0.55, 1.0]) + assert trail[0].get_alpha() == pytest.approx(1.0) + + +# -------------------------------------------------------------------------- +# C. arguments +# -------------------------------------------------------------------------- + +def test_tail_linewidth_on_a_markers_only_format_warns(): + with pytest.warns(UserWarning, match='tail_linewidth=.*no dataset.*line'): + hyp.plot(X, 'o', animate=True, tail_linewidth=5, duration=1, + frame_rate=10, show=False) + with warnings.catch_warnings(): + warnings.simplefilter('error') + # one dataset with a line is enough + hyp.plot([X, Y], ['-', 'o'], animate=True, tail_linewidth=5, + duration=1, frame_rate=10, show=False) + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_tail_linewidth_does_not_widen_a_spinning_or_static_line(ndims): + """``animate='spin'`` warned that `tail_linewidth=` is ignored and + drew the whole line at that width.""" + if ndims == 3: + with pytest.warns(UserWarning, match='ignoring tail_linewidth'): + anim = hyp.plot(X, '-', animate='spin', linewidth=1, + tail_linewidth=10, duration=1, frame_rate=10, + show=False) + anim.draw_frame(3) + assert anim.figure.axes[0].lines[0].get_linewidth() == 1.0 + with pytest.warns(UserWarning, match='tail_linewidth only affects'): + fig = hyp.plot(X[:, :ndims], '-', linewidth=1, tail_linewidth=10, + show=False) + assert fig.axes[0].lines[0].get_linewidth() == 1.0 + + +BAD_HEAD_MARKERS = [ + ({'size': -3}, "head_marker\\['size'\\]"), + ({'size': 0}, "head_marker\\['size'\\]"), + ({'size': float('nan')}, "head_marker\\['size'\\]"), + ({'size': 'big'}, "head_marker\\['size'\\]"), + ({'markersize': -1}, "head_marker\\['markersize'\\]"), + ({'color': 'notacolor'}, "head_marker\\['color'\\]"), + ({'edgecolor': 'nope'}, "head_marker\\['edgecolor'\\]"), + ({'alpha': 2}, "head_marker\\['alpha'\\]"), + ({'alpha': 'half'}, "head_marker\\['alpha'\\]"), + ({'edgewidth': -1}, "head_marker\\['edgewidth'\\]"), + ({'fillstyle': 'striped'}, "head_marker\\['fillstyle'\\]"), + ({'zorder': 'top'}, "head_marker\\['zorder'\\]"), +] + + +@pytest.mark.parametrize('spec, match', BAD_HEAD_MARKERS) +def test_head_marker_values_are_checked_by_name(spec, match): + with pytest.raises(ValueError, match=match): + hyp.plot(X, '-', animate=True, head_marker=spec, duration=1, + frame_rate=10, show=False) + + +def test_good_head_marker_values_still_draw(): + anim = hyp.plot(X, '-', animate=True, duration=1, frame_rate=10, + head_marker={'marker': 'D', 'size': 9.5, 'color': 'k', + 'edgecolor': (1, 1, 1), 'edgewidth': 0, + 'alpha': 1, 'fillstyle': 'full', + 'zorder': 9}, show=False) + marker = [line for line in anim.figure.axes[0].lines + if getattr(line, '_hyp_trace_role', None) == 'head_marker'][0] + assert marker.get_markersize() == 9.5 and marker.get_marker() == 'D' + + +BAD_TEXT_STYLES = [ + ({'size': -1}, 'size'), ({'size': 0}, 'size'), + ({'size': float('nan')}, 'size'), ({'size': 'huge'}, 'size'), + ({'fontsize': -2}, 'fontsize'), ({'weight': 'heavyish'}, 'weight'), + ({'weight': 2000}, 'weight'), ({'style': 'slanted'}, 'style'), + ({'family': 7}, 'family'), ({'color': 'notacolor'}, 'color'), + ({'alpha': 3}, 'alpha'), ({'linespacing': 0}, 'linespacing'), +] + + +@pytest.mark.parametrize('style, key', BAD_TEXT_STYLES) +@pytest.mark.parametrize('name', ['caption_kwargs', 'suptitle_kwargs']) +def test_figure_text_values_are_checked_by_name(name, style, key): + text = name.split('_')[0] + with pytest.raises(ValueError, match=f"{name}\\['{key}'\\] must be"): + hyp.plot(X, '-', show=False, **{text: 'Some text', name: style}) + + +@pytest.mark.parametrize('style, key', [ + ({'size': -3}, 'size'), ({'size': 'huge'}, 'size'), + ({'color': 'notacolor'}, 'color'), ({'alpha': 3}, 'alpha')]) +def test_title_kwargs_values_are_checked_by_name(style, key): + with pytest.raises(ValueError, match=f"title_kwargs\\['{key}'\\] must be"): + hyp.plot(X, '-', title='A title', title_kwargs=style, show=False) + + +def test_good_text_styles_still_draw(): + fig = hyp.plot(X, '-', show=False, title='A title', + title_kwargs={'size': 'x-large', 'weight': 600}, + caption='A caption', suptitle='A heading', + caption_kwargs={'size': 9, 'weight': 'bold', + 'style': 'italic', 'alpha': 0.5, + 'color': '#444444', 'linespacing': 1.1, + 'family': ['DejaVu Sans']}, + suptitle_kwargs={'size': 'large', 'color': (0, 0, 0)}) + caption = fig.findobj(lambda a: a.get_gid() == CAPTION_GID)[0] + assert caption.get_fontsize() == 9 and caption.get_alpha() == 0.5 + + +def test_suptitle_bytes_are_decoded_like_a_caption(): + fig = hyp.plot(X, '-', suptitle=b'In bytes', caption=b'Also bytes', + show=False) + assert fig.findobj(lambda a: a.get_gid() == SUPTITLE_GID)[ + 0].get_text() == 'In bytes' + assert fig.findobj(lambda a: a.get_gid() == CAPTION_GID)[ + 0].get_text() == 'Also bytes' + + +def test_static_plotly_ignores_the_animation_styling_with_a_warning(): + """As `chemtrails=` on a static plot: a warning, on either backend. + An ANIMATED plotly plot raises (the docstring said every plotly plot + does).""" + pytest.importorskip('plotly') + for kwargs in ({'head_marker': 'o'}, {'tail_linewidth': 3}): + name = next(iter(kwargs)) + with pytest.warns(UserWarning, match=f'{name} only affects ANIMATED'): + hyp.plot(X, '-', backend='plotly', show=False, **kwargs) + with pytest.raises(NotImplementedError, match=name): + hyp.plot(X, '-', backend='plotly', animate=True, show=False, + **kwargs) + with pytest.warns(UserWarning, match='chemtrails only affect ANIMATED'): + hyp.plot(X, '-', backend='plotly', chemtrails=True, show=False) + with pytest.warns(UserWarning, + match='head_marker/tail_linewidth only affect '): + hyp.plot(X, '-', head_marker='o', tail_linewidth=2, show=False) + + +def test_hold_in_a_gif_keeps_the_time_and_merges_identical_frames(tmp_path): + """What the docstring says of a saved gif: the playing time is + ``duration + hold``; Pillow stores a run of identical frames as one + frame with the run's duration, so the file has fewer frames.""" + path = tmp_path / 'held.gif' + anim = hyp.plot(X, '-', animate=True, rotations=0, duration=1, + frame_rate=10, hold=1, show=False, save_path=str(path)) + assert anim.n_frames == 20 + with Image.open(path) as gif: + durations = [] + for k in range(gif.n_frames): + gif.seek(k) + durations.append(gif.info['duration']) + assert sum(durations) == 2000 + assert len(durations) == 10 + assert durations[-1] == 1100 and set(durations[:-1]) == {100} + + +def _hull_gap(points, box): + """Distance in px between the convex outline of `points` and the + rectangle `box` (0 when they touch or overlap).""" + from matplotlib.path import Path + from scipy.spatial import ConvexHull + hull = points[ConvexHull(points).vertices] + rect = np.array([[box.x0, box.y0], [box.x1, box.y0], + [box.x1, box.y1], [box.x0, box.y1]]) + if Path(hull).contains_points(rect).any() \ + or Path(rect).contains_points(hull).any(): + return 0.0 + + def point_segment(p, a, b): + d = b - a + t = np.clip((p - a) @ d / (d @ d), 0.0, 1.0) + return float(np.linalg.norm(p - (a + t * d))) + + best = np.inf + for i in range(len(hull)): + a, b = hull[i], hull[(i + 1) % len(hull)] + for j in range(4): + c, d = rect[j], rect[(j + 1) % 4] + best = min(best, point_segment(a, c, d), point_segment(b, c, d), + point_segment(c, a, b), point_segment(d, a, b)) + return best + + +@pytest.mark.parametrize('size', [(6.4, 4.8), (8, 8)]) +def test_cube_keeps_its_stated_margin_from_the_legend_on_every_frame(size): + """The changelog's number, measured with the real renderer on every + frame: the cube's outline stays about 2% of the canvas's SHORTER side + from the legend (at least 1.9%), and that far inside the canvas.""" + t = np.linspace(0, 4 * np.pi, 80) + a = np.c_[np.cos(t), np.sin(t), t / 6] + b = np.c_[np.cos(t) * .5 + 2, np.sin(t) * .5, -t / 6] + anim = hyp.plot([a, b], '-', animate=True, legend=['A', 'B'], size=size, + duration=3, frame_rate=20, show=False) + fig = anim.figure + ax = fig.axes[0] + short = min(fig.bbox.width, fig.bbox.height) + gaps, edges = [], [] + for frame in range(anim.n_frames): + anim.draw_frame(frame) + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + corners = np.array(list(itertools.product( + ax.get_xlim3d(), ax.get_ylim3d(), ax.get_zlim3d()))) + xs, ys, _ = proj3d.proj_transform(*corners.T, ax.get_proj()) + px = ax.transData.transform(np.column_stack([xs, ys])) + gaps.append(_hull_gap( + px, ax.get_legend().get_window_extent(renderer))) + edges.append(min(px[:, 0].min(), fig.bbox.width - px[:, 0].max(), + px[:, 1].min(), fig.bbox.height - px[:, 1].max())) + assert min(gaps) >= 0.019 * short, min(gaps) / short + assert min(gaps) <= 0.03 * short # ...and no more room + assert min(edges) >= 0.019 * short, min(edges) / short + + +def _extent(fig, gid): + return fig.findobj(lambda a: a.get_gid() == gid)[0].get_window_extent( + fig.canvas.get_renderer()) + + +@pytest.mark.parametrize('kwargs', [{}, {'ndims': 2}, {'panels': True}], + ids=['3d', '2d', 'grid']) +def test_suptitle_clears_a_top_caption_that_grows(kwargs): + """The suptitle was placed against frame 0's one-line caption and + the four-line caption of the later frames ran into it.""" + def caption(ctx): + return 'short' if ctx.frame == 0 else 'one\ntwo\nthree\nfour' + + data = [X, Y] if kwargs.get('panels') else X + anim = hyp.plot(data, '-', animate=True, caption=caption, + caption_kwargs={'position': 'top'}, suptitle='Heading', + duration=2, frame_rate=10, show=False, **kwargs) + fig = anim.figure + heights = set() + for frame in (0, 1, 10, anim.n_frames - 1): + anim.draw_frame(frame) + fig.canvas.draw() + caption_box = _extent(fig, CAPTION_GID) + title_box = _extent(fig, SUPTITLE_GID) + heights.add(round(caption_box.height)) + assert caption_box.y1 < title_box.y0, frame + assert title_box.y1 <= fig.bbox.height + assert len(heights) == 2 # it really did grow diff --git a/tests/test_review_round2_1_2_1.py b/tests/test_review_round2_1_2_1.py new file mode 100644 index 00000000..5c52ecf2 --- /dev/null +++ b/tests/test_review_round2_1_2_1.py @@ -0,0 +1,1106 @@ +"""1.2.1 review round 2: what a second pair of reviews found in the GH #299 +animation arguments and the GH #297 layout fixes, and what was found next +to each fix. + +A. Values inside the styling dicts (``title_kwargs=``, + ``caption_kwargs=``, ``suptitle_kwargs=``, ``head_marker=``): + matplotlib decides what a property accepts. +B. Observation labels: the labels of every call into one axes, an axes + that was cleared, one arrangement at every dpi and in every file + format, a 3-D plot turned with the mouse, no work on a redraw, no + draw to place an animation's labels. +C. A measurement leaves the figure its own canvas. +D. Warnings about ignored styling in ``panels=`` grids; per-dataset trail + lists with a categorical ``hue=``; ``labels=`` with ``animate='morph'``. +E. Continuous ``hue=`` markers wear the dataset's marker styling, and a + trace's second artist follows the one a callback is handed. +F. A per-frame caption or title is never clipped, whichever frame it is + tallest on. + +Real figures and real frames, rendered headless. Nothing is mocked (two +tests COUNT the draws matplotlib makes, through a wrapper that calls the +real method), and no assertion depends on a font's absolute metrics. +""" +import io +import os +import subprocess +import sys +import textwrap +import warnings + +import matplotlib +matplotlib.use('Agg') + +import matplotlib.pyplot as plt # noqa: E402 +import matplotlib.text as mtext # noqa: E402 +import numpy as np # noqa: E402 +import pytest # noqa: E402 +from matplotlib.backend_bases import MouseButton, MouseEvent # noqa: E402 +from matplotlib.backends.backend_agg import FigureCanvasAgg # noqa: E402 +from matplotlib.collections import PathCollection # noqa: E402 +from matplotlib.figure import Figure # noqa: E402 + +import hypertools as hyp # noqa: E402 +from hypertools.plot.matplotlib_backend import ( # noqa: E402 + LABEL_OFFSET_PT, _LabelDeclutter, forget_label_tracks, label_tracks) +from hypertools.plot.plot import CAPTION_GID, SUPTITLE_GID # noqa: E402 + + +def _walk(seed, rows=40, cols=3): + return np.random.default_rng(seed).normal(size=(rows, cols)).cumsum(0) + + +X, Y, Z = _walk(0), _walk(1), _walk(2) +HUE = np.linspace(0.0, 1.0, len(X)) +HOME = (-LABEL_OFFSET_PT, LABEL_OFFSET_PT) + + +@pytest.fixture(autouse=True) +def _close_figures(): + yield + plt.close('all') + + +def _figure_of(result): + return getattr(result, 'figure', result) + + +# -------------------------------------------------------------------------- +# A. values inside the styling dicts: matplotlib decides +# -------------------------------------------------------------------------- + +#: values matplotlib accepts and 1.2.0 drew, which the first 1.2.1 check +#: refused +ACCEPTED_TEXT_STYLES = [ + {'size': None}, {'alpha': None}, {'size': '12'}, {'weight': '700'}, + {'alpha': True}, {'family': None}, {'weight': None}, {'style': None}, + {'size': 'large'}, {'size': np.float32(13)}, {'weight': 550}, + {'family': ['serif', 'DejaVu Sans']}, {'color': ('red', 0.5)}, + {'color': '0.5'}, {'size': 0.5}, +] + + +@pytest.mark.parametrize('style', ACCEPTED_TEXT_STYLES) +@pytest.mark.parametrize('animate', [False, True]) +def test_title_kwargs_take_what_matplotlib_takes(style, animate): + extra = dict(animate=True, duration=1, frame_rate=5) if animate else {} + result = hyp.plot(X, '-', title='A title', title_kwargs=style, + show=False, **extra) + fig = _figure_of(result) + fig.canvas.draw() + assert fig.axes[0].get_title() == 'A title' + + +@pytest.mark.parametrize('style', ACCEPTED_TEXT_STYLES + [{'color': None}]) +@pytest.mark.parametrize('name', ['caption_kwargs', 'suptitle_kwargs']) +def test_figure_text_kwargs_take_what_matplotlib_takes(name, style): + text = name.split('_')[0] + fig = hyp.plot(X, '-', show=False, **{text: 'Some text', name: style}) + fig.canvas.draw() + gid = CAPTION_GID if text == 'caption' else SUPTITLE_GID + assert fig.findobj(lambda a: a.get_gid() == gid)[0].get_text() \ + == 'Some text' + + +def test_a_size_given_as_a_string_is_that_size(): + fig = hyp.plot(X, '-', show=False, title='T', title_kwargs={'size': '17'}, + caption='C', caption_kwargs={'size': '9', 'weight': '700'}) + assert fig.axes[0].title.get_fontsize() == 17 + caption = fig.findobj(lambda a: a.get_gid() == CAPTION_GID)[0] + assert caption.get_fontsize() == 9 and caption.get_fontweight() == 700 + + +def test_none_in_a_figure_text_dict_is_the_default(): + plain = hyp.plot(X, '-', show=False, caption='C', suptitle='S') + styled = hyp.plot(X, '-', show=False, caption='C', suptitle='S', + caption_kwargs={'size': None, 'color': None, + 'weight': None, 'linespacing': None, + 'loc': None}, + suptitle_kwargs={'size': None, 'family': None}) + for gid in (CAPTION_GID, SUPTITLE_GID): + one, other = (fig.findobj(lambda a: a.get_gid() == gid)[0] + for fig in (plain, styled)) + assert one.get_fontsize() == other.get_fontsize() + assert one.get_color() == other.get_color() + assert one.get_fontweight() == other.get_fontweight() + assert one.get_position() == other.get_position() + + +def test_title_kwargs_agree_with_matplotlib_over_many_values(): + """Whatever matplotlib's own `Text` takes for a property, the title + takes; whatever it refuses is refused with the argument and key + named. The only values refused beyond matplotlib's are sizes and + line spacings that are not positive and finite.""" + nan = float('nan') + values = { + 'size': [None, 12, '12', '12.5', 'x-small', 'smaller', True, 0.5, + 40, 'huge', 'bogus', [12]], + 'weight': [None, 'bold', 700, '700', 0, 1000, 1001, -1, True, + 'bogus', nan, 'roman'], + 'style': [None, 'italic', 'oblique', 'bogus', 3], + 'family': [None, 'serif', ['serif'], ('serif',)], + 'color': ['red', 'C1', '#ff000080', (1, 0, 0, .5), ('red', .5), + '0.5', 'bogus', None, 0.5, (1, 2, 3)], + 'alpha': [None, 0, 1, .5, True, False, '0.5', 2, -1, nan], + 'variant': [None, 'small-caps', 'bogus'], + 'stretch': [None, 'condensed', 500, 'bogus', 1001], + 'rotation': [None, 30, 'vertical', 'bogus'], + 'backgroundcolor': ['yellow', 'bogus'], + 'ha': ['left', 'bogus'], 'va': ['top', 'bogus'], + 'wrap': [True, False], + } + full = {'size': 'fontsize', 'weight': 'fontweight', 'style': 'fontstyle', + 'family': 'fontfamily', 'variant': 'fontvariant', + 'stretch': 'fontstretch'} + checked = 0 + for key, candidates in values.items(): + for value in candidates: + try: + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + mtext.Text().update({full.get(key, key): value}) + accepted = True + except Exception: + accepted = False + if accepted: + fig = hyp.plot(X, '-', title='A title', + title_kwargs={key: value}, show=False) + fig.canvas.draw() + assert fig.axes[0].get_title() == 'A title', (key, value) + else: + with pytest.raises(ValueError, match=( + f"title_kwargs\\['{key}'\\] must be")): + hyp.plot(X, '-', title='A title', + title_kwargs={key: value}, show=False) + plt.close('all') + checked += 1 + assert checked > 60 + + +@pytest.mark.parametrize('style, key', [ + ({'size': -3}, 'size'), ({'size': 0}, 'size'), + ({'size': float('nan')}, 'size'), ({'size': '-3'}, 'size'), + ({'size': float('inf')}, 'size'), + ({'size': '0'}, 'size'), ({'size': False}, 'size'), + ({'linespacing': 0}, 'linespacing'), ({'color': 'auto'}, 'color'), + ({'family': 7}, 'family')]) +@pytest.mark.parametrize('name', ['title_kwargs', 'caption_kwargs', + 'suptitle_kwargs']) +def test_what_draws_nothing_readable_is_still_refused_by_name( + name, style, key): + text = name.split('_')[0] + with pytest.raises(ValueError, match=f"{name}\\['{key}'\\] must be"): + hyp.plot(X, '-', show=False, **{text: 'Some text', name: style}) + + +def _head_marker(anim): + return [line for line in anim.figure.axes[0].lines + if getattr(line, '_hyp_trace_role', None) == 'head_marker'] + + +@pytest.mark.parametrize('spec', [ + {'color': None}, {'size': None}, {'alpha': None}, {'edgecolor': None}, + {'edgewidth': None}, {'fillstyle': None}, {'zorder': None}, + {'marker': None}, {'edgecolor': 'auto'}, {'alpha': True}, + {'size': '9'}]) +def test_head_marker_dict_takes_what_matplotlib_takes(spec): + anim = hyp.plot(X, '-', animate=True, head_marker=spec, duration=1, + frame_rate=10, show=False) + anim.draw_frame(4) + (marker,) = _head_marker(anim) + assert marker.get_marker() == 'o' + line = anim.figure.axes[0].lines[0] + if spec.get('color', 0) is None: + # None is "the default": the dataset's color, not the next color + # of the axes' cycle + assert matplotlib.colors.same_color(marker.get_color(), + line.get_color()) + if spec.get('size') == '9': + assert marker.get_markersize() == 9 + + +@pytest.mark.parametrize('spec', [{'marker': True}, True, np.True_]) +def test_head_marker_true_is_a_circle_wherever_it_is_written(spec): + """`{'marker': True}` drew matplotlib's marker number 1, a tick.""" + anim = hyp.plot(X, '-', animate=True, head_marker=spec, duration=1, + frame_rate=10, show=False) + (marker,) = _head_marker(anim) + assert marker.get_marker() == 'o' + + +@pytest.mark.parametrize('spec', [{'marker': False}, False, np.False_]) +def test_head_marker_false_is_no_marker_wherever_it_is_written(spec): + anim = hyp.plot(X, '-', animate=True, head_marker=spec, duration=1, + frame_rate=10, show=False) + assert _head_marker(anim) == [] + + +TRIANGLE = np.array([[0, 1], [-1, -1], [1, -1]]) + + +@pytest.mark.parametrize('spec', [ + TRIANGLE, {'marker': TRIANGLE}, TRIANGLE.tolist(), (5, 1), '$A$'], + ids=['array', 'array in dict', 'list', 'tuple', 'mathtext']) +def test_head_marker_takes_every_kind_of_matplotlib_marker(spec): + """A marker given as an array of vertices failed with "needs a + matplotlib marker" (the truth value of an array).""" + anim = hyp.plot(X, '-', animate=True, head_marker=spec, duration=1, + frame_rate=10, show=False) + anim.draw_frame(5) + anim.figure.canvas.draw() + (marker,) = _head_marker(anim) + assert len(marker.get_xdata()) == 1 + + +@pytest.mark.parametrize('spec, match', [ + ({'edgecolor': 'bogus'}, "head_marker\\['edgecolor'\\]"), + ({'color': 'auto'}, "head_marker\\['color'\\]"), + ({'size': '-3'}, "head_marker\\['size'\\]"), + (np.array([1.0, 2.0, 3.0]), 'head_marker= needs a matplotlib marker'), + ('', 'head_marker= needs a matplotlib marker')]) +def test_bad_head_markers_are_refused_by_name(spec, match): + with pytest.raises(ValueError, match=match): + hyp.plot(X, '-', animate=True, head_marker=spec, duration=1, + frame_rate=10, show=False) + + +# -------------------------------------------------------------------------- +# B. observation labels +# -------------------------------------------------------------------------- + +def _entries(ax): + return [entry for entry in ax._hyp_labels_and_points + if entry[0].axes is ax] + + +def _overlapping_pairs(fig, labels): + """How many pairs of the label boxes overlap, as they were drawn.""" + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + boxes = [label.get_bbox_patch().get_window_extent(renderer) + for label in labels if label.get_visible()] + count = 0 + for i, one in enumerate(boxes): + for other in boxes[i + 1:]: + if (min(one.x1, other.x1) - max(one.x0, other.x0) > 0.5 + and min(one.y1, other.y1) - max(one.y0, other.y0) > 0.5): + count += 1 + return count + + +def _places(labels): + return [tuple(np.round(label.xyann, 3)) for label in labels] + + +def _two_calls(ndims): + rng = np.random.default_rng(0) + first = rng.normal(size=(6, ndims)) + second = np.array([[0, 0], [.02, .01], [.04, 0], [.01, .03], + [3, 3], [-3, -3.]]) + if ndims == 3: + second = np.column_stack([second, rng.normal(size=6) * .01]) + return first, second + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_two_labeled_calls_into_one_axes_are_kept_off_each_other(ndims): + """The second call's list replaced the first's on the axes, so only + the last call's labels were ever moved.""" + first, second = _two_calls(ndims) + fig, ax = plt.subplots( + subplot_kw={'projection': '3d'} if ndims == 3 else {}) + hyp.plot(first, 'o', labels=[f'first {i}' for i in range(6)], ax=ax, + show=False) + hyp.plot(second, 'o', labels=[f'second {i}' for i in range(6)], ax=ax, + show=False) + texts = [entry[0].get_text() for entry in _entries(ax)] + assert texts == [f'first {i}' for i in range(6)] + [ + f'second {i}' for i in range(6)] + labels = [entry[0] for entry in _entries(ax)] + assert _overlapping_pairs(fig, labels) == 0 + # ...as one call with the second call's data arranges them + single = hyp.plot(second, 'o', labels=[f'second {i}' for i in range(6)], + show=False) + assert _overlapping_pairs( + single, [entry[0] for entry in _entries(single.axes[0])]) == 0 + + +def test_two_labeled_calls_each_answer_their_own_mouse_events(): + """Each call still hides and restores ITS labels on a mouse press.""" + first, second = _two_calls(3) + fig, ax = plt.subplots(subplot_kw={'projection': '3d'}) + hyp.plot(first, 'o', labels=list('abcdef'), ax=ax, show=False) + hyp.plot(second, 'o', labels=list('uvwxyz'), ax=ax, show=False) + fig.canvas.draw() + labels = [entry[0] for entry in _entries(ax)] + x, y = ax.bbox.x0 + ax.bbox.width / 2, ax.bbox.y0 + ax.bbox.height / 2 + fig.canvas.callbacks.process('button_press_event', MouseEvent( + 'button_press_event', fig.canvas, x, y, button=MouseButton.LEFT)) + assert not any(label.get_visible() for label in labels) + fig.canvas.callbacks.process('button_release_event', MouseEvent( + 'button_release_event', fig.canvas, x, y, button=MouseButton.LEFT)) + assert all(label.get_visible() for label in labels) + + +def _crowded(n=30, ndims=3, seed=1): + rng = np.random.default_rng(seed) + x = rng.normal(size=(n, ndims)) + crowd = slice(n // 3, 2 * n // 3) + x[crowd] = x[n // 3] + rng.normal( + scale=.03, size=(len(x[crowd]), ndims)) + return x, [f'label {i}' for i in range(n)] + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_a_cleared_axes_declutters_its_new_labels(ndims): + """`ax.clear()` removed the declutter artist from the axes and left + the attribute that said it was there, so it was never put back.""" + x, names = _crowded(ndims=ndims) + fig, ax = plt.subplots( + subplot_kw={'projection': '3d'} if ndims == 3 else {}) + hyp.plot(x, 'o', labels=names, ax=ax, show=False) + fig.canvas.draw() + ax.clear() + hyp.plot(x[::-1], 'o', labels=names, ax=ax, show=False) + watchers = [child for child in ax.get_children() + if isinstance(child, _LabelDeclutter)] + assert len(watchers) == 1 + assert len(_entries(ax)) == len(names) == len(ax.texts) + fig.canvas.draw() + labels = [entry[0] for entry in _entries(ax)] + assert sum(place != HOME for place in _places(labels)) >= 3 + # the same arrangement as the same call into an axes never used + fresh_fig, fresh_ax = plt.subplots( + subplot_kw={'projection': '3d'} if ndims == 3 else {}) + hyp.plot(x[::-1], 'o', labels=names, ax=fresh_ax, show=False) + fresh_fig.canvas.draw() + assert _places(labels) == _places( + [entry[0] for entry in _entries(fresh_ax)]) + + +def test_an_axes_reused_after_an_animation_places_labels_again(): + """An animation's hold on its labels (since review round 5 its + table, `label_tracks`) stayed on the axes after `ax.clear()`: a + static plot's labels were never moved.""" + x, names = _crowded() + anim = hyp.plot(x, 'o', labels=names, animate='spin', duration=1, + frame_rate=5, show=False) + fig = anim.figure + ax = fig.axes[0] + anim.draw_frame(2) + assert label_tracks(ax) is not None + ax.clear() + hyp.plot(x, 'o', labels=names, ax=ax, show=False) + assert label_tracks(ax) is None + fig.canvas.draw() + labels = [entry[0] for entry in _entries(ax)] + assert len(labels) == len(names) + assert sum(place != HOME for place in _places(labels)) >= 3 + + +def test_labels_added_to_an_animations_axes_join_its_table(): + """Without a clear, the animation's labels are still there: the new + ones are placed with them, in the animation's one table (rewritten + in review round 5 from the test that all of them hold one place), so + every frame shows all 24 the same way whenever it is drawn.""" + x, names = _crowded(n=12) + anim = hyp.plot(x, 'o', labels=names, animate='spin', duration=1, + frame_rate=5, show=False) + ax = anim.figure.axes[0] + hyp.plot(x + 0.01, 'o', labels=[name.upper() for name in names], ax=ax, + show=False) + tracks = label_tracks(ax) + labels = [entry[0] for entry in _entries(ax)] + assert len(labels) == 24 + assert [ref() for ref in tracks['labels']] == labels + home = tracks['places'][0].min() + assert (tracks['places'] != home).any(axis=0).sum() >= 3 + seen = {} + for frame in (3, 1, 4, 1, 3): + anim.draw_frame(frame) + anim.figure.canvas.draw() + assert seen.setdefault(frame, _places(labels)) == _places(labels) + assert label_tracks(ax) is tracks + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_the_arrangement_is_the_same_at_every_dpi_and_in_every_format( + ndims, tmp_path): + """The placement was made from the renderer's pixels: 10 of 30 labels + sat elsewhere at dpi 101 than at dpi 100, and a PDF differed again.""" + x, names = _crowded(ndims=ndims) + + def arrangement(save): + fig = hyp.plot(x, 'o', labels=names, show=False) + save(fig) + places = _places([entry[0] for entry in _entries(fig.axes[0])]) + plt.close(fig) + return places + + reference = arrangement(lambda fig: fig.canvas.draw()) + assert sum(place != HOME for place in reference) >= 3 + for dpi in (72, 100, 101, 120, 150, 300): + assert arrangement(lambda fig: fig.savefig( + io.BytesIO(), format='png', dpi=dpi)) == reference, dpi + for fmt in ('pdf', 'svg'): + assert arrangement(lambda fig: fig.savefig( + tmp_path / f'labels.{fmt}')) == reference, fmt + # the screen first, then files of the same figure + fig = hyp.plot(x, 'o', labels=names, show=False) + labels = [entry[0] for entry in _entries(fig.axes[0])] + fig.canvas.draw() + for dpi in (300, 72): + fig.savefig(io.BytesIO(), format='png', dpi=dpi) + assert _places(labels) == reference + fig.savefig(io.BytesIO(), format='png', bbox_inches='tight') + assert _places(labels) == reference + + +def test_a_resized_figure_may_be_arranged_again_and_stays_on_the_canvas(): + x, names = _crowded(ndims=2) + fig = hyp.plot(x, 'o', labels=names, show=False) + labels = [entry[0] for entry in _entries(fig.axes[0])] + fig.canvas.draw() + before = _overlapping_pairs(fig, labels) + fig.set_size_inches(12, 9) + assert _overlapping_pairs(fig, labels) <= before + + +def _drag(fig, ax, steps=3, dx=0.3): + """Press, drag and release the left mouse button on `ax`, with real + mouse events, drawing as a window would.""" + x, y = ax.bbox.x0 + ax.bbox.width / 2, ax.bbox.y0 + ax.bbox.height / 2 + + def send(name, at): + fig.canvas.callbacks.process(name, MouseEvent( + name, fig.canvas, at, y, button=MouseButton.LEFT)) + + send('button_press_event', x) + during = [] + for step in range(1, steps + 1): + send('motion_notify_event', x + dx * step) + fig.canvas.draw() + during.append([entry[0].get_visible() for entry in _entries(ax)]) + send('button_release_event', x + dx * steps) + fig.canvas.draw() + return during + + +def test_turning_a_plot_with_the_mouse_keeps_the_labels_where_they_were(): + """A press hides the labels; the next draw sent every hidden label + back to its usual place, so on release the placement started over + and labels that were clear of each other changed place.""" + rng = np.random.default_rng(1) + x = rng.normal(size=(12, 3)) + x[4:9] = x[4] + rng.normal(scale=.03, size=(5, 3)) + fig = hyp.plot(x, 'o', labels=[f'label {i}' for i in range(12)], + show=False) + ax = fig.axes[0] + fig.canvas.draw() + labels = [entry[0] for entry in _entries(ax)] + before = _places(labels) + assert sum(place != HOME for place in before) >= 3 + azim = ax.azim + during = _drag(fig, ax) + assert ax.azim != azim # the plot really turned + assert not any(any(shown) for shown in during) # hidden while dragged + assert all(label.get_visible() for label in labels) + # a turn of less than a degree: no label's box was covered, so none + # of them has a reason to move + assert _places(labels) == before + + +def test_a_redraw_of_an_unchanged_figure_places_nothing_again(): + x, names = _crowded(n=60) + fig = hyp.plot(x, 'o', labels=names, show=False) + ax = fig.axes[0] + labels = [entry[0] for entry in _entries(ax)] + # `plot()` leaves the labels at their usual places: they are + # arranged for the finished figure, on its first draw + assert all(place == HOME for place in _places(labels)) + fig.canvas.draw() + answer = ax._hyp_label_answer + assert answer['settled'] + places = _places(labels) + assert sum(place != HOME for place in places) >= 3 + for _ in range(2): + fig.canvas.draw() + assert ax._hyp_label_answer is answer # not worked out again + assert _places(labels) == places + # the same call again: the same arrangement + again = hyp.plot(x, 'o', labels=names, show=False) + again.canvas.draw() + assert _places([entry[0] for entry in _entries(again.axes[0])]) == places + + +def test_labels_saved_by_plot_itself_are_arranged(tmp_path): + """`save_path=` writes the finished figure: its labels are not left + at their usual places because `plot()` is still running.""" + x, names = _crowded(ndims=2) + fig = hyp.plot(x, 'o', labels=names, show=False, + save_path=str(tmp_path / 'labels.png')) + labels = [entry[0] for entry in _entries(fig.axes[0])] + assert sum(place != HOME for place in _places(labels)) >= 3 + + +@pytest.fixture +def count_draws(monkeypatch): + """Count the draws of whole figures; every draw is really made.""" + drawn = [] + real_draw = Figure.draw + + def counting_draw(self, renderer, *args, **kwargs): + drawn.append(self) + return real_draw(self, renderer, *args, **kwargs) + + monkeypatch.setattr(Figure, 'draw', counting_draw) + return drawn + + +def test_placing_an_animations_labels_draws_nothing(count_draws): + """Placing an animation's labels rendered the whole figure (and + replaced the figure's canvas doing it). The table of review round 5 + (`solve_label_tracks`) is worked out without a draw too.""" + names = [f'a{i}' if i % 5 == 0 else None for i in range(len(X))] + counts = {} + for key, labels in (('plain', None), ('labeled', names)): + del count_draws[:] + hyp.plot(X, '-', animate=True, labels=labels, duration=1, + frame_rate=10, show=False) + counts[key] = len(count_draws) + # the one draw `labels=` adds is the one that creates the labels + assert counts['labeled'] - counts['plain'] <= 1 + + +def test_an_animated_grid_places_its_labels_without_a_draw_per_panel( + count_draws): + """A grid of N labeled panels rendered the whole grid N times to + place the labels.""" + data = [X, Y, Z, X + 1] + names = [f'a{i}' if i % 5 == 0 else None for i in range(len(X))] + counts = {} + for key, labels in (('plain', None), ('labeled', [names] * 4)): + del count_draws[:] + anim = hyp.plot(data, '-', animate=True, panels=(2, 2), + labels=labels, duration=1, frame_rate=10, show=False) + counts[key] = len(count_draws) + # (each panel's labels are created with one draw, as in a static grid) + assert counts['labeled'] - counts['plain'] <= len(data) + for ax in anim.figure.axes[:4]: + assert label_tracks(ax) is not None + + +def test_an_animations_labels_are_placed_as_a_draw_would_place_them(): + """The placement made without a draw is the one a draw of the same + state makes (rewritten in review round 5: the table's first row for + an animation that does not loop, placed frame by frame on its own, + against a real draw of frame 0 with the labels arranged as a static + figure's are).""" + from hypertools.plot.matplotlib_backend import ( + _LABEL_CANDIDATES, _label_place, _send_label_home, + solve_label_tracks) + x, names = _crowded() + anim = hyp.plot(x, 'o', labels=names, animate='spin', duration=1, + frame_rate=5, rotations=0.4, show=False) + ax = anim.figure.axes[0] + labels = [entry[0] for entry in _entries(ax)] + tracks = solve_label_tracks(ax, _independent=True) + tabled = [_LABEL_CANDIDATES[k] for k in tracks['places'][0]] + assert sum(place != _LABEL_CANDIDATES[tracks['places'][0].min()] + for place in tabled) >= 3 + anim.draw_frame(0) + # the same state, placed by a real draw + forget_label_tracks(ax) + for label in labels: + label._hyp_place = None + _send_label_home(label) + ax._hyp_label_answer = None + anim.figure.canvas.draw() + assert [_label_place(label) for label in labels] == tabled + + +# -------------------------------------------------------------------------- +# C. a measurement leaves the figure its own canvas +# -------------------------------------------------------------------------- + +class _WindowCanvas(FigureCanvasAgg): + """A canvas of its own class, standing in for a GUI window's.""" + + +CANVAS_CASES = { + 'legend': dict(legend=['a']), + 'legend outside': dict(legend=['a'], legend_kwargs={ + 'loc': 'center left', 'bbox_to_anchor': (1.02, 0.5)}), + 'colorbar': dict(hue=HUE, colorbar=True), + 'labels': dict(labels=[str(i) for i in range(len(X))]), + 'title': dict(title='A title'), +} + + +@pytest.mark.parametrize('case', CANVAS_CASES) +@pytest.mark.parametrize('ndims', [2, 3]) +def test_plot_leaves_a_callers_figure_on_its_own_canvas(case, ndims): + """A measurement draw attached a new Agg canvas and left it there: in + a window (macosx, QtAgg, TkAgg) the figure then updated a canvas + nobody saw.""" + fig = Figure() + canvas = _WindowCanvas(fig) + ax = fig.add_subplot(projection='3d' if ndims == 3 else None) + hyp.plot(X[:, :ndims], '-', ax=ax, show=False, **CANVAS_CASES[case]) + assert fig.canvas is canvas + + +@pytest.mark.parametrize('kwargs', [ + dict(legend=['a', 'b']), dict(panels=(1, 2)), + dict(animate=True, duration=1, frame_rate=10, + labels=[[str(i) for i in range(len(X))]] * 2), + dict(animate=True, duration=1, frame_rate=10, panels=(1, 2), + labels=[[str(i) for i in range(len(X))]] * 2)], + ids=['legend', 'panels', 'animated labels', 'animated labeled panels']) +def test_a_shown_figure_keeps_the_canvas_of_its_manager(kwargs): + """`show=True` leaves the figure with pyplot: its canvas is still the + one its figure manager (the window) owns.""" + result = hyp.plot([X, Y], '-', show=True, **kwargs) + fig = _figure_of(result) + assert fig.canvas.manager is not None + assert fig.canvas.manager.canvas is fig.canvas + assert plt.fignum_exists(fig.number) + + +def test_a_measurement_keeps_a_scaled_figures_original_dpi(): + """A new canvas overwrites `_original_dpi` with the current dpi, + which on a high-resolution display is the scaled one.""" + fig = Figure(dpi=100) + canvas = _WindowCanvas(fig) + ax = fig.add_subplot() + canvas._set_device_pixel_ratio(2) + assert fig.dpi == 200 and fig._original_dpi == 100 + from hypertools.plot.plot import _measurement_renderer + hyp.plot(X[:, :2], '-', ax=ax, legend=['a'], show=False) + renderer = _measurement_renderer(fig) + assert renderer is not canvas.get_renderer() + assert fig.canvas is canvas + assert fig.dpi == 200 and fig._original_dpi == 100 + + +def test_the_canvas_of_a_real_window_backend_survives_plot(): + """The same on a GUI backend, where one can be loaded (macOS).""" + script = textwrap.dedent(''' + import warnings + import matplotlib + matplotlib.use('macosx') + import matplotlib.pyplot as plt + from matplotlib._pylab_helpers import Gcf + import numpy as np + import hypertools as hyp + warnings.simplefilter('ignore') + plt.ioff() + x = np.random.default_rng(0).normal(size=(20, 3)).cumsum(0) + names = [str(i) for i in range(20)] + for kwargs in (dict(labels=names), dict(legend=['a']), + dict(animate=True, labels=names), + dict(animate=True, labels=names, ndims=2), + dict(animate=True, caption='A caption')): + result = hyp.plot(x, '-', show=True, **kwargs) + fig = getattr(result, 'figure', result) + (manager,) = Gcf.get_all_fig_managers() + assert type(fig.canvas).__name__ == 'FigureCanvasMac', kwargs + assert manager.canvas is fig.canvas, kwargs + plt.close('all') + print('CANVAS KEPT') + ''') + probe = subprocess.run( + [sys.executable, '-c', + "import matplotlib; matplotlib.use('macosx'); " + "import matplotlib.pyplot as plt; plt.figure()"], + capture_output=True, text=True, timeout=120) + if probe.returncode != 0: + pytest.skip('no macosx backend here: ' + probe.stderr[-200:]) + done = subprocess.run([sys.executable, '-c', script], capture_output=True, + text=True, timeout=300, env=dict(os.environ)) + assert done.returncode == 0, done.stderr[-2000:] + assert 'CANVAS KEPT' in done.stdout + + +# -------------------------------------------------------------------------- +# D. warnings in grids, per-dataset lists with hue, labels with morph +# -------------------------------------------------------------------------- + +def _warnings_of(*args, **kwargs): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + result = hyp.plot(*args, show=False, **kwargs) + return result, [str(w.message) for w in caught] + + +ANIMATED = dict(animate=True, duration=1, frame_rate=8) + + +@pytest.mark.parametrize('panels', [None, (1, 2)]) +def test_tail_linewidth_is_not_called_ignored_when_a_panel_draws_a_line( + panels): + extra = {'panels': panels} if panels else {} + anim, messages = _warnings_of([X, Y], ['-', 'o'], tail_linewidth=4, + linewidth=1, **ANIMATED, **extra) + assert not [m for m in messages if 'tail_linewidth' in m] + anim.draw_frame(4) + widths = [line.get_linewidth() for ax in anim.figure.axes + for line in ax.lines + if line.get_linestyle() == '-' and len(line.get_xdata())] + assert 4.0 in widths + + +@pytest.mark.parametrize('panels', [None, (1, 2)]) +@pytest.mark.parametrize('panel_fit', [None, 'independent']) +def test_trail_alpha_is_not_called_ignored_when_a_panel_draws_a_trail( + panels, panel_fit): + if panels is None and panel_fit is not None: + pytest.skip('panel_fit= belongs to panels=') + extra = {'panels': panels} if panels else {} + if panel_fit: + extra['panel_fit'] = panel_fit + _anim, messages = _warnings_of( + [X, Y], '-', trail_alpha=0.6, chemtrails=[True, False], + **ANIMATED, **extra) + assert not [m for m in messages if 'trail_alpha' in m] + + +@pytest.mark.parametrize('kwargs, fmt, text', [ + (dict(tail_linewidth=4), ['o', 'o'], 'tail_linewidth= sets the width'), + (dict(trail_alpha=0.6), '-', 'trail_alpha= sets the opacity'), + (dict(head_marker='o', animate='spin'), '-', 'no reveal head'), + (dict(head_marker='o', animate=False), '-', 'only affects ANIMATED')]) +@pytest.mark.parametrize('panels', [None, (1, 2)]) +def test_a_true_warning_is_given_once_for_the_whole_figure( + panels, kwargs, fmt, text): + extra = {'panels': panels} if panels else {} + call = dict(ANIMATED, **kwargs) + _result, messages = _warnings_of([X, Y], fmt, **call, **extra) + assert len([m for m in messages if text in m]) == 1, messages + + +CATEGORIES = [['a'] * 20 + ['b'] * 20, ['a'] * 40, ['c'] * 10 + ['a'] * 30] + + +def _trail_datasets(anim): + """Which drawn traces have a trail artist.""" + return sorted({line._hyp_trace_index for line in anim.figure.axes[0].lines + if getattr(line, '_hyp_trace_role', None) == 'trail'}) + + +@pytest.mark.parametrize('fmt', ['-', '-o']) +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('flag', ['chemtrails', 'precog', 'bullettime']) +def test_a_per_dataset_trail_list_is_matched_to_the_callers_datasets( + fmt, ndims, flag): + """A categorical hue splits three datasets into five runs, and the + three-entry list was refused: "3 entries but there are 5 datasets".""" + anim = hyp.plot([X, Y, Z], fmt, hue=CATEGORIES, ndims=ndims, + show=False, **ANIMATED, **{flag: [False, True, True]}) + anim.draw_frame(5) + # the runs: dataset 0 gives runs 0 and 1, dataset 1 run 2, dataset 2 + # runs 3 and 4; the trails are the runs of datasets 1 and 2 + assert _trail_datasets(anim) == [2, 3, 4] + + +def test_a_per_dataset_trail_list_with_cluster_and_on_plotly(): + anim = hyp.plot([X, Y, Z], '-', cluster='KMeans', n_clusters=2, + random_state=0, chemtrails=[False, False, True], + show=False, **ANIMATED) + owners = set(_trail_datasets(anim)) + assert owners and len(owners) < len(anim.figure.axes[0].lines) + pytest.importorskip('plotly') + fig = hyp.plot([X, Y, Z], '-', hue=CATEGORIES, backend='plotly', + chemtrails=[False, True, True], show=False, **ANIMATED) + assert len(fig.frames) > 1 + + +def test_a_trail_list_of_the_wrong_length_counts_the_callers_datasets(): + with pytest.raises(ValueError, match=( + 'chemtrails list has 2 entries but there are 3 datasets')): + hyp.plot([X, Y, Z], '-', hue=CATEGORIES, chemtrails=[True, False], + show=False, **ANIMATED) + with pytest.raises(ValueError, match='one trace per category'): + hyp.plot([X, Y, Z], 'o', hue=CATEGORIES, chemtrails=[True, False], + show=False, **ANIMATED) + + +def test_a_per_dataset_surface_list_is_matched_to_the_callers_datasets(): + """The same list-against-runs mismatch, for `surface=`.""" + fig = hyp.plot([X, Y, Z], '-', hue=CATEGORIES, + surface=[False, True, True], show=False) + assert fig.axes + + +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('backend', ['matplotlib', 'plotly']) +def test_labels_with_morph_say_that_they_are_not_drawn(ndims, backend): + """matplotlib hid every label without a word; plotly drew them in 2-D + at the first positions while the cloud moved away.""" + if backend == 'plotly': + pytest.importorskip('plotly') + clouds = [np.random.default_rng(seed).normal(size=(12, 3)) + for seed in (0, 1)] + names = [[f'{which}{i}' for i in range(12)] for which in 'ab'] + result, messages = _warnings_of( + clouds, 'o', animate='morph', labels=names, ndims=ndims, + duration=2, frame_rate=8, backend=backend) + assert len([m for m in messages + if "animate='morph'" in m and 'ignoring labels=' in m]) == 1 + if backend == 'plotly': + assert not result.layout.annotations + assert not getattr(result.layout.scene, 'annotations', None) + else: + for frame in (0, result.n_frames // 2, result.n_frames - 1): + result.draw_frame(frame) + assert not [text for text in result.figure.axes[0].texts + if isinstance(text, mtext.Annotation) + and text.get_visible()] + # an all-None list asks for nothing, so there is nothing to say + _result, messages = _warnings_of( + clouds, 'o', animate='morph', labels=[[None] * 12] * 2, ndims=ndims, + duration=2, frame_rate=8, backend=backend) + assert not [m for m in messages if 'ignoring labels=' in m] + + +def test_a_seeded_clustering_is_the_same_picture_every_time(): + """`cluster='KMeans'` groups differently on each call unless + `random_state=` is given, as documented for every random stage.""" + both = np.vstack([X, Y + 5]) + + def pixels(**kwargs): + fig = hyp.plot(both, 'o', cluster='KMeans', n_clusters=3, + show=False, **kwargs) + buffer = io.BytesIO() + fig.savefig(buffer, format='png') + plt.close(fig) + return buffer.getvalue() + + assert pixels(random_state=0) == pixels(random_state=0) + assert 'random_state' in hyp.plot.__doc__.split('cluster :')[1].split( + 'n_clusters :')[0] + + +# -------------------------------------------------------------------------- +# E. hue markers: the dataset's marker styling, and one fate per trace +# -------------------------------------------------------------------------- + +HOLLOW = dict(markerfacecolor='none', markeredgecolor='k', + markeredgewidth=3, markersize=12) + + +def _scatters(ax): + return [coll for coll in ax.collections + if isinstance(coll, PathCollection)] + + +def _assert_hollow_black(scatter): + assert len(scatter.get_facecolor()) == 0 # no fill + edge = np.atleast_2d(scatter.get_edgecolor()) + assert np.allclose(edge[:, :3], 0.0) # black edges + assert np.allclose(scatter.get_linewidths(), 3) + assert np.allclose(scatter.get_sizes(), 144.0) + + +@pytest.mark.parametrize('fmt', ['-o', 'o']) +@pytest.mark.parametrize('ndims', [2, 3]) +def test_hue_markers_wear_the_marker_styling_static_and_animated( + fmt, ndims): + """Hollow markers with a black outline were drawn as filled dots with + default edges, by the static plot and by the animation.""" + x = X[:, :ndims] + fig = hyp.plot(x, fmt, hue=HUE, show=False, **HOLLOW) + (static,) = _scatters(fig.axes[0]) + _assert_hollow_black(static) + anim = hyp.plot(x, fmt, hue=HUE, chemtrails=True, tail_duration=0.3, + show=False, **ANIMATED, **HOLLOW) + anim.draw_frame(anim.n_frames - 2) + anim.figure.canvas.draw() + shown = [scatter for scatter in _scatters(anim.figure.axes[0]) + if scatter.get_visible()] + assert len(shown) == 2 # tail and trail + for scatter in shown: + _assert_hollow_black(scatter) + + +@pytest.mark.parametrize('animated', [False, True]) +def test_hue_colors_the_edge_of_a_marker_with_its_own_fill(animated): + """As on a `Line2D`: `markerfacecolor=` names the fill, and the edge + keeps the trace's color, which with `hue=` is each observation's.""" + kwargs = dict(ANIMATED) if animated else {} + result = hyp.plot(X, 'o', hue=HUE, mfc='w', mew=2, ms=10, show=False, + **kwargs) + if animated: + result.draw_frame(result.n_frames - 1) + ax = _figure_of(result).axes[0] + scatter = [s for s in _scatters(ax) if s.get_visible()][0] + assert np.allclose(np.atleast_2d(scatter.get_facecolor())[:, :3], 1.0) + edges = np.atleast_2d(scatter.get_edgecolor()) + assert len(np.unique(edges[:, :3].round(3), axis=0)) >= 3 + assert np.allclose(scatter.get_linewidths(), 2) + # (`ms=` is matplotlib's short name for `markersize=`: the static + # scatter read the long name only) + assert np.allclose(scatter.get_sizes(), 100.0) + + +def test_plain_hue_markers_are_drawn_as_before(): + fig = hyp.plot(X, 'o', hue=HUE, show=False) + (scatter,) = _scatters(fig.axes[0]) + faces, edges = scatter.get_facecolor(), scatter.get_edgecolor() + assert len(faces) > 30 and np.allclose(faces, edges) + assert len(np.unique(faces[:, :3].round(3), axis=0)) > 30 + + +def _trace_and_markers(ax, role='head'): + line = [coll for coll in ax.collections + if getattr(coll, '_hyp_trace_role', None) == role][0] + return line, line._hyp_markers + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_hiding_a_trace_in_a_callback_hides_its_markers_and_head_marker( + ndims): + """`ctx.artists[0]` is the colored line; its markers are a second + artist the callback never saw, and they stayed on screen.""" + anim = hyp.plot( + X[:, :ndims], '-o', hue=HUE, head_marker='D', show=False, + on_frame=lambda ctx: ctx.artists[0].set_visible(ctx.frame % 2 == 0), + **ANIMATED) + ax = anim.figure.axes[0] + line, dots = _trace_and_markers(ax) + (head_marker,) = _head_marker(anim) + for frame in (4, 5, 6): + anim.draw_frame(frame) + anim.figure.canvas.draw() + shown = frame % 2 == 0 + assert line.get_visible() is shown + assert dots.get_visible() is shown + assert head_marker.get_visible() is shown + + +def test_fading_a_trace_in_a_callback_fades_its_markers(): + anim = hyp.plot( + X, '-o', hue=HUE, show=False, + on_frame=lambda ctx: ctx.artists[0].set_alpha(0.25), **ANIMATED) + line, dots = _trace_and_markers(anim.figure.axes[0]) + anim.draw_frame(5) + anim.figure.canvas.draw() + assert line.get_alpha() == 0.25 and dots.get_alpha() == 0.25 + + +def test_a_head_marker_is_hidden_with_its_line_without_hue(): + anim = hyp.plot( + X, '-', head_marker='o', show=False, + on_frame=lambda ctx: ctx.artists[0].set_visible(False), **ANIMATED) + (head_marker,) = _head_marker(anim) + anim.draw_frame(5) + anim.figure.canvas.draw() + assert not head_marker.get_visible() + + +def test_markers_hidden_by_the_caller_stay_hidden(): + """Following goes one way: a follower hidden for another reason is + not shown again because its line is visible.""" + anim = hyp.plot(X, '-o', hue=HUE, show=False, **ANIMATED) + line, dots = _trace_and_markers(anim.figure.axes[0]) + anim.draw_frame(5) + dots.set_visible(False) + anim.figure.canvas.draw() + assert line.get_visible() and not dots.get_visible() + + +def test_an_animated_figure_still_pickles(): + """The followers are kept by an artist of a module-level class, not + by closures on the artists.""" + import pickle + # (only bytes this test has just written itself are loaded back) + anim = hyp.plot(X, '-o', hue=HUE, head_marker='o', show=False, + labels=[str(i) if i % 9 == 0 else None + for i in range(len(X))], **ANIMATED) + anim.draw_frame(3) + anim.figure.canvas.draw() + assert pickle.loads(pickle.dumps(anim.figure)).axes + + +# -------------------------------------------------------------------------- +# F. a per-frame caption or title is never clipped +# -------------------------------------------------------------------------- + +def _tall_on_frame_five(ctx): + return ('tall\n' * 6 + 'end') if ctx.frame == 5 else 'short' + + +def _clipped(anim): + """The (frame, text) of every caption, suptitle or title that leaves + the canvas on some frame.""" + fig, out = anim.figure, [] + for frame in range(anim.n_frames): + anim.draw_frame(frame) + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + texts = [t for t in fig.texts if t.get_text().strip()] + [ + ax.title for ax in fig.axes if ax.title.get_text().strip()] + for text in texts: + box = text.get_window_extent(renderer) + if (box.y0 < -0.5 or box.y1 > fig.bbox.height + 0.5 + or box.x0 < -0.5 or box.x1 > fig.bbox.width + 0.5): + out.append((frame, text.get_text()[:12])) + return out + + +FRAME_TEXT_CASES = { + 'caption': dict(caption=_tall_on_frame_five), + 'caption 2-D': dict(caption=_tall_on_frame_five, ndims=2), + 'caption at the top': dict(caption=_tall_on_frame_five, + caption_kwargs={'position': 'top'}), + 'caption, large': dict(caption=_tall_on_frame_five, + caption_kwargs={'size': 18}), + 'caption, serial': dict(caption=_tall_on_frame_five, animate='serial'), + 'caption, held': dict(caption=_tall_on_frame_five, hold=0.5), + 'caption in a grid': dict(caption=_tall_on_frame_five, panels=(1, 2)), + 'title': dict(title=_tall_on_frame_five), + 'title 2-D': dict(title=_tall_on_frame_five, ndims=2), + 'title under a suptitle': dict(title=_tall_on_frame_five, + suptitle='A heading'), + 'titles in a grid': dict(title=_tall_on_frame_five, panels=(1, 2)), +} + + +@pytest.mark.parametrize('case', FRAME_TEXT_CASES) +def test_a_text_that_is_tallest_on_any_frame_stays_on_the_canvas(case): + """The room was sized from the first, middle and last frames: a text + that was tallest on another frame ran off the canvas.""" + kwargs = dict(animate=True, duration=2, frame_rate=8) + kwargs.update(FRAME_TEXT_CASES[case]) + anim = hyp.plot([X, Y], '-', show=False, **kwargs) + assert anim.n_frames > 8 # frame 5 is not a sampled one + assert _clipped(anim) == [] + + +def test_a_tall_title_frame_clears_the_suptitle_and_a_top_caption(): + anim = hyp.plot([X, Y], '-', animate=True, duration=2, frame_rate=8, + title=_tall_on_frame_five, suptitle='A heading', + caption='A caption', caption_kwargs={'position': 'top'}, + show=False) + fig = anim.figure + anim.draw_frame(5) + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + title = fig.axes[0].title.get_window_extent(renderer) + for gid in (SUPTITLE_GID, CAPTION_GID): + text = fig.findobj(lambda a: a.get_gid() == gid)[0] + assert text.get_window_extent(renderer).y0 >= title.y1 - 0.5 + + +def test_a_per_frame_caption_is_asked_about_every_frame_once_to_size_it(): + """What the room costs: one call of the caption per frame before the + animation is handed back (and nothing is rendered for it).""" + asked = [] + + def caption(ctx): + asked.append(ctx.frame) + return f'frame {ctx.frame}' + + anim = hyp.plot(X, '-', animate=True, duration=2, frame_rate=8, + caption=caption, show=False) + assert sorted(set(asked)) == list(range(anim.n_frames)) diff --git a/tests/test_review_round3_1_2_1.py b/tests/test_review_round3_1_2_1.py new file mode 100644 index 00000000..134f43c9 --- /dev/null +++ b/tests/test_review_round3_1_2_1.py @@ -0,0 +1,480 @@ +"""1.2.1 review round 3: what the third review found in the round 2 fixes. + +A. ``labels=`` with ``animate='morph'`` reads arrays and Series like + every other reader of ``labels=`` (the check now goes through the + shared datatype predicates; `tests/test_datatype_gate.py`). +B. The mouse callbacks of a labeled plot: one pair per axes, and they + work on the labels the axes holds now, so an ``ax.clear()`` followed + by a new labeled plot survives a mouse click. +C. A label's measured size follows everything that changes its drawn + extent (rotation, ``parse_math``), so labels turned on their side are + still kept off each other. +D. Continuous ``hue=`` markers with a half ``fillstyle`` are whole + outlined markers with one half filled, as matplotlib draws them on a + line, static and animated, 2-D and 3-D. + +Real figures, real mouse events and real frames, rendered headless. +Nothing is mocked, and no assertion depends on a font's absolute +metrics. +""" +import pickle +import warnings + +import matplotlib +matplotlib.use('Agg') + +import matplotlib.pyplot as plt # noqa: E402 +import numpy as np # noqa: E402 +import pandas as pd # noqa: E402 +import pytest # noqa: E402 +from matplotlib.backend_bases import MouseButton, MouseEvent # noqa: E402 +from matplotlib.backends.backend_agg import FigureCanvasAgg # noqa: E402 +from matplotlib.collections import PathCollection # noqa: E402 +from matplotlib.colors import to_rgb # noqa: E402 + +import hypertools as hyp # noqa: E402 +from hypertools.plot.matplotlib_backend import _label_size_pt # noqa: E402 + + +@pytest.fixture(autouse=True) +def _close_figures(): + yield + plt.close('all') + + +def _entries(ax): + return [entry for entry in ax._hyp_labels_and_points + if entry[0].axes is ax] + + +# --------------------------------------------------------------------------- +# A. labels= with animate='morph': arrays and Series +# --------------------------------------------------------------------------- + +def _morph_label_warnings(labels): + rng = np.random.default_rng(0) + clouds = [rng.normal(size=(12, 3)), rng.normal(size=(12, 3)) + 2] + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + hyp.plot(clouds, 'o', animate='morph', labels=labels, ndims=3, + duration=1, frame_rate=5, show=False) + return [str(w.message) for w in caught + if "animate='morph'" in str(w.message) + and 'ignoring labels=' in str(w.message)] + + +@pytest.mark.parametrize('make', [ + lambda names: [np.array(names), np.array(names)], + lambda names: [pd.Series(names), pd.Series(names)], + lambda names: (tuple(names), tuple(names)), +], ids=['arrays', 'series', 'tuples']) +def test_morph_says_that_array_and_series_labels_are_not_drawn(make): + names = [f'p{i}' for i in range(12)] + assert len(_morph_label_warnings(make(names))) == 1 + + +@pytest.mark.parametrize('labels', [ + [[None] * 12, [None] * 12], + [np.array([None] * 12, dtype=object)] * 2, +], ids=['lists', 'arrays']) +def test_morph_says_nothing_when_no_label_is_given(labels): + assert _morph_label_warnings(labels) == [] + + +# --------------------------------------------------------------------------- +# B. one pair of mouse callbacks per labeled axes +# --------------------------------------------------------------------------- + +def _connected(fig, name): + return len(fig.canvas.callbacks.callbacks.get(name, {})) + + +def _click(fig, ax): + """Press and release the left mouse button over `ax` (real events).""" + x, y = ax.bbox.x0 + ax.bbox.width / 2, ax.bbox.y0 + ax.bbox.height / 2 + for name in ('button_press_event', 'button_release_event'): + fig.canvas.callbacks.process(name, MouseEvent( + name, fig.canvas, x, y, button=MouseButton.LEFT)) + + +def _labeled_axes(ndims): + fig, ax = plt.subplots( + subplot_kw={'projection': '3d'} if ndims == 3 else {}) + return fig, ax, np.random.default_rng(0).normal(size=(6, ndims)) + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_a_click_after_clearing_and_relabeling_an_axes_works(ndims): + """The first call's callbacks stayed connected with its removed + labels (``axes is None``) and raised AttributeError out of the + button release, which also left the new labels hidden.""" + fig, ax, x = _labeled_axes(ndims) + hyp.plot(x, 'o', ax=ax, labels=list('abcdef'), show=False, + reduce=None, ndims=ndims) + removed = [entry[0] for entry in _entries(ax)] + ax.clear() + hyp.plot(x + 1, 'o', ax=ax, labels=list('uvwxyz'), show=False, + reduce=None, ndims=ndims) + fig.canvas.draw() + labels = [entry[0] for entry in _entries(ax)] + assert [label.get_text() for label in labels] == list('uvwxyz') + assert all(label.axes is None for label in removed) + + x0, y0 = ax.bbox.x0 + ax.bbox.width / 2, ax.bbox.y0 + ax.bbox.height / 2 + fig.canvas.callbacks.process('button_press_event', MouseEvent( + 'button_press_event', fig.canvas, x0, y0, button=MouseButton.LEFT)) + assert not any(label.get_visible() for label in labels) + fig.canvas.callbacks.process('button_release_event', MouseEvent( + 'button_release_event', fig.canvas, x0, y0, + button=MouseButton.LEFT)) + assert all(label.get_visible() for label in labels) + # ...and a second click, and a draw after it + _click(fig, ax) + fig.canvas.draw() + assert all(label.get_visible() for label in labels) + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_a_click_on_a_cleared_axes_that_was_not_relabeled_works(ndims): + fig, ax, x = _labeled_axes(ndims) + hyp.plot(x, 'o', ax=ax, labels=list('abcdef'), show=False, + reduce=None, ndims=ndims) + ax.clear() + _click(fig, ax) + fig.canvas.draw() + assert len(ax.texts) == 0 + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_labeled_calls_into_one_axes_share_one_pair_of_callbacks(ndims): + """Every call connected a press and a release callback of its own.""" + fig, ax, x = _labeled_axes(ndims) + hyp.plot(x, 'o', ax=ax, labels=list('abcdef'), show=False, + reduce=None, ndims=ndims) + _click(fig, ax) # (matplotlib drops what it no longer needs here) + press = _connected(fig, 'button_press_event') + release = _connected(fig, 'button_release_event') + for _ in range(3): + ax.clear() + hyp.plot(x, 'o', ax=ax, labels=list('abcdef'), show=False, + reduce=None, ndims=ndims) + _click(fig, ax) + assert _connected(fig, 'button_press_event') == press + # (the same six labels each time, so the same number of matplotlib's + # own per-label callbacks, which it disconnects at the click) + assert _connected(fig, 'button_release_event') == release + # a second call WITHOUT a clear adds labels, and no callback of ours + hyp.plot(x + 1, 'o', ax=ax, labels=list('uvwxyz'), show=False, + reduce=None, ndims=ndims) + assert _connected(fig, 'button_press_event') == press + labels = [entry[0] for entry in _entries(ax)] + assert len(labels) == 12 + _click(fig, ax) + assert all(label.get_visible() for label in labels) + + +def test_a_labeled_figure_given_another_canvas_answers_the_mouse_there(): + fig, ax, x = _labeled_axes(2) + hyp.plot(x, 'o', ax=ax, labels=list('abcdef'), show=False, + reduce=None, ndims=2) + FigureCanvasAgg(fig) + fresh = _connected(fig, 'button_press_event') + hyp.plot(x + 1, 'o', ax=ax, labels=list('uvwxyz'), show=False, + reduce=None, ndims=2) + assert _connected(fig, 'button_press_event') == fresh + 1 + labels = [entry[0] for entry in _entries(ax)] + assert len(labels) == 12 + x0, y0 = ax.bbox.x0 + 5, ax.bbox.y0 + 5 + fig.canvas.callbacks.process('button_press_event', MouseEvent( + 'button_press_event', fig.canvas, x0, y0, button=MouseButton.LEFT)) + assert not any(label.get_visible() for label in labels) + fig.canvas.callbacks.process('button_release_event', MouseEvent( + 'button_release_event', fig.canvas, x0, y0, + button=MouseButton.LEFT)) + assert all(label.get_visible() for label in labels) + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_a_labeled_figure_that_was_clicked_can_be_pickled(ndims): + fig, ax, x = _labeled_axes(ndims) + hyp.plot(x, 'o', ax=ax, labels=list('abcdef'), show=False, + reduce=None, ndims=ndims) + _click(fig, ax) + # (bytes this test has just made from its own figure) + again = pickle.loads(pickle.dumps(fig)) + assert [text.get_text() for text in again.axes[0].texts] == list( + 'abcdef') + + +def test_each_labeled_axes_of_a_figure_answers_the_mouse(): + fig, (left, right) = plt.subplots(1, 2) + x = np.random.default_rng(0).normal(size=(5, 2)) + hyp.plot(x, 'o', ax=left, labels=list('abcde'), show=False, + reduce=None, ndims=2) + hyp.plot(x, 'o', ax=right, labels=list('vwxyz'), show=False, + reduce=None, ndims=2) + labels = [entry[0] for ax in (left, right) for entry in _entries(ax)] + assert len(labels) == 10 + x0, y0 = left.bbox.x0 + 5, left.bbox.y0 + 5 + fig.canvas.callbacks.process('button_press_event', MouseEvent( + 'button_press_event', fig.canvas, x0, y0, button=MouseButton.LEFT)) + assert not any(label.get_visible() for label in labels) + fig.canvas.callbacks.process('button_release_event', MouseEvent( + 'button_release_event', fig.canvas, x0, y0, + button=MouseButton.LEFT)) + assert all(label.get_visible() for label in labels) + + +# --------------------------------------------------------------------------- +# C. a label's size follows its rotation and its parse_math +# --------------------------------------------------------------------------- + +def _overlapping_pairs(fig, labels): + """How many pairs of the label boxes overlap, as they were drawn.""" + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + boxes = [label.get_bbox_patch().get_window_extent(renderer) + for label in labels if label.get_visible()] + count = 0 + for i, one in enumerate(boxes): + for other in boxes[i + 1:]: + if (min(one.x1, other.x1) - max(one.x0, other.x0) > 0.5 + and min(one.y1, other.y1) - max(one.y0, other.y0) > 0.5): + count += 1 + return count + + +def _stacked_labels(): + """Two points one above the other, far enough apart that their + (wide, flat) labels are clear of each other.""" + x = np.array([[0.0, 0.0], [0.0, 0.25], [1.0, 1.0], [-1.0, -1.0]]) + fig = hyp.plot(x, 'o', reduce=None, ndims=2, show=False, + labels=['a long label below', 'a long label above', + None, None]) + ax = fig.axes[0] + labels = [entry[0] for entry in _entries(ax)] + return fig, labels + + +def test_a_rotated_label_is_measured_as_it_is_drawn(): + fig, labels = _stacked_labels() + fig.canvas.draw() + label = labels[0] + wide, flat = _label_size_pt(label) + assert wide > 3 * flat + label.set_rotation(90) + fig.canvas.draw() + assert _label_size_pt(label) == pytest.approx((flat, wide), rel=0.05) + label.set_rotation(45) + fig.canvas.draw() + width, height = _label_size_pt(label) + assert width == pytest.approx(height, rel=0.05) + assert flat < width < wide + label.set_rotation(0) + fig.canvas.draw() + assert _label_size_pt(label) == pytest.approx((wide, flat)) + + +def test_a_label_switched_to_plain_text_is_measured_again(): + fig, labels = _stacked_labels() + label = labels[0] + label.set_text(r'$\frac{a}{b}$ and $\sum_{i}^{n} x_i^2$') + fig.canvas.draw() + as_math = _label_size_pt(label) + label.set_parse_math(False) + fig.canvas.draw() + as_text = _label_size_pt(label) + # (the plain text is every character of the source, on one line) + assert as_text[0] > as_math[0] + assert as_text[1] < as_math[1] + + +def test_labels_turned_on_their_side_are_kept_off_each_other(): + """The size kept from before the rotation said the two labels were + still clear of each other, so they were left overlapping.""" + fig, labels = _stacked_labels() + assert _overlapping_pairs(fig, labels) == 0 + before = [tuple(label.xyann) for label in labels] + for label in labels: + label.set_rotation(90) + fig.canvas.draw() + assert _overlapping_pairs(fig, labels) == 0 + # (they did overlap where they were: one of them has moved) + assert [tuple(label.xyann) for label in labels] != before + + +# --------------------------------------------------------------------------- +# D. half-filled markers colored by a continuous hue +# --------------------------------------------------------------------------- + +XY = np.array([[0.0, 0.0], [1.0, 1.0], [2.0, 0.0]]) +# (in 3-D, no observation on an edge of the cube the data spans: an +# animation draws those edges, and a line through a marker is not the +# marker's own look) +XYZ = np.array([[0.0, 0.1, -0.2], [1.0, 0.3, 0.2], [-1.0, -0.2, 0.1], + [0.2, 1.0, 0.3], [-0.3, -1.0, -0.1], [0.3, -0.2, 1.0], + [-0.2, 0.2, -1.0]]) +HALF = dict(reduce=None, fillstyle='left', markeredgecolor='k', + markersize=30, show=False) + + +def _half_scatter(ndims, animated, fmt='o', **kwargs): + data = XYZ if ndims == 3 else XY + options = dict(HALF, ndims=ndims, + hue=np.linspace(0.0, 1.0, len(data)), **kwargs) + if animated: + anim = hyp.plot(data, fmt, animate=True, duration=1, frame_rate=4, + **options) + anim.draw_frame(anim.n_frames - 1) + fig = anim.figure + else: + fig = hyp.plot(data, fmt, **options) + ax = fig.axes[0] + dots = [coll for coll in ax.collections + if isinstance(coll, PathCollection) and coll.get_visible()] + assert len(dots) == 1 + return fig, ax, dots[0] + + +def _pixels(fig): + fig.canvas.draw() + return np.asarray(fig.canvas.buffer_rgba())[..., :3] / 255.0 + + +def _marker_looks(fig, ax, dots): + """Per marker, from the drawn pixels: the color inside its left + half, the color inside its right half, and the darkest pixel on the + way out of the marker through its right rim.""" + image = _pixels(fig) + centers = dots.get_offset_transform().transform( + np.asarray(dots.get_offsets(), dtype=float)) + radius = 0.5 * np.sqrt(dots.get_sizes()[0]) * fig.dpi / 72.0 + height = image.shape[0] + looks = [] + for cx, cy in centers: + row = int(round(height - cy)) + left = image[row, int(round(cx - 0.5 * radius))] + right = image[row, int(round(cx + 0.5 * radius))] + rim = image[row, int(round(cx + 0.7 * radius)): + int(round(cx + 1.3 * radius)) + 1] + looks.append((left, right, float(rim.sum(axis=1).min()) / 3.0)) + return looks + + +def _right_outline_pixels(fig, dots): + """Per marker, how many dark pixels lie in the right part of its + box, clear of the straight edge down its middle: the outline of the + right half, about two and a half radii long when it is drawn.""" + image = _pixels(fig) + centers = dots.get_offset_transform().transform( + np.asarray(dots.get_offsets(), dtype=float)) + radius = 0.5 * np.sqrt(dots.get_sizes()[0]) * fig.dpi / 72.0 + height = image.shape[0] + counts = [] + for cx, cy in centers: + row = height - cy + part = image[int(round(row - 1.3 * radius)): + int(round(row + 1.3 * radius)) + 1, + int(round(cx + 0.3 * radius)): + int(round(cx + 1.3 * radius)) + 1] + counts.append(int((part.mean(axis=2) < 0.35).sum()) / radius) + return counts + + +@pytest.mark.parametrize('animated', [False, True], + ids=['static', 'animated']) +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('fmt', ['o', '-o']) +def test_half_filled_hue_markers_are_whole_outlined_markers( + ndims, animated, fmt): + """The scatter drew the filled half alone: half-discs with nothing + where the other half of the marker is.""" + fig, ax, dots = _half_scatter(ndims, animated, fmt=fmt) + looks = _marker_looks(fig, ax, dots) + count = 7 if ndims == 3 else 3 + assert len(looks) == count + hues = np.asarray(dots.get_facecolors())[:, :3] + assert len(hues) == count + # the black edge goes round the right half of every marker + assert min(_right_outline_pixels(fig, dots)) > 1.5 + if fmt == 'o': + # (a line format draws its line through the markers, static + # over them, so single pixels are read on markers alone) + for left, right, rim in looks: + # the left half wears one of the hue colors... + assert min(np.abs(hues - left).max(axis=1)) < 0.05 + # ...the right half is not filled... + assert min(np.abs(hues - right).max(axis=1)) > 0.2 + # ...and the edge is met on the way out through it + assert rim < 0.35 + # one artist with one offset per observation, like any scatter + assert len(dots.get_offsets()) == count + assert len(dots.get_paths()) == 1 + + +def test_half_filled_hue_markers_match_matplotlibs_own_on_a_line(): + """The same picture as ``ax.plot(..., fillstyle='left')`` draws, + marker for marker, with the hue in the place of the line's color.""" + fig, ax, dots = _half_scatter(2, False) + ours = _marker_looks(fig, ax, dots) + hues = np.asarray(dots.get_facecolors())[:, :3] + + ref_fig, ref_ax = plt.subplots(figsize=fig.get_size_inches(), + dpi=fig.dpi) + for (px, py), color in zip(XY, hues): + ref_ax.plot([px], [py], 'o', color=color, fillstyle='left', + markeredgecolor='k', markersize=30) + image = _pixels(ref_fig) + radius = 0.5 * 30 * ref_fig.dpi / 72.0 + for (px, py), (left, right, rim) in zip(XY, ours): + cx, cy = ref_ax.transData.transform((px, py)) + row = int(round(image.shape[0] - cy)) + assert image[row, int(round(cx - 0.5 * radius))] == pytest.approx( + left, abs=0.05) + assert image[row, int(round(cx + 0.5 * radius))] == pytest.approx( + right, abs=0.05) + ref_rim = image[row, int(round(cx + 0.7 * radius)): + int(round(cx + 1.3 * radius)) + 1] + assert float(ref_rim.sum(axis=1).min()) / 3.0 < 0.35 + assert rim < 0.35 + + +@pytest.mark.parametrize('animated', [False, True], + ids=['static', 'animated']) +def test_the_other_half_wears_markerfacecoloralt(animated): + fig, ax, dots = _half_scatter(2, animated, markerfacecoloralt='gold') + for _left, right, rim in _marker_looks(fig, ax, dots): + assert right == pytest.approx(to_rgb('gold'), abs=0.05) + assert rim < 0.35 + + +def test_a_full_fillstyle_and_an_unfilled_marker_draw_as_before(): + fig, ax, dots = _half_scatter(2, False, fillstyle='full') + assert type(dots) is PathCollection + for left, right, rim in _marker_looks(fig, ax, dots): + assert right == pytest.approx(left, abs=0.05) + assert rim < 0.35 + # a marker with nothing to fill has no other half + fig, ax, dots = _half_scatter(2, False, fmt='x') + assert type(dots) is PathCollection + assert _pixels(fig).min() < 0.35 + + +def test_a_figure_with_half_filled_hue_markers_can_be_pickled(): + fig, ax, dots = _half_scatter(2, False) + before = _pixels(fig).copy() + # (bytes this test has just made from its own figure) + again = pickle.loads(pickle.dumps(fig)) + FigureCanvasAgg(again) + assert np.array_equal(_pixels(again), before) + + +def test_hidden_half_filled_markers_draw_nothing(): + fig, ax, dots = _half_scatter(2, False) + shown = _pixels(fig).copy() + dots.set_visible(False) + hidden = _pixels(fig) + fig_plain, ax_plain, dots_plain = _half_scatter(2, False) + dots_plain.remove() + assert np.array_equal(hidden, _pixels(fig_plain)) + assert not np.array_equal(hidden, shown) diff --git a/tests/test_review_round4_1_2_1.py b/tests/test_review_round4_1_2_1.py new file mode 100644 index 00000000..a65025c7 --- /dev/null +++ b/tests/test_review_round4_1_2_1.py @@ -0,0 +1,792 @@ +"""1.2.1 review round 4: what the fourth review found. + +A. Observation labels (``labels=``) are kept off the legends (an axes' + own and the one shared legend of a ``panels=`` grid), the colorbars, + the panel titles and the figure's ``suptitle=``/``caption=``, in 2-D + and 3-D, static and in the one placement an animation makes. +B. ``legend_kwargs={'loc': ...}`` on a 2-D plot puts the legend inside + the frame the reader sees, as a ``loc`` does in matplotlib. +C. ``head_marker=`` draws ONE marker per dataset when ``hue=`` cuts the + dataset into categories, and a serial reveal shows the head on its + first frame. +D. A ``head_marker=`` dict takes matplotlib's short names and a face + color. +E. The ``trail_alpha=`` warning under ``animate='window'`` and a + ``hold=`` too short to add a frame. + +Real figures, real frames and real saved files, rendered headless. +Nothing is mocked, and no assertion depends on a font's absolute +metrics. +""" +import shutil +import subprocess +import warnings + +import matplotlib +matplotlib.use('Agg') + +import matplotlib.pyplot as plt # noqa: E402 +import matplotlib.text as mtext # noqa: E402 +import numpy as np # noqa: E402 +import pytest # noqa: E402 +from matplotlib.colors import to_rgba # noqa: E402 +from PIL import Image # noqa: E402 + +import hypertools as hyp # noqa: E402 + +HAS_FFMPEG = (shutil.which('ffmpeg') is not None + and shutil.which('ffprobe') is not None) + +LABELS = [f'label{i}' for i in range(24)] + + +@pytest.fixture(autouse=True) +def _close_figures(): + yield + plt.close('all') + + +def _quiet(*args, **kwargs): + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + return hyp.plot(*args, show=False, **kwargs) + + +def _trajectories(k=1, n=40, dims=3, seed=0): + rng = np.random.default_rng(seed) + out = [np.cumsum(rng.normal(size=(n, dims)), axis=0) for _ in range(k)] + return out if k > 1 else out[0] + + +# --------------------------------------------------------------------------- +# A. labels stay off legends, colorbars, titles, suptitle and caption +# --------------------------------------------------------------------------- + +def _label_boxes(fig, renderer): + return [label.get_bbox_patch().get_window_extent(renderer) + for ax in fig.axes for label in ax.findobj(mtext.Annotation) + if label.get_visible() and label.get_text()] + + +def _furniture(fig, renderer): + """What the figure shows beside its data, by kind.""" + legends = list(fig.legends) + [ + ax.get_legend() for ax in fig.axes if ax.get_legend() is not None] + return { + 'legend': [one.get_window_extent(renderer) for one in legends], + 'title': [ax.title.get_window_extent(renderer) + for ax in fig.axes if ax.title.get_text()], + 'figure text': [text.get_window_extent(renderer) + for text in fig.texts if text.get_text()], + 'colorbar': [ax.get_tightbbox(renderer) for ax in fig.axes + if hasattr(ax, '_colorbar')], + } + + +def _covered(fig): + """How many label boxes lie on each kind of furniture, and how many + pairs of labels lie on each other, on a real draw of `fig`.""" + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + boxes = _label_boxes(fig, renderer) + counts = {kind: sum(bool(box.overlaps(other)) + for box in boxes for other in others) + for kind, others in _furniture(fig, renderer).items()} + counts['labels'] = sum( + bool(boxes[i].overlaps(boxes[j])) + for i in range(len(boxes)) for j in range(i + 1, len(boxes))) + return len(boxes), counts + + +def _panel_call(seed, dims): + x = np.random.default_rng(seed).normal(size=(24, 3))[:, :dims] + return ([x[:12], x[12:]], 'o'), dict( + panels=True, labels=[LABELS[:12], LABELS[12:]], legend=['a', 'b'], + title=['A', 'B'], suptitle='S') + + +#: the seeds of the review's twelve on which the 1.2.1 draft put a label +#: on the shared legend, a panel title or the suptitle (3-D: 0, 1, 2, 6, +#: 7, 8; 2-D: 2, 5, 7, 8, 10, 11), and one clean seed of each +@pytest.mark.parametrize('dims, seed', [ + (3, 0), (3, 1), (3, 2), (3, 6), (3, 7), (3, 8), (3, 3), + (2, 2), (2, 5), (2, 7), (2, 8), (2, 10), (2, 11), (2, 0)]) +def test_panel_labels_stay_off_the_shared_legend_and_the_titles(dims, seed): + args, kwargs = _panel_call(seed, dims) + fig = hyp.plot(*args, show=False, **kwargs) + n, counts = _covered(fig) + assert n == 24 + assert len(fig.legends) == 1 + # (not asserted: that no two labels meet. They do not with + # matplotlib 3.10's text sizes; with 3.11's slightly larger ones one + # pair does on two of these seeds, as before this change) + del counts['labels'] + assert counts == {'legend': 0, 'title': 0, 'figure text': 0, + 'colorbar': 0} + + +@pytest.mark.parametrize('seed', [0, 2, 6, 7]) +def test_animated_panel_labels_are_placed_off_the_legend_and_texts(seed): + """An animation's placement keeps off the same things on every frame + (rewritten in review round 5 from the test of one placement, made + for frame 0 and held), and a frame shown again has its labels where + they were.""" + x = np.random.default_rng(seed).normal(size=(24, 3)) + anim = _quiet([x[:12], x[12:]], 'o', animate='spin', panels=True, + labels=[LABELS[:12], LABELS[12:]], legend=['a', 'b'], + title=['A', 'B'], suptitle='S', caption='A caption', + duration=1, frame_rate=5) + places = {} + for frame in range(anim.n_frames): + anim.draw_frame(frame) + n, counts = _covered(anim.figure) + assert n == 24 + assert counts['legend'] == counts['title'] == 0, frame + assert counts['figure text'] == 0, frame + places[frame] = [label.xyann for ax in anim.figure.axes + for label in ax.findobj(mtext.Annotation)] + for frame in (3, 0, 4): + anim.draw_frame(frame) + anim.figure.canvas.draw() + assert places[frame] == [label.xyann for ax in anim.figure.axes + for label in ax.findobj(mtext.Annotation)] + + +@pytest.mark.parametrize('across', [0.2, 0.4]) +def test_one_label_under_the_title_moves_off_it(across): + """A single label was never looked at (there was no other label to + keep it from), so the label of the topmost point lay on the title.""" + x = np.array([[across, 1.0], [-1.0, -1.0], [1.0, -1.0]]) + fig = hyp.plot(x, 'o', labels=['top', None, None], title='A title', + show=False) + n, counts = _covered(fig) + assert n == 1 + assert counts['title'] == 0 + + +def test_a_label_clear_of_everything_stays_where_it_always_was(): + x = np.array([[0.0, 0.0], [-1.0, -1.0], [1.0, 1.0]]) + fig = hyp.plot(x, 'o', labels=['middle', None, None], title='A title', + legend=['data'], show=False) + fig.canvas.draw() + (label,) = [one for one in fig.axes[0].findobj(mtext.Annotation) + if one.get_text()] + assert tuple(label.xyann) == (-20, 20) + + +@pytest.mark.parametrize('dims', [2, 3]) +def test_labels_stay_off_a_colorbar_drawn_where_they_were(dims): + """A colorbar put exactly where a label hangs: the label leaves.""" + rng = np.random.default_rng(1) + x = rng.normal(size=(6, dims)) + fig = plt.figure(figsize=(6, 5)) + ax = fig.add_subplot(projection='3d' if dims == 3 else None) + hyp.plot(x, 'o', labels=[f'point {i}' for i in range(6)], ax=ax, + show=False) + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + before = _label_boxes(fig, renderer) + # a colorbar axes over the first label's box (figure fractions) + target = before[0].transformed(fig.transFigure.inverted()) + cax = fig.add_axes([target.x0, target.y0, target.width, target.height]) + fig.colorbar(plt.cm.ScalarMappable(cmap='viridis'), cax=cax) + n, counts = _covered(fig) + assert n == 6 + assert counts['colorbar'] == 0 + assert counts['labels'] == 0 + + +def test_the_obstacles_are_the_legends_colorbars_titles_and_figure_texts(): + """Every kind of furniture is in the list the placement keeps off, + each box covering the artist as drawn (boxes are in points from the + canvas corner, widened to whole points).""" + from hypertools.plot.matplotlib_backend import _label_obstacles_pt + x = np.random.default_rng(0).normal(size=(24, 3)) + fig = hyp.plot([x[:12], x[12:]], 'o', panels=True, + hue=[np.arange(12.), np.arange(12.)], colorbar=True, + labels=[LABELS[:12], LABELS[12:]], title=['A', 'B'], + suptitle='S', caption='A caption', show=False) + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + to_pt = 72.0 / fig.dpi + obstacles = _label_obstacles_pt(fig.axes[0], None, (0.0, 0.0), to_pt) + furniture = _furniture(fig, renderer) + assert furniture['colorbar'] and furniture['figure text'] + assert len(furniture['title']) == 2 and len(furniture['figure text']) == 2 + for kind, boxes in furniture.items(): + for box in boxes: + want = np.array(box.extents) * to_pt + inside = ((obstacles[:, 0] <= want[0] + 1e-6) + & (obstacles[:, 1] <= want[1] + 1e-6) + & (obstacles[:, 2] >= want[2] - 1e-6) + & (obstacles[:, 3] >= want[3] - 1e-6)) + assert inside.any(), kind + # ...and a 2-D single plot with a legend, a title and a caption + fig = hyp.plot(x[:, :2], 'o', labels=LABELS, legend=['data'], + title='Title', caption='cap', show=False) + fig.canvas.draw() + assert len(_label_obstacles_pt( + fig.axes[0], None, (0.0, 0.0), 72.0 / fig.dpi)) == 3 + + +@pytest.mark.parametrize('kwargs', [ + dict(legend=['data'], title='Title', caption='cap'), + dict(hue=np.arange(24.), title='Title', suptitle='Sup'), +]) +@pytest.mark.parametrize('dims', [2, 3]) +def test_single_plot_labels_stay_off_legend_colorbar_and_texts(dims, kwargs): + for seed in (0, 1, 2, 3): + x = np.random.default_rng(seed).normal(size=(24, 3))[:, :dims] + fig = hyp.plot(x, 'o', labels=LABELS, show=False, **kwargs) + _n, counts = _covered(fig) + assert counts['legend'] == counts['title'] == 0, seed + assert counts['figure text'] == counts['colorbar'] == 0, seed + plt.close(fig) + + +def test_a_redraw_with_obstacles_places_nothing_again(): + args, kwargs = _panel_call(2, 3) + fig = hyp.plot(*args, show=False, **kwargs) + fig.canvas.draw() + first = [tuple(label.xyann) for ax in fig.axes + for label in ax.findobj(mtext.Annotation)] + answers = [ax._hyp_label_answer for ax in fig.axes[:2]] + for _ in range(3): + fig.canvas.draw() + assert first == [tuple(label.xyann) for ax in fig.axes + for label in ax.findobj(mtext.Annotation)] + assert all(now is then for now, then in + zip([ax._hyp_label_answer for ax in fig.axes[:2]], answers)) + + +def test_the_same_call_twice_places_the_labels_the_same(): + places = [] + for _ in range(2): + args, kwargs = _panel_call(0, 3) + fig = hyp.plot(*args, show=False, **kwargs) + fig.canvas.draw() + places.append([tuple(label.xyann) for ax in fig.axes + for label in ax.findobj(mtext.Annotation)]) + plt.close(fig) + assert places[0] == places[1] + + +def test_a_tiny_figure_with_large_texts_keeps_the_labels_off_them(): + """The extreme case of the review (3 x 2.5 in, size 18 suptitle and + caption, 30 labels): there is no room for every label, so labels + lie on each other, and none of them on a text or on the legend (a + place on one of those is the last resort). Before, a third of the + labels lay on the suptitle, the title or the caption.""" + rng = np.random.default_rng(1) + x = rng.normal(size=(30, 3)) + x[:10] *= 0.05 + fig = hyp.plot( + x, 'o', size=(3, 2.5), labels=[f'obs {i}' for i in range(30)], + caption='A caption that is long enough to wrap several times in a ' + 'small figure', caption_kwargs={'size': 18}, + suptitle='Suptitle long enough to wrap in a small figure', + suptitle_kwargs={'size': 18}, title='Title', legend=['d'], + show=False) + n, counts = _covered(fig) + assert n == 30 + assert counts['legend'] == 0 + assert counts['figure text'] == 0 + assert counts['title'] == 0 + + +# --------------------------------------------------------------------------- +# B. legend_kwargs={'loc': ...} on a 2-D plot: inside the drawn frame +# --------------------------------------------------------------------------- + +def _frame_and_legend(fig): + """The window extents of the 2-D frame square and of the legend.""" + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + ax = fig.axes[0] + (frame,) = [patch for patch in ax.patches + if type(patch).__name__ == 'Rectangle'] + return (frame.get_window_extent(renderer), + ax.get_legend().get_window_extent(renderer), ax) + + +@pytest.mark.parametrize('loc', ['upper left', 'lower right', 'center', + 'upper right', 'best', 2]) +@pytest.mark.parametrize('animate', [False, True]) +def test_a_named_legend_loc_is_inside_the_2d_frame(loc, animate): + data = [d[:, :2] for d in _trajectories(3, 30)] + extra = dict(animate=True, duration=1, frame_rate=5) if animate else {} + out = _quiet(data, '-', legend=['a', 'b', 'c'], + legend_kwargs={'loc': loc}, title='T', **extra) + fig = out.figure if animate else out + frame, legend, _ax = _frame_and_legend(fig) + assert frame.x0 <= legend.x0 and legend.x1 <= frame.x1 + assert frame.y0 <= legend.y0 and legend.y1 <= frame.y1 + # in its corner, a little in from the border as in matplotlib + if loc in ('upper left', 2): + assert legend.x0 - frame.x0 < 0.5 * legend.width + assert frame.y1 - legend.y1 < 0.5 * legend.height + assert legend.x0 > frame.x0 and legend.y1 < frame.y1 + if loc == 'lower right': + assert frame.x1 - legend.x1 < 0.5 * legend.width + assert legend.y0 - frame.y0 < 0.5 * legend.height + if loc == 'center': + assert 0.5 * (legend.x0 + legend.x1) == pytest.approx( + 0.5 * (frame.x0 + frame.x1), abs=1.0) + + +def test_the_default_2d_legend_is_still_right_of_the_frame(): + data = [d[:, :2] for d in _trajectories(3, 30)] + fig = hyp.plot(data, '-', legend=['a', 'b', 'c'], show=False) + frame, legend, _ax = _frame_and_legend(fig) + assert legend.x0 >= frame.x1 + assert 0.5 * (legend.y0 + legend.y1) == pytest.approx( + 0.5 * (frame.y0 + frame.y1), abs=1.5) + + +def test_a_bbox_to_anchor_is_the_callers_own_placement(): + data = [d[:, :2] for d in _trajectories(3, 30)] + fig = hyp.plot(data, '-', legend=['a', 'b', 'c'], show=False, + legend_kwargs={'loc': 'upper left', + 'bbox_to_anchor': (0.5, 0.5)}) + _frame, legend, ax = _frame_and_legend(fig) + # the legend's upper-left corner at the middle of the AXES, as the + # same two arguments mean in matplotlib + middle = ax.transAxes.transform((0.5, 0.5)) + assert legend.x0 == pytest.approx(middle[0], abs=1.0) + assert legend.y1 == pytest.approx(middle[1], abs=1.0) + + +def test_a_named_loc_on_a_3d_plot_is_inside_its_axes(): + fig = hyp.plot(_trajectories(3, 30), '-', legend=['a', 'b', 'c'], + legend_kwargs={'loc': 'upper left'}, show=False) + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + ax = fig.axes[0] + box, legend = ax.get_window_extent(renderer), \ + ax.get_legend().get_window_extent(renderer) + assert box.x0 <= legend.x0 and legend.x1 <= box.x1 + assert box.y0 <= legend.y0 and legend.y1 <= box.y1 + + +@pytest.mark.parametrize('dims', [2, 3]) +def test_a_named_loc_on_a_grid_still_names_the_side_of_the_grid(dims): + data = [d[:, :dims] for d in _trajectories(3, 30)] + fig = hyp.plot(data, '-', panels=True, legend=['a', 'b', 'c'], + legend_kwargs={'loc': 'upper left'}, show=False) + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + (legend,) = fig.legends + box = legend.get_window_extent(renderer) + panels = [ax.get_window_extent(renderer) for ax in fig.axes] + assert box.x1 <= min(panel.x0 for panel in panels) + 1.0 + assert box.x0 >= 0 + + +# --------------------------------------------------------------------------- +# C. head_marker=: one per dataset; a serial reveal's first frame +# --------------------------------------------------------------------------- + +def _points(line): + """The data of a line artist as an (n, d) array.""" + if hasattr(line, 'get_data_3d'): + return np.array([np.asarray(c, dtype=float) + for c in line.get_data_3d()]).T.reshape(-1, 3) + return np.array([np.asarray(c, dtype=float) + for c in line.get_data()]).T.reshape(-1, 2) + + +def _head_markers(ax): + return [line for line in ax.lines + if getattr(line, '_hyp_trace_role', None) == 'head_marker'] + + +def _leader(ax, marker): + (line,) = [line for line in ax.lines + if getattr(line, '_hyp_head_marker', None) is marker] + return line + + +@pytest.mark.parametrize('dims', [2, 3]) +@pytest.mark.parametrize('style', [True, 'window']) +def test_one_head_marker_per_dataset_with_categories(dims, style): + x = _trajectories(1, 40, dims) + anim = _quiet(x, '-', animate=style, hue=['u'] * 20 + ['v'] * 20, + head_marker='o', duration=1.5, frame_rate=10) + ax = anim.figure.axes[0] + markers = _head_markers(ax) + assert len(markers) == 2 # one artist per category run + for frame in range(anim.n_frames): + anim.draw_frame(frame) + drawn = [m for m in markers if len(_points(m))] + assert len(drawn) == 1, frame # ...ONE of them drawn + (marker,) = drawn + leader = _leader(ax, marker) + assert np.allclose(_points(marker)[0], _points(leader)[-1]) + assert to_rgba(marker.get_color()) == to_rgba(leader.get_color()) + # at the end it is on the dataset's last point, in the color of the + # category that point is in (the second run), and the first + # category's marker is gone + last_run = _leader(ax, markers[1]) + assert len(_points(markers[0])) == 0 + assert np.allclose(_points(markers[1])[0], _points(last_run)[-1]) + anim.draw_frame(0) + assert len(_points(markers[0])) == 1 and len(_points(markers[1])) == 0 + + +def test_two_datasets_with_categories_have_two_head_markers(): + a, b = _trajectories(2, 30) + hue = [['u'] * 10 + ['v'] * 20, ['v'] * 15 + ['w'] * 15] + anim = _quiet([a, b], '-', animate=True, hue=hue, head_marker='o', + duration=1, frame_rate=10) + ax = anim.figure.axes[0] + for frame in (0, anim.n_frames // 2, anim.n_frames - 1): + anim.draw_frame(frame) + assert sum(len(_points(m)) for m in _head_markers(ax)) == 2 + + +def test_a_dataset_in_one_piece_keeps_its_one_head_marker(): + anim = _quiet(_trajectories(3, 30), '-', animate=True, head_marker='o', + duration=1, frame_rate=10) + ax = anim.figure.axes[0] + for frame in (0, 5, anim.n_frames - 1): + anim.draw_frame(frame) + markers = _head_markers(ax) + assert [len(_points(m)) for m in markers] == [1, 1, 1] + for marker in markers: + assert np.allclose(_points(marker)[0], + _points(_leader(ax, marker))[-1]) + + +@pytest.mark.parametrize('dims', [2, 3]) +@pytest.mark.parametrize('trail', [{}, {'chemtrails': True}]) +def test_a_serial_reveal_shows_the_first_head_on_frame_0(dims, trail): + data = [d[:, :dims] for d in _trajectories(3, 40)] + anim = _quiet(data, '-', animate='serial', head_marker='o', + duration=1.5, frame_rate=10, **trail) + ax = anim.figure.axes[0] + markers = _head_markers(ax) + anim.draw_frame(anim.n_frames // 4) + first_point = _points(_leader(ax, markers[0]))[0] + anim.draw_frame(0) + assert [len(_points(m)) for m in markers] == [1, 0, 0] + # at the first dataset's first point + assert np.all(np.isfinite(_points(markers[0]))) + if not trail: + # (without a trail the line is drawn from its first point on) + assert np.allclose(_points(markers[0])[0], first_point) + # as a parallel reveal shows its heads on frame 0 + parallel = _quiet(data, '-', animate=True, head_marker='o', + duration=1.5, frame_rate=10) + parallel.draw_frame(0) + assert all(len(_points(m)) == 1 + for m in _head_markers(parallel.figure.axes[0])) + + +def test_a_serial_first_frame_draws_the_head_marker(): + """Pixels: frame 0 with a head marker is not the empty frame.""" + data = _trajectories(3, 40) + frames = [] + for head in (None, 'o'): + anim = _quiet(data, '-', animate='serial', head_marker=head, + duration=1.5, frame_rate=10) + fig = anim.draw_frame(0).figure + fig.canvas.draw() + frames.append(np.asarray(fig.canvas.buffer_rgba()).copy()) + plt.close(fig) + assert frames[0].shape == frames[1].shape + assert int((frames[0] != frames[1]).any(axis=-1).sum()) > 10 + + +def test_a_serial_grid_shows_each_panels_head_on_frame_0(): + anim = _quiet(_trajectories(3, 40), '-', animate='serial', panels=True, + head_marker='o', duration=1.5, frame_rate=10) + anim.draw_frame(0) + panels = [ax for ax in anim.figure.axes if _head_markers(ax)] + assert len(panels) == 3 + for ax in panels: + assert [len(_points(m)) for m in _head_markers(ax)] == [1] + + +def test_serial_head_markers_after_frame_0_are_where_they_were(): + """Past frame 0 a serial head marker is at the end of what its + dataset has revealed, and a dataset not yet reached has none.""" + data = _trajectories(3, 40) + anim = _quiet(data, '-', animate='serial', head_marker='o', + duration=1.5, frame_rate=10) + ax = anim.figure.axes[0] + for frame in range(1, anim.n_frames): + anim.draw_frame(frame) + for marker in _head_markers(ax): + shown = _points(_leader(ax, marker)) + assert len(_points(marker)) == min(1, len(shown)) + if len(shown): + assert np.allclose(_points(marker)[0], shown[-1]) + + +def test_a_serial_hue_head_marker_wears_the_first_rows_color_on_frame_0(): + x = _trajectories(1, 40) + anim = _quiet(x, '-', animate='serial', hue=np.linspace(0, 1, 40), + head_marker='o', duration=1.5, frame_rate=10) + ax = anim.figure.axes[0] + (marker,) = _head_markers(ax) + anim.draw_frame(0) + assert len(_points(marker)) == 1 + first = to_rgba(marker.get_color()) + anim.draw_frame(anim.n_frames - 1) + assert to_rgba(marker.get_color()) != first + anim.draw_frame(0) + assert to_rgba(marker.get_color()) == first + + +# --------------------------------------------------------------------------- +# D. the head_marker= dict: matplotlib's short names, a face color +# --------------------------------------------------------------------------- + +def _one_head_marker(spec, **kwargs): + anim = _quiet(_trajectories(1, 30), '-', animate=True, head_marker=spec, + duration=1, frame_rate=10, **kwargs) + anim.draw_frame(5) + (marker,) = _head_markers(anim.figure.axes[0]) + return marker + + +def test_head_marker_takes_matplotlibs_short_names(): + short = _one_head_marker({'marker': 'o', 'mec': 'k', 'mfc': 'none', + 'mew': 3, 'ms': 20}) + long = _one_head_marker({ + 'marker': 'o', 'markeredgecolor': 'k', 'markerfacecolor': 'none', + 'markeredgewidth': 3, 'markersize': 20}) + own = _one_head_marker({'marker': 'o', 'edgecolor': 'k', + 'facecolor': 'none', 'edgewidth': 3, 'size': 20}) + for marker in (short, long, own): + assert marker.get_markersize() == 20 + assert marker.get_markeredgewidth() == 3 + assert to_rgba(marker.get_markeredgecolor()) == to_rgba('k') + assert marker.get_markerfacecolor() == 'none' + + +def test_head_marker_face_color_is_its_own_key(): + marker = _one_head_marker({'marker': 's', 'facecolor': 'gold', + 'color': 'navy'}) + assert to_rgba(marker.get_markerfacecolor()) == to_rgba('gold') + assert to_rgba(marker.get_markeredgecolor()) == to_rgba('navy') + # without a face color the marker is filled with its `color` + plain = _one_head_marker({'marker': 's', 'color': 'navy'}) + assert to_rgba(plain.get_markerfacecolor()) == to_rgba('navy') + # `c` is `color`, `mfcalt`/`facecoloralt` the other half's fill + half = _one_head_marker({'marker': 'o', 'c': 'navy', 'fillstyle': 'left', + 'mfcalt': 'gold'}) + assert to_rgba(half.get_color()) == to_rgba('navy') + assert to_rgba(half.get_markerfacecoloralt()) == to_rgba('gold') + assert to_rgba(_one_head_marker( + {'fillstyle': 'left', 'facecoloralt': 'gold'} + ).get_markerfacecoloralt()) == to_rgba('gold') + + +def test_head_marker_face_color_is_drawn(): + """Pixels: the middle of a large head marker is the face color.""" + anim = _quiet(_trajectories(1, 30, 2), '-', animate=True, + head_marker={'marker': 'o', 'ms': 30, 'mfc': 'gold', + 'mec': 'k'}, + duration=1, frame_rate=10) + fig = anim.draw_frame(9).figure + fig.canvas.draw() + ax = fig.axes[0] + (marker,) = _head_markers(ax) + px, py = ax.transData.transform(_points(marker)[0]) + image = np.asarray(fig.canvas.buffer_rgba()) + pixel = image[image.shape[0] - 1 - int(round(py)), int(round(px)), :3] + assert np.allclose(pixel / 255.0, to_rgba('gold')[:3], atol=0.02) + + +def test_a_pinned_face_color_stays_while_hue_colors_the_edge(): + x = _trajectories(1, 30) + anim = _quiet(x, '-', animate=True, hue=np.linspace(0, 1, 30), + head_marker={'marker': 'o', 'mfc': 'gold'}, + duration=1, frame_rate=10) + (marker,) = _head_markers(anim.figure.axes[0]) + edges = [] + for frame in (1, 9): + anim.draw_frame(frame) + assert to_rgba(marker.get_markerfacecolor()) == to_rgba('gold') + edges.append(to_rgba(marker.get_markeredgecolor())) + assert edges[0] != edges[1] + + +@pytest.mark.parametrize('spec, names', [ + ({'size': 9, 'ms': 12}, ('size', 'ms')), + ({'mec': 'k', 'edgecolor': 'r'}, ('mec', 'edgecolor')), + ({'markerfacecolor': 'k', 'facecolor': 'r'}, + ('markerfacecolor', 'facecolor')), + ({'c': 'k', 'color': 'r'}, ('c', 'color')), +]) +def test_head_marker_refuses_one_option_under_two_names(spec, names): + with pytest.raises(ValueError, match='head_marker') as raised: + _one_head_marker(spec) + for name in names: + assert repr(name) in str(raised.value) + + +@pytest.mark.parametrize('spec', [ + {'ms': -3}, {'mew': 'wide'}, {'mfc': 'no such color'}, + {'facecolor': 'no such color'}, {'mec': 12.5}]) +def test_head_marker_short_names_have_their_values_checked(spec): + with pytest.raises(ValueError, match='head_marker') as raised: + _one_head_marker(spec) + assert repr(next(iter(spec))) in str(raised.value) + + +def test_head_marker_still_refuses_an_unknown_key(): + with pytest.raises(ValueError, match='not a supported head marker'): + _one_head_marker({'marker': 'o', 'linewidth': 3}) + + +def test_head_marker_short_names_inside_the_animate_dict(): + anim = _quiet(_trajectories(1, 30), '-', duration=1, frame_rate=10, + animate={'style': True, + 'head_marker': {'ms': 14, 'mfc': 'gold'}}) + (marker,) = _head_markers(anim.figure.axes[0]) + assert marker.get_markersize() == 14 + assert to_rgba(marker.get_markerfacecolor()) == to_rgba('gold') + + +# --------------------------------------------------------------------------- +# E. the trail_alpha= warning under 'window'; a hold= shorter than a frame +# --------------------------------------------------------------------------- + +def _warnings_of(**kwargs): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + out = hyp.plot(_trajectories(1, 40), '-', show=False, duration=1, + **kwargs) + return out, [str(w.message) for w in caught + if issubclass(w.category, UserWarning)] + + +@pytest.mark.parametrize('trail', [ + {'chemtrails': True}, {'precog': True}, {'bullettime': True}, {}]) +def test_trail_alpha_under_window_does_not_ask_for_a_flag_already_given( + trail): + _out, messages = _warnings_of(animate='window', trail_alpha=0.5, + frame_rate=10, **trail) + (message,) = [m for m in messages if m.startswith('trail_alpha=')] + assert "animate='window'" in message + assert 'Pass chemtrails=True' not in message + assert "animate=True or 'serial'" in message + + +def test_trail_alpha_without_a_trail_still_says_how_to_draw_one(): + _out, messages = _warnings_of(animate=True, trail_alpha=0.5, + frame_rate=10) + (message,) = [m for m in messages if m.startswith('trail_alpha=')] + assert 'Pass chemtrails=True' in message + _out, messages = _warnings_of(animate=True, trail_alpha=0.5, + chemtrails=True, frame_rate=10) + assert not [m for m in messages if 'trail_alpha' in m] + + +#: (frame rate, hold): holds on both sides of half a frame +HOLDS = [(rate, hold) for rate in (5, 10, 24, 30) + for hold in (0.01, 0.04, 0.1, 0.5, 1.0)] + + +@pytest.mark.parametrize('rate, hold', HOLDS) +def test_hold_is_rounded_to_frames_and_says_so_when_that_is_none(rate, hold): + """The rule: ``round(hold * frame_rate)`` repeats of the last frame. + A hold that rounds to no frame warns; any other adds its frames and + says nothing.""" + plain, _ = _warnings_of(animate=True, frame_rate=rate) + held, messages = _warnings_of(animate=True, frame_rate=rate, hold=hold) + about_hold = [m for m in messages if m.startswith('hold=')] + extra = int(round(hold * rate)) + assert held.n_frames - plain.n_frames == extra + if extra == 0: + (message,) = about_hold + assert 'adds no frame' in message + assert f'frame_rate={rate}' in message + else: + assert not about_hold + + +def test_the_shortest_hold_the_warning_names_adds_one_frame(): + for rate in (5, 10, 24, 30): + _out, messages = _warnings_of(animate=True, frame_rate=rate, + hold=0.001) + (message,) = [m for m in messages if m.startswith('hold=')] + shortest = float(message.split('Pass hold=')[1].split(' ')[0]) + plain, _ = _warnings_of(animate=True, frame_rate=rate) + held, again = _warnings_of(animate=True, frame_rate=rate, + hold=shortest) + assert held.n_frames == plain.n_frames + 1 + assert not [m for m in again if m.startswith('hold=')] + + +def test_a_short_hold_on_a_grid_warns_once(): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + anim = hyp.plot(_trajectories(2, 30), '-', animate=True, panels=True, + hold=0.01, duration=1, frame_rate=10, show=False) + assert anim.n_frames == 10 + assert len([w for w in caught + if str(w.message).startswith('hold=')]) == 1 + + +def test_hold_zero_says_nothing(): + _out, messages = _warnings_of(animate=True, frame_rate=10, hold=0) + assert not [m for m in messages if m.startswith('hold=')] + + +def _gif_seconds(path): + with Image.open(path) as im: + total = 0 + for index in range(getattr(im, 'n_frames', 1)): + im.seek(index) + total += im.info.get('duration', 0) + return total / 1000.0 + + +@pytest.mark.parametrize('rate', [5, 10, 25]) +def test_hold_in_a_saved_gif_at_several_frame_rates(tmp_path, rate): + """Read back from real files: the playing time grows by the held + frames, and not at all for a hold that rounds to none.""" + data = _trajectories(1, 40, 2) + seconds = {} + for name, hold in (('plain', None), ('none', 0.4 / rate), + ('one', 1.0 / rate), ('four', 4.0 / rate)): + path = str(tmp_path / f'{name}.gif') + _quiet(data, '-', animate=True, duration=1, frame_rate=rate, + hold=hold, save_path=path) + seconds[name] = _gif_seconds(path) + frame = 1.0 / rate + assert seconds['plain'] == pytest.approx(1.0, abs=0.5 * frame) + assert seconds['none'] == pytest.approx(seconds['plain'], abs=1e-6) + assert seconds['one'] - seconds['plain'] == pytest.approx( + frame, abs=0.011) + assert seconds['four'] - seconds['plain'] == pytest.approx( + 4 * frame, abs=0.011) + + +def _video_frames(path): + out = subprocess.run( + ['ffprobe', '-v', 'error', '-select_streams', 'v:0', + '-count_frames', '-show_entries', 'stream=nb_read_frames', + '-of', 'csv=p=0', str(path)], + capture_output=True, text=True, check=True) + return int(out.stdout.strip().split(',')[0]) + + +@pytest.mark.skipif(not HAS_FFMPEG, reason='ffmpeg/ffprobe not installed') +@pytest.mark.parametrize('rate', [10, 24, 30]) +def test_hold_in_a_saved_mp4_at_several_frame_rates(tmp_path, rate): + data = _trajectories(1, 40) + frames = {} + for name, hold in (('plain', None), ('none', 0.4 / rate), + ('one', 1.0 / rate), ('four', 4.0 / rate)): + path = tmp_path / f'{name}.mp4' + _quiet(data, '-', animate=True, duration=1, frame_rate=rate, + hold=hold, save_path=str(path)) + frames[name] = _video_frames(path) + assert frames['plain'] == rate + assert frames['none'] == rate + assert frames['one'] == rate + 1 + assert frames['four'] == rate + 4 diff --git a/tests/test_review_round5_1_2_1.py b/tests/test_review_round5_1_2_1.py new file mode 100644 index 00000000..38fd8e1c --- /dev/null +++ b/tests/test_review_round5_1_2_1.py @@ -0,0 +1,1099 @@ +"""1.2.1 review round 5: an animation's labels are placed on every frame. + +The owner's rule (2026-11-23): axis labels move with the rotation and +stay with their axes; the labels of individual datapoints have correct +positioning in every frame, may shift from frame to frame but must not +wobble back and forth; legends, titles and other static text are laid +out once, for the worst case over all frames, and then do not move. + +A. On every frame the datapoint labels are at their points, off the + legend, the titles, the suptitle and the caption, and on the canvas; + they cover each other far less than labels left at the usual place. +B. They do not wobble: no label's offset turns back within the time of + one glide, and a label never jumps (it glides) unless a glide would + carry it over static content. +C. A frame is the same picture whatever was drawn before it, in a new + identical call and in a saved file. +D. Static content has the same extent on every frame, and a 3-D plot's + axis labels turn with the cube without leaving the canvas or + touching static content. + +Real figures and real frames, rendered headless; saved files are read +back. Nothing is mocked, and no assertion depends on a font's absolute +metrics: boxes are measured where they were drawn and compared with +each other. +""" +import itertools +import warnings + +import matplotlib +matplotlib.use('Agg') + +import matplotlib.pyplot as plt # noqa: E402 +import numpy as np # noqa: E402 +import pytest # noqa: E402 +from matplotlib.animation import PillowWriter # noqa: E402 +from PIL import Image # noqa: E402 + +import hypertools as hyp # noqa: E402 +from hypertools.plot import matplotlib_backend as backend # noqa: E402 +from hypertools.plot.matplotlib_backend import label_tracks # noqa: E402 + + +def _walk(seed, rows=40, cols=3): + return np.random.default_rng(seed).normal(size=(rows, cols)).cumsum(0) + + +CLOUD = np.random.default_rng(3).standard_normal((30, 3)) +NAMES = [f'Subject {i}' for i in range(len(CLOUD))] + + +@pytest.fixture(autouse=True) +def _close_figures(): + yield + plt.close('all') + + +def _quiet(*args, **kwargs): + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + return hyp.plot(*args, show=False, **kwargs) + + +def _spin8(**kwargs): + return _quiet(CLOUD[:8], 'o', labels=NAMES[:8], animate='spin', + **{'duration': 4, 'frame_rate': 15, **kwargs}) + + +def _spin12_dressed(**kwargs): + return _quiet([CLOUD[:6], CLOUD[6:12]], 'o', + labels=[NAMES[:6], NAMES[6:12]], animate='spin', + legend=['first', 'second'], title='A title', + suptitle='Above it all', caption='A caption under it', + **{'duration': 4, 'frame_rate': 15, **kwargs}) + + +def _spin30_dressed(**kwargs): + return _quiet([CLOUD[:15], CLOUD[15:]], 'o', + labels=[NAMES[:15], NAMES[15:]], animate='spin', + legend=['first', 'second'], title='A title', + caption='A caption under it', + **{'duration': 4, 'frame_rate': 15, **kwargs}) + + +def _window3d(**kwargs): + return _quiet(CLOUD, 'o', labels=NAMES, animate='window', + **{'duration': 4, 'frame_rate': 15, **kwargs}) + + +def _window2d(**kwargs): + data = [_walk(1, cols=2), _walk(2, cols=2)] + names = [[f'{letter}{k}' if k % 3 == 0 else None for k in range(40)] + for letter in 'ab'] + return _quiet(data, '-o', labels=names, legend=['a', 'b'], + title='Two walks', animate='window', + **{'duration': 4, 'frame_rate': 15, **kwargs}) + + +def _serial2d(**kwargs): + return _quiet(CLOUD[:, :2], 'o', labels=NAMES, animate='serial', + title='One at a time', + **{'duration': 4, 'frame_rate': 15, **kwargs}) + + +def _panels(**kwargs): + data = [np.random.default_rng(seed).normal(size=(12, 3)) + for seed in range(4)] + names = [[f'p{seed}-{i}' for i in range(12)] for seed in range(4)] + return _quiet(data, 'o', panels=(2, 2), labels=names, + legend=list('abcd'), title=list('ABCD'), suptitle='S', + caption='A caption', animate='spin', + **{'duration': 4, 'frame_rate': 15, **kwargs}) + + +ANIMATIONS = { + 'spin, 8 labels': _spin8, + 'spin, 12 labels, legend, title, suptitle, caption': _spin12_dressed, + 'spin, 30 labels, legend, title, caption': _spin30_dressed, + 'window, 3-D': _window3d, + 'window, 2-D, two lines': _window2d, + 'serial, 2-D': _serial2d, + '2 x 2 panels': _panels, +} +#: the animations whose points pass each other on screen (the cube +#: turns), with few enough labels that every label has a free place +PASSING = ['spin, 30 labels, legend, title, caption', + '2 x 2 panels'] + + +def _labeled_axes(fig): + return [ax for ax in fig.axes + if getattr(ax, '_hyp_labels_and_points', None)] + + +def _labels(ax): + return [entry[0] for entry in ax._hyp_labels_and_points] + + +def _static_artists(fig): + """Everything that must not move during an animation: legends, + figure texts (suptitle, caption) and the panels' titles.""" + found = list(fig.legends) + [text for text in fig.texts + if text.get_text().strip()] + for ax in fig.axes: + if ax.get_legend() is not None: + found.append(ax.get_legend()) + if ax.title.get_text().strip(): + found.append(ax.title) + return found + + +def _show(anim, frame): + anim.draw_frame(int(frame)) + anim.figure.canvas.draw() + return anim.figure.canvas.get_renderer() + + +def _pixels(anim, frame): + _show(anim, frame) + return np.asarray(anim.figure.canvas.buffer_rgba()).copy() + + +def _census(anim): + """Over every frame: pairs of label boxes of one axes that overlap, + label boxes on static content, label boxes that leave the canvas, + and how many label boxes were looked at.""" + fig = anim.figure + counts = dict(pairs=0, on_static=0, off_canvas=0, boxes=0) + for frame in range(anim.n_frames): + renderer = _show(anim, frame) + static = [artist.get_window_extent(renderer) + for artist in _static_artists(fig)] + for ax in _labeled_axes(fig): + boxes = [label.get_bbox_patch().get_window_extent(renderer) + for label in _labels(ax) if label.get_visible()] + counts['boxes'] += len(boxes) + counts['pairs'] += sum( + 1 for one, other in itertools.combinations(boxes, 2) + if one.overlaps(other)) + counts['on_static'] += sum( + 1 for box in boxes for other in static + if box.overlaps(other)) + # (half a pixel: a box edge is drawn across a pixel) + counts['off_canvas'] += sum( + 1 for box in boxes + if box.x0 < -0.5 or box.y0 < -0.5 + or box.x1 > fig.bbox.width + 0.5 + or box.y1 > fig.bbox.height + 0.5) + return counts + + +def _leave_labels_at_the_usual_place(anim): + """Replace every table of `anim` by one that leaves each label up + and to the left of its point on every frame (where 1.2.0 drew it).""" + home = backend._LABEL_CANDIDATES.index(backend._LABEL_HOME) + for ax in _labeled_axes(anim.figure): + tracks = label_tracks(ax) + sizes = np.array([backend._label_size_pt(ref()) + for ref in tracks['labels']]) + usual = backend._label_center_offsets( + np.full(tracks['places'].shape, home), sizes) + tracks['offsets'] = np.where(tracks['shown'][..., None], usual, + np.nan) + + +def _turns_back(track, window, tolerance=1.0): + """How many times the series `track` (one component of a label's + offset, in points, NaN while the label is hidden) goes more than + `tolerance` one way and then more than `tolerance` back, both within + `window` frames of the turn.""" + count, inside = 0, False + for t in range(1, len(track) - 1): + before = track[max(0, t - window):t] + after = track[t + 1:t + 1 + window] + turn = False + if not (np.isnan(track[t]) or np.isnan(before).any() + or np.isnan(after).any()): + peak = (track[t] - before.min() > tolerance + and track[t] - after.min() > tolerance) + trough = (before.max() - track[t] > tolerance + and after.max() - track[t] > tolerance) + turn = peak or trough + count += turn and not inside + inside = turn + return count + + +def _wobbles(anim): + """Turns back within one glide's time, summed over every label and + both components; and the largest change of an offset between two + frames, in points, outside the frames a label was made to jump.""" + turns, step = 0, 0.0 + for ax in _labeled_axes(anim.figure): + tracks = label_tracks(ax) + offsets, window = tracks['offsets'], tracks['ease_frames'] + if tracks['periodic']: + # (round the loop: the last frame leads into the first) + offsets = np.concatenate([offsets, offsets[:window + 1]]) + for k in range(offsets.shape[1]): + for component in range(2): + turns += _turns_back(offsets[:, k, component], window) + moved = np.abs(np.diff(offsets, axis=0)).max(axis=2) + forced = tracks['forced'] + if tracks['periodic']: + forced = np.concatenate([forced, forced[:window + 1]]) + moved[forced[1:] | forced[:-1]] = np.nan + if np.isfinite(moved).any(): + step = max(step, float(np.nanmax(moved))) + return turns, step + + +# -------------------------------------------------------------------------- +# A. every frame's labels are placed for that frame + +@pytest.mark.parametrize('name', list(ANIMATIONS)) +def test_labels_keep_off_static_content_and_on_the_canvas_every_frame(name): + anim = ANIMATIONS[name]() + assert anim.n_frames == 60 + counts = _census(anim) + assert counts['boxes'] > 60 + assert counts['on_static'] == 0 + assert counts['off_canvas'] == 0 + + +def _pairs_per_frame(anim): + """Per frame, how many pairs of label boxes of one axes overlap, as + the frame is drawn.""" + fig = anim.figure + pairs = [] + for frame in range(anim.n_frames): + renderer = _show(anim, frame) + count = 0 + # (all the figure's labels together: in a grid a panel's labels + # must keep off the next panel's too) + for boxes in [[label.get_bbox_patch().get_window_extent(renderer) + for ax in _labeled_axes(fig) + for label in _labels(ax) if label.get_visible()]]: + count += sum(1 for one, other in itertools.combinations(boxes, 2) + if one.overlaps(other)) + pairs.append(count) + return np.array(pairs) + + +@pytest.mark.parametrize('name', [ + 'spin, 8 labels', + 'spin, 12 labels, legend, title, suptitle, caption', + 'window, 3-D', + 'window, 2-D, two lines', + 'serial, 2-D']) +def test_no_two_labels_overlap_on_any_frame(name): + """With a dozen labels on a plot (the sliding windows show fewer at + a time) no label's box is on another's on any frame, glides from + place to place included. Review round 5 had 20 to 30 frames of 60 + with stacked labels in the spins (a label was left under another + for up to a second and a half rather than moved).""" + anim = ANIMATIONS[name]() + pairs = _pairs_per_frame(anim) + assert len(pairs) == 60 + assert pairs.max() == 0, pairs.tolist() + + +def test_a_grids_labels_overlap_on_few_frames(): + """A 2 x 2 grid with 12 labels a panel (48 on one default-size + figure, each panel's kept out of the other panels and off the other + panels' labels) has less room than a single plot: at most two pairs + of labels overlap at a time, on at most a quarter of the frames + (measured: one pair on 4 frames of 60 with matplotlib 3.10, whose + text is narrower, more with 3.11; review round 5 had pairs on 55 + frames, up to 7 at once).""" + anim = _panels() + pairs = _pairs_per_frame(anim) + assert pairs.max() <= 2, pairs.tolist() + assert (pairs > 0).sum() <= 15, pairs.tolist() + + +def test_thirty_labels_overlap_less_than_stills_of_each_frame(): + """30 labels on a default-size cube that turns once in four seconds + are more than can be kept apart on every frame without hopping, and + the bound is what the rule of a static figure reaches when it places + each frame on its own, free to move every label on every frame + (4 to 10 pairs a frame, 5.6 on average, with 164 turn-backs): the + planned labels have at most one pair more than that on any frame, + never more than its worst frame, under a third as many in all, and + no pair at all on a quarter of the frames (measured: 0.9 a frame, + at most 3, no pair on 23 frames of 60 with matplotlib 3.10; 1.3 a + frame and at most 6 with the wider text of 3.11).""" + anim = ANIMATIONS['spin, 30 labels, legend, title, caption']() + planned = _pairs_per_frame(anim) + for ax in _labeled_axes(anim.figure): + backend.solve_label_tracks(ax, _independent=True) + stills = _pairs_per_frame(anim) + assert stills.sum() > 120 + assert (planned <= stills + 1).all(), (planned - stills).tolist() + assert planned.max() <= stills.max(), planned.tolist() + assert planned.sum() <= stills.sum() / 3, (planned.sum(), stills.sum()) + assert (planned == 0).sum() >= 15 + + +@pytest.mark.parametrize('name, share', [ + ('spin, 8 labels', 0.25), + ('spin, 12 labels, legend, title, suptitle, caption', 0.25), + ('spin, 30 labels, legend, title, caption', 0.25), + ('window, 3-D', 0.25), + ('2 x 2 panels', 0.25)]) +def test_labels_cover_each_other_far_less_than_at_the_usual_place( + name, share): + """Summed over all frames, the pairs of labels that overlap are a + fraction of what they are with every label left up and to the left + of its point (1.2.0, and what a label placed once for frame 0 drifts + back toward as the cube turns).""" + anim = ANIMATIONS[name]() + placed = _census(anim)['pairs'] + _leave_labels_at_the_usual_place(anim) + usual = _census(anim)['pairs'] + assert usual > 0 + assert placed <= share * usual, (placed, usual) + + +def test_a_label_is_drawn_where_the_table_has_it(): + """The table's offsets are what is drawn: on every frame the middle + of each label's box is that far from the label's point.""" + anim = _spin8() + fig = anim.figure + (ax,) = _labeled_axes(fig) + tracks = label_tracks(ax) + scale = fig.dpi / 72.0 + for frame in range(0, anim.n_frames, 7): + renderer = _show(anim, frame) + for k, label in enumerate(_labels(ax)): + box = label.get_bbox_patch().get_window_extent(renderer) + anchor = ax.transData.transform(label.xy) + drawn = (0.5 * (box.x0 + box.x1) - anchor[0], + 0.5 * (box.y0 + box.y1) - anchor[1]) + np.testing.assert_allclose( + drawn, tracks['offsets'][frame, k] * scale, atol=1.5) + + +def test_labels_follow_their_points_as_the_cube_turns(): + """Each label's arrow ends on its point's projection in the frame's + own view, and the points do move.""" + from mpl_toolkits.mplot3d import proj3d + anim = _spin8() + (ax,) = _labeled_axes(anim.figure) + seen = [] + for frame in (0, 15, 30, 45): + _show(anim, frame) + spots = [] + for label, x, y, z in ax._hyp_labels_and_points: + x2, y2, _ = proj3d.proj_transform(x, y, z, ax.get_proj()) + np.testing.assert_allclose( + ax.transData.transform(label.xy), + ax.transData.transform((x2, y2)), atol=0.5) + spots.append(ax.transData.transform(label.xy)) + seen.append(np.array(spots)) + assert np.abs(seen[0] - seen[2]).max() > 20.0 + + +@pytest.mark.parametrize('make', [_window3d, _window2d, _serial2d]) +def test_labels_of_points_not_shown_are_hidden(make): + """A label is shown on exactly the frames the table has an offset + for it, some labels are hidden on some frames, and a label that has + come into view is at a real place.""" + anim = make() + (ax,) = _labeled_axes(anim.figure) + tracks = label_tracks(ax) + assert not tracks['shown'].all() and tracks['shown'].any() + for frame in range(0, anim.n_frames, 5): + _show(anim, frame) + visible = [label.get_visible() for label in _labels(ax)] + assert visible == list(tracks['shown'][frame]) + assert np.array_equal(np.isfinite(tracks['offsets'][frame, :, 0]), + tracks['shown'][frame]) + + +# -------------------------------------------------------------------------- +# B. no wobble + +@pytest.mark.parametrize('name', list(ANIMATIONS)) +def test_no_label_turns_back_within_a_glide(name): + """Points pass each other as the cube turns, so labels have to + change places; no label's offset goes one way and then back by more + than a point within the time of one glide (round the loop too, for + an animation that loops). Placing every frame on its own, which is + what the rule would be without the table, does turn back.""" + anim = ANIMATIONS[name]() + turns, _step = _wobbles(anim) + assert turns == 0 + if name in PASSING: + moved = sum(int((label_tracks(ax)['places'][1:] + != label_tracks(ax)['places'][:-1]).sum()) + for ax in _labeled_axes(anim.figure)) + assert moved > 0 # (labels did change places) + for ax in _labeled_axes(anim.figure): + backend.solve_label_tracks(ax, _independent=True) + alone, _step = _wobbles(anim) + assert alone > 0 + + +@pytest.mark.parametrize('name', PASSING) +def test_a_label_glides_to_its_next_place(name): + """Between two frames a label moves by no more than 0.35 of the way + from one place to the next (a glide takes at least five frames), + where placing every frame on its own jumps the whole way at once.""" + anim = ANIMATIONS[name]() + _turns, step = _wobbles(anim) + jump = 0.0 + for ax in _labeled_axes(anim.figure): + tracks = label_tracks(ax) + assert tracks['ease_frames'] >= 5 + sizes = np.array([backend._label_size_pt(ref()) + for ref in tracks['labels']]) + targets = backend._label_center_offsets( + tracks['places'], sizes, tracks['candidates']) + change = np.abs(np.diff(targets, axis=0)).max(axis=2) + jump = max(jump, float(change.max())) + assert jump > 20.0 # (some label changed places) + assert 0.0 < step <= 0.35 * jump, (step, jump) + for ax in _labeled_axes(anim.figure): + backend.solve_label_tracks(ax, _independent=True) + _turns, alone = _wobbles(anim) + assert alone > 2.0 * step + + +def test_a_looping_spin_has_no_seam(): + """A spin of whole turns leads from its last frame back into its + first: the labels are placed round the loop, so no label is further + from where it is on frame 0 than one frame's glide.""" + anim = _spin8() + (ax,) = _labeled_axes(anim.figure) + tracks = label_tracks(ax) + assert tracks['periodic'] + offsets = tracks['offsets'] + seam = np.abs(offsets[0] - offsets[-1]).max() + inside = np.abs(np.diff(offsets, axis=0)).max() + assert seam <= inside + 1e-9 + # ...and a reveal, whose last frame shows everything and whose first + # shows one point, is not taken for a loop + (window_ax,) = _labeled_axes(_window3d().figure) + assert not label_tracks(window_ax)['periodic'] + + +# -------------------------------------------------------------------------- +# C. a frame is a function of the animation and its index + +class _KeepFrames(PillowWriter): + """Pillow's own gif writer, which also keeps the frames it was given + so they can be compared with frames drawn one at a time.""" + + def finish(self): + self.kept = [np.asarray(frame.convert('RGBA')).copy() + for frame in self._frames] + super().finish() + + +@pytest.mark.parametrize('name', ['spin, 8 labels', + 'spin, 12 labels, legend, title, ' + 'suptitle, caption', + 'window, 3-D', 'window, 2-D, two lines', + '2 x 2 panels']) +def test_a_frame_is_the_same_picture_however_it_is_reached(name, tmp_path): + """Frame k drawn in order, in a shuffled order, backwards, as the + only frame ever drawn of a second identical call, and as handed to + the writer of a saved gif: the same pixels.""" + make = ANIMATIONS[name] + anim = make(duration=2, frame_rate=10) + n = anim.n_frames + forward = [_pixels(anim, i) for i in range(n)] + assert any(not np.array_equal(forward[0], other) + for other in forward[1:]) + order = list(np.random.default_rng(0).permutation(n)) \ + + list(range(n))[::-1] + for i in order: + assert np.array_equal(_pixels(anim, i), forward[i]), i + for k in (n // 2, n - 1, 0): + fresh = make(duration=2, frame_rate=10) + assert np.array_equal(_pixels(fresh, k), forward[k]), k + plt.close(fresh.figure) + _show(anim, n // 3) + writer = _KeepFrames(fps=10) + path = tmp_path / 'saved.gif' + anim.animation.save(str(path), writer=writer) + assert len(writer.kept) == n + for i, saved in enumerate(writer.kept): + assert np.array_equal(saved, forward[i]), i + with Image.open(path) as saved: + assert saved.n_frames == n + saved.seek(n // 2) + middle = np.asarray(saved.convert('RGBA')).astype(float) + # (a gif stores 256 colors, so the file is compared loosely) + assert np.abs(middle - forward[n // 2]).mean() < 4.0 + assert (np.abs(middle - forward[n // 2]).mean() + < np.abs(middle - forward[0]).mean()) + + +def test_the_table_is_the_same_whenever_it_is_worked_out(): + """Worked out again after frames were drawn in any order, the table + is the same, number for number.""" + anim = _spin12_dressed() + (ax,) = _labeled_axes(anim.figure) + first = label_tracks(ax)['offsets'].copy() + for frame in (41, 3, 59, 17): + _show(anim, frame) + again = backend.solve_label_tracks(ax)['offsets'] + assert np.array_equal(first, again, equal_nan=True) + twin = _spin12_dressed() + (twin_ax,) = _labeled_axes(twin.figure) + assert np.array_equal(first, label_tracks(twin_ax)['offsets'], + equal_nan=True) + + +def test_a_resized_figure_has_its_labels_placed_again(): + """The table is made for the figure's size: after the figure is + given another size the next frame works it out again, and the + labels are on the canvas and off static content at the new size.""" + anim = _spin12_dressed() + fig = anim.figure + (ax,) = _labeled_axes(fig) + before = label_tracks(ax) + width, height = fig.get_size_inches() + fig.set_size_inches(0.8 * width, 0.8 * height) + _show(anim, 5) + assert label_tracks(ax) is not before + counts = _census(anim) + assert counts['off_canvas'] == 0 and counts['on_static'] == 0 + + +# -------------------------------------------------------------------------- +# D. static content is laid out once; axis labels turn with the cube + +def _layout(fig, renderer): + extents = [tuple(np.round(artist.get_window_extent(renderer).extents, 3)) + for artist in _static_artists(fig)] + boxes = [tuple(np.round(ax.get_position().bounds, 9)) + for ax in fig.axes] + zooms = [tuple(np.round(ax.get_box_aspect(), 9)) + for ax in fig.axes if hasattr(ax, 'get_proj')] + return extents, boxes, zooms, tuple(fig.get_size_inches()) + + +@pytest.mark.parametrize('name', list(ANIMATIONS)) +def test_static_content_is_the_same_on_every_frame(name): + """Legends, titles, suptitle, caption, every axes' box, every cube's + size and the figure's size: identical on all frames.""" + anim = ANIMATIONS[name]() + fig = anim.figure + first = _layout(fig, _show(anim, 0)) + assert len(first[0]) + len(first[1]) >= 1 + for frame in range(1, anim.n_frames): + assert _layout(fig, _show(anim, frame)) == first, frame + + +def _axis_texts(ax): + return [axis3d.label for axis3d in ax._axis_map.values() + if axis3d.label.get_text().strip()] + + +AXIS_LABELED = { + 'landscape': dict(), + 'square, legend': dict(size=(5, 5), legend=['first', 'second']), + 'square, legend inside': dict( + size=(5, 5), legend=['first', 'second'], + legend_kwargs={'loc': 'upper left'}), + 'legend, title, suptitle, caption': dict( + legend=['first', 'second'], title='A title', suptitle='Above', + caption='A caption under the plot'), + 'colorbar': dict(hue=[np.linspace(0, 1, 15)] * 2, colorbar=True), + 'two turns back': dict(rotations=-2), +} + + +@pytest.mark.parametrize('name', list(AXIS_LABELED)) +def test_axis_labels_turn_with_the_cube_inside_the_canvas(name): + """A single animated 3-D plot's axis labels were fitted for no view + at all: on a square figure "the z axis" was 61 px off the canvas for + part of the turn, and with a legend, a title and a caption the + labels crossed them on 6 frames of 60. On EVERY frame each axis + label is on the canvas and off the static content, the static + content does not move, and the labels do move with the cube.""" + anim = _quiet([CLOUD[:15], CLOUD[15:]], 'o', animate='spin', + xlabel='the x axis', ylabel='the y axis', + zlabel='the z axis', duration=4, frame_rate=15, + **AXIS_LABELED[name]) + fig = anim.figure + ax = fig.axes[0] + width, height = fig.bbox.width, fig.bbox.height + first, places = None, [] + for frame in range(anim.n_frames): + renderer = _show(anim, frame) + layout = _layout(fig, renderer) + first = layout if first is None else first + assert layout == first, frame + static = [artist.get_window_extent(renderer) + for artist in _static_artists(fig)] + static += [other.get_tightbbox(renderer) for other in fig.axes + if other is not ax] + texts = _axis_texts(ax) + assert len(texts) == 3 + boxes = [text.get_window_extent(renderer) for text in texts] + places.append([box.extents for box in boxes]) + for text, box in zip(texts, boxes): + assert box.x0 >= 0 and box.y0 >= 0 and box.x1 <= width \ + and box.y1 <= height, (frame, text.get_text(), box.extents) + assert not any(box.overlaps(other) for other in static), ( + frame, text.get_text()) + places = np.array(places) + assert np.ptp(places[:, :, 0], axis=0).min() > 5.0 + + +def test_datapoint_labels_keep_off_the_axis_labels_as_they_turn(): + """The cube's axis labels hang where the labels of points near its + edges want to go: on every frame no datapoint label covers one.""" + anim = _quiet(CLOUD[:12], 'o', labels=NAMES[:12], animate='spin', + xlabel='the x axis', ylabel='the y axis', + zlabel='the z axis', legend=['data'], title='A title', + duration=4, frame_rate=15) + fig = anim.figure + (ax,) = _labeled_axes(fig) + covered = glided = 0 + tracks = label_tracks(ax) + half = tracks['ease_frames'] + moving = (tracks['places'] != np.roll(tracks['places'], half, axis=0)) + for frame in range(anim.n_frames): + renderer = _show(anim, frame) + texts = [text.get_window_extent(renderer) + for text in _axis_texts(ax)] + for k, label in enumerate(_labels(ax)): + box = label.get_bbox_patch().get_window_extent(renderer) + if any(box.overlaps(text) for text in texts): + # (a label gliding from one place to the next may pass + # an axis label that is itself turning) + covered += not moving[frame, k] + glided += bool(moving[frame, k]) + assert covered == 0 + assert glided <= 12 + + +def test_a_label_does_not_reach_into_the_next_panel(): + """A label that reached into the next panel of a grid was painted + over by that panel's background, cut off at its edge. On every frame + each label's box stays off every other panel.""" + anim = _panels() + fig = anim.figure + panels = _labeled_axes(fig) + assert len(panels) == 4 + inside = 0 + for frame in range(0, anim.n_frames, 3): + renderer = _show(anim, frame) + for ax in panels: + others = [other.get_window_extent(renderer) + for other in panels if other is not ax] + for label in _labels(ax): + box = label.get_bbox_patch().get_window_extent(renderer) + inside += any(box.overlaps(other) for other in others) + assert inside == 0 + + +@pytest.mark.parametrize('dressed', [False, True]) +def test_a_grids_axis_labels_stay_on_the_canvas_and_apart_every_frame( + dressed): + """An animated grid's cubes are fitted with their axis labels at a + sample of the views (every 30 degrees): checked here on EVERY frame, + no axis label leaves the canvas, lies on static content or meets a + label of another panel.""" + data = [np.random.default_rng(seed).normal(size=(12, 3)) + for seed in range(4)] + extra = dict(legend=list('abcd'), title=list('ABCD'), suptitle='S', + caption='A caption') if dressed else {} + anim = _quiet(data, 'o', panels=(2, 2), xlabel='the x axis', + ylabel='the y axis', zlabel='the z axis', animate='spin', + duration=4, frame_rate=15, **extra) + fig = anim.figure + panels = [ax for ax in fig.axes if hasattr(ax, 'get_proj')] + first = None + for frame in range(anim.n_frames): + renderer = _show(anim, frame) + layout = _layout(fig, renderer) + first = layout if first is None else first + assert layout == first, frame + static = [artist.get_window_extent(renderer) + for artist in _static_artists(fig)] + boxes = [[text.get_window_extent(renderer) + for text in _axis_texts(ax) if text.get_visible()] + for ax in panels] + assert sum(map(len, boxes)) >= 3 + for k, own in enumerate(boxes): + for box in own: + assert box.x0 >= 0 and box.y0 >= 0 \ + and box.x1 <= fig.bbox.width \ + and box.y1 <= fig.bbox.height, frame + assert not any(box.overlaps(other) for other in static), frame + assert not any(box.overlaps(other) + for others in boxes[k + 1:] + for other in others), frame + + +# -------------------------------------------------------------------------- +# Third pass: what a source review of the planner found (memory, a leak, +# pickled figures, a plan gone stale), and edge inputs + +def _table_bytes(tracks): + return sum(value.nbytes for value in tracks.values() + if isinstance(value, np.ndarray)) + + +def test_more_labels_than_are_arranged_store_nothing_per_frame(): + """Above 300 labels the labels stay at their usual places. The table + had a row for every frame all the same (58 bytes a label and frame: + 13.9 MB for 400 labels on 600 frames, more than 10 GB for 10000 + labels on 18000) and every frame was run to fill it. It has one + row, whatever the number of frames, and working it out again + allocates next to nothing.""" + import tracemalloc + rng = np.random.default_rng(3) + names = [f'S{i}' for i in range(400)] + sizes = {} + for duration in (2, 20): + anim = _quiet(rng.normal(size=(400, 3)), 'o', labels=names, + animate='spin', duration=duration, frame_rate=30) + ax = _labeled_axes(anim.figure)[0] + tracks = label_tracks(ax) + assert tracks['n_frames'] == anim.n_frames == 30 * duration + assert tracks['offsets'].shape == (1, 400, 2) + sizes[duration] = _table_bytes(tracks) + tracemalloc.start() + backend.solve_label_tracks(ax) + _now, peak = tracemalloc.get_traced_memory() + tracemalloc.stop() + assert peak < 2_000_000, peak + # every frame shows every label at its usual place + home = backend._label_center_offsets( + np.zeros(400, dtype=int), + np.array([backend._label_size_pt(label) + for label in _labels(ax)])) + for frame in (0, anim.n_frames // 2, anim.n_frames - 1): + anim.draw_frame(frame) + assert np.allclose([label.xyann for label in _labels(ax)], + home, atol=1e-4) + plt.close(anim.figure) + assert sizes[2] == sizes[20] <= 400 * 28 + + +def test_a_long_animation_is_planned_at_a_bounded_number_of_frames(): + """30 labels on 300 frames are more labels x frames than are planned + one by one (`_LABEL_TRACK_BUDGET`): 120 evenly spaced frames are + planned, the table is no larger than 28 bytes a label and planned + frame however long the animation, and between two planned frames a + label is drawn between its offsets on the two (the same picture + whichever frames were drawn before). Planning every frame took time + in proportion to the frames: 30 CPU seconds for 60 labels on 600 + frames, against 1.6 on 60.""" + anim = _quiet([CLOUD[:15], CLOUD[15:]], 'o', + labels=[NAMES[:15], NAMES[15:]], animate='spin', + duration=10, frame_rate=30) + assert anim.n_frames == 300 + ax = _labeled_axes(anim.figure)[0] + tracks = label_tracks(ax) + keys = tracks['frames'] + assert len(keys) == backend._LABEL_TRACK_BUDGET // 30 == 120 + assert keys[0] == 0 and keys[-1] == 299 + assert tracks['offsets'].shape == (120, 30, 2) + assert tracks['offsets'].dtype == np.float32 + assert _table_bytes(tracks) <= 28 * 30 * 120 + keys.nbytes + labels = _labels(ax) + # a planned frame shows its row; a frame between two is between them + low, high = int(keys[40]), int(keys[41]) + assert high - low >= 2 + seen = {} + for frame in (high, low + 1, low, low + 1): + anim.draw_frame(frame) + seen.setdefault(frame, []).append( + np.array([label.xyann for label in labels])) + assert np.allclose(seen[low][0], tracks['offsets'][40], atol=1e-4) + assert np.allclose(seen[high][0], tracks['offsets'][41], atol=1e-4) + assert np.array_equal(seen[low + 1][0], seen[low + 1][1]) + share = 1.0 / (high - low) + assert np.allclose( + seen[low + 1][0], + (1 - share) * tracks['offsets'][40] + share * tracks['offsets'][41], + atol=1e-3) + turns, _step = _wobbles(anim) + assert turns == 0 + # and the labels are still kept apart on the frames between + pairs = [] + for frame in range(0, 300, 7): + renderer = _show(anim, frame) + boxes = [label.get_bbox_patch().get_window_extent(renderer) + for label in labels] + pairs.append(sum(1 for one, other in itertools.combinations(boxes, 2) + if one.overlaps(other))) + assert np.mean(pairs) <= 2.0, pairs + + +def test_closed_figures_with_labels_are_freed(): + """The labels' state held the animation's frame function, which + refers to the animation and its axes, as the value of a dictionary + keyed weakly by that axes: the key never died, and every closed + animated figure with labels stayed allocated with its table. (And + the last static figure with labels was kept by a module global.)""" + import gc + import weakref + gc.collect() + before = len(backend._LABEL_STATES) + alive = [] + for make in (_spin8, _panels, _window2d): + for _again in range(2): + anim = make(duration=1, frame_rate=10) + anim.draw_frame(3) + anim.figure.canvas.draw() + alive.append(weakref.ref(anim.figure)) + alive.extend(weakref.ref(ax) for ax in anim.figure.axes) + plt.close(anim.figure) + del anim + for _again in range(2): + fig = _quiet(CLOUD[:8], 'o', labels=NAMES[:8]) + fig.canvas.draw() + alive.append(weakref.ref(fig)) + plt.close(fig) + del fig + gc.collect() + gc.collect() + assert [ref() for ref in alive if ref() is not None] == [] + assert len(backend._LABEL_STATES) == before + + +def test_an_animation_outlives_nothing_it_needs(): + """The frame function is held weakly, by the labels' state; the + animation keeps it, so the plan can still be made again while the + animation lives (a resized figure), garbage collection or not.""" + import gc + anim = _spin8() + gc.collect() + ax = _labeled_axes(anim.figure)[0] + first = label_tracks(ax) + anim.figure.set_size_inches(9, 7) + anim.draw_frame(5) + assert label_tracks(ax) is not first + assert label_tracks(ax)['offsets'].shape == first['offsets'].shape + + +@pytest.mark.parametrize('how', ['pickle', 'deepcopy']) +@pytest.mark.parametrize('kind', ['animated', 'static']) +def test_a_copied_or_unpickled_figure_draws(kind, how, tmp_path): + """`pickle.loads(pickle.dumps(anim.figure)).canvas.draw()` raised + ``TypeError: cannot unpack non-iterable NoneType object``: a planned + label has no named place, and the copy has no plan. A figure read + back from a pickle, or copied, has no animation to follow: its + labels stay exactly where the frame it was copied at had them, it + draws, and it saves. A static figure's labels are arranged as + before.""" + import copy + import pickle + if kind == 'animated': + anim = _spin12_dressed() + fig = anim.figure + anim.draw_frame(17) + else: + fig = _quiet(CLOUD[:12], 'o', labels=NAMES[:12]) + fig.canvas.draw() + was = [(label.get_text(), tuple(np.round(label.xyann, 4)), + label.get_ha(), label.get_va()) + for label in _labels(_labeled_axes(fig)[0])] + new = (pickle.loads(pickle.dumps(fig)) if how == 'pickle' + else copy.deepcopy(fig)) + new.canvas.draw() + new.savefig(tmp_path / 'restored.png') + new.canvas.draw() + assert (tmp_path / 'restored.png').stat().st_size > 5000 + ax = _labeled_axes(new)[0] + assert label_tracks(ax) is None + now = [(label.get_text(), tuple(np.round(label.xyann, 4)), + label.get_ha(), label.get_va()) for label in _labels(ax)] + assert now == was + renderer = new._get_renderer() + boxes = [label.get_bbox_patch().get_window_extent(renderer) + for label in _labels(ax)] + assert not any(one.overlaps(other) + for one, other in itertools.combinations(boxes, 2)) + plt.close(new) + + +def test_a_text_added_to_the_figure_is_planned_for(): + """The plan was made again only for another figure size, axes box or + set of labels: a ``fig.text`` put on top of a label afterwards was + not kept clear on later frames. What the labels are kept off is + part of what the plan was made for; the plan is made again once, + and not again while the figure stays as it is.""" + anim = _spin8() + fig = anim.figure + ax = _labeled_axes(fig)[0] + renderer = _show(anim, 3) + label = _labels(ax)[0] + box = label.get_bbox_patch().get_window_extent(renderer) + first = label_tracks(ax) + note = fig.text(0.5 * (box.x0 + box.x1) / fig.bbox.width, + 0.5 * (box.y0 + box.y1) / fig.bbox.height, + 'A NOTE ADDED LATER', ha='center', va='center') + renderer = _show(anim, 3) + second = label_tracks(ax) + assert second is not first + for frame in range(anim.n_frames): + renderer = _show(anim, frame) + there = note.get_window_extent(renderer) + assert not any( + one.get_bbox_patch().get_window_extent(renderer).overlaps(there) + for one in _labels(ax)), frame + assert label_tracks(ax) is second # (planned once) + _turns, _step = _wobbles(anim) + assert _turns == 0 + + +@pytest.mark.parametrize('change', ['fontsize', 'text', 'long text']) +def test_a_label_made_larger_is_planned_for(change): + """`set_fontsize` or `set_text` on a label after the plan was made + left the old offsets in place, so the larger labels lay on each + other. The size of every label is part of what the plan was made + for. (Eight names of 24 characters, each a quarter of the canvas + wide, are planned with no overlap under matplotlib 3.10; under + 3.11's wider text one glide passes over a resting label on one + frame of 60, the bound here.)""" + anim = _spin8() + ax = _labeled_axes(anim.figure)[0] + _show(anim, 2) + first = label_tracks(ax) + for label in _labels(ax): + if change == 'fontsize': + label.set_fontsize(15) + elif change == 'text': + label.set_text(label.get_text() + ' (b)') + else: + label.set_text(label.get_text() + ', a longer name') + _show(anim, 3) + second = label_tracks(ax) + assert second is not first + pairs = _pairs_per_frame(anim) + if change == 'long text': + assert pairs.max() <= 1 and (pairs > 0).sum() <= 1 + else: + assert pairs.max() == 0 + assert label_tracks(ax) is second + assert _census(anim)['off_canvas'] == 0 + + +def test_a_figure_that_changes_every_frame_is_not_planned_every_frame(): + """A caller who rewrites a figure text on every frame (a counter) + changes what the labels are kept off on every frame; the plan is + made again for the first two changes in a row and then waits until + the figure stops changing, when it is made once more.""" + anim = _spin8() + fig = anim.figure + ax = _labeled_axes(fig)[0] + counter = fig.text(0.02, 0.02, 'frame 0', ha='left', va='bottom') + plans = {id(label_tracks(ax))} + kept = [label_tracks(ax)] + for frame in range(20): + counter.set_text('frame ' + '9' * (frame + 1)) + anim.draw_frame(frame) + kept.append(label_tracks(ax)) + plans.add(id(kept[-1])) + assert len(plans) <= 3 + for frame in range(20, 24): # (the text now stays) + anim.draw_frame(frame) + kept.append(label_tracks(ax)) + final = kept[-1] + assert len({id(tracks) for tracks in kept}) <= 4 + anim.draw_frame(24) + assert label_tracks(ax) is final + renderer = _show(anim, 30) + there = counter.get_window_extent(renderer) + assert not any( + one.get_bbox_patch().get_window_extent(renderer).overlaps(there) + for one in _labels(ax)) + + +def _nan_cloud(): + data = CLOUD[:12].copy() + data[3] = np.nan + return data + + +EDGE_INPUTS = { + 'no labels': lambda: _quiet( + CLOUD[:12], 'o', animate='spin', duration=1, frame_rate=10), + 'one label': lambda: _quiet( + CLOUD[:12], 'o', labels=['only'] + [None] * 11, animate='spin', + duration=1, frame_rate=10), + 'labels with None entries': lambda: _quiet( + CLOUD[:12], 'o', + labels=[name if k % 2 else None + for k, name in enumerate(NAMES[:12])], + animate='spin', duration=1, frame_rate=10), + 'one frame': lambda: _quiet( + CLOUD[:12], 'o', labels=NAMES[:12], animate='spin', duration=0.1, + frame_rate=10), + 'two frames': lambda: _quiet( + CLOUD[:12], 'o', labels=NAMES[:12], animate='spin', duration=0.2, + frame_rate=10), + 'NaN point, spin': lambda: _quiet( + _nan_cloud(), 'o', labels=NAMES[:12], animate='spin', duration=1, + frame_rate=10), + 'NaN point, window': lambda: _quiet( + _nan_cloud(), 'o', labels=NAMES[:12], animate='window', duration=1, + frame_rate=10), + 'panels with unequal label counts': lambda: _quiet( + [CLOUD[:12], CLOUD[:5], CLOUD[:1], CLOUD[:9]], 'o', panels=(2, 2), + labels=[NAMES[:12], NAMES[:5], None, NAMES[:9]], animate='spin', + duration=2, frame_rate=15), +} +EDGE_FRAMES = {'one frame': 1, 'two frames': 2, + 'panels with unequal label counts': 30} +EDGE_LABELS = {'no labels': [], 'one label': [1], + 'labels with None entries': [6], + 'panels with unequal label counts': [12, 5, 9]} + + +@pytest.mark.parametrize('name', list(EDGE_INPUTS)) +def test_edge_inputs_are_planned_and_drawn(name, tmp_path): + """No labels, one label, None among the labels, an animation of one + frame and of two, a NaN point with a label (hypertools fills the + point in, so its label is shown), panels with different + numbers of labels (one with none): each is planned, every frame + draws with every shown label on the canvas and off the others, and + the animation saves.""" + anim = EDGE_INPUTS[name]() + fig = anim.figure + assert anim.n_frames == EDGE_FRAMES.get(name, 10) + axes = _labeled_axes(fig) + counts = [len(_labels(ax)) for ax in axes] + assert counts == EDGE_LABELS.get(name, [12]) + for ax, count in zip(axes, counts): + tracks = label_tracks(ax) + assert tracks['offsets'].shape == (anim.n_frames, count, 2) + census = _census(anim) + assert census['off_canvas'] == 0 and census['on_static'] == 0 + # (a grid has less room, and how much depends on the width of the + # text: its bound is `test_a_grids_labels_overlap_on_few_frames`) + # (measured for this grid: at most 2 pairs on 5 frames of 30 under + # matplotlib 3.10, 3 pairs on 22 frames under 3.11's wider text) + pairs = _pairs_per_frame(anim) + assert pairs.max() <= (3 if name.startswith('panels') else 0) + anim.save(tmp_path / 'edge.gif', writer=PillowWriter(fps=10)) + assert (tmp_path / 'edge.gif').stat().st_size > 1000 + + +def test_saving_an_animation_twice_gives_the_same_frames(tmp_path): + """Two saves of one animation hold the same frames, pixel for pixel + (the labels' places belong to the animation and the frame, not to + what was drawn before).""" + anim = _spin12_dressed(duration=1, frame_rate=10) + frames = [] + for name in ('one.gif', 'two.gif'): + anim.save(tmp_path / name, writer=PillowWriter(fps=10)) + with Image.open(tmp_path / name) as saved: + assert saved.n_frames == anim.n_frames + every = [] + for index in range(saved.n_frames): + saved.seek(index) + every.append(np.asarray(saved.convert('RGB')).copy()) + frames.append(np.stack(every)) + assert np.array_equal(frames[0], frames[1]) + assert (frames[0][0] != frames[0][5]).any() diff --git a/tests/test_static_cube_untouched.py b/tests/test_static_cube_untouched.py new file mode 100644 index 00000000..c2711803 --- /dev/null +++ b/tests/test_static_cube_untouched.py @@ -0,0 +1,93 @@ +"""A static 3-D plot whose cube needs no fitting is drawn exactly as +matplotlib lays it out (1.2.1 gallery review). + +The cube fit of GH #297 (`plot._keep_cube_clear`) applied its starting +zoom, 1, to every static 3-D plot through `Axes3D.set_box_aspect`, which +rescales the aspect it is handed. An axes given its own aspect back came +out one unit in the last place away from it, and three gallery figures +(`plot_missing_data` twice, `plot_multiindex`) differed from 1.2.0 in 2 +to 7 antialiased pixels, each by one level of one channel. +""" +import matplotlib + +matplotlib.use('Agg') + +import matplotlib.pyplot as plt # noqa: E402 +import numpy as np # noqa: E402 +import pandas as pd # noqa: E402 +import pytest # noqa: E402 + +import hypertools as hyp # noqa: E402 + + +def _multiindex_frame(): + """The data of `examples/plot_multiindex.py`.""" + rng = np.random.default_rng(3) + n_time = 60 + t = np.linspace(0, 4 * np.pi, n_time) + tuples, rows = [], [] + for ci, cond in enumerate(['baseline', 'treatment']): + for si in range(4): + noise = rng.standard_normal((n_time, 3)) * 0.15 + helix = np.column_stack([np.cos(t), np.sin(t), t / 4]) + noise + helix[:, 0] += ci * 3.0 + rows.append(helix) + tuples.extend([(cond, f'subj{si}')] * n_time) + index = pd.MultiIndex.from_tuples(tuples, names=['condition', 'subject']) + return pd.DataFrame(np.vstack(rows), columns=['x', 'y', 'z'], index=index) + + +def _pixels(fig): + fig.canvas.draw() + return np.asarray(fig.canvas.buffer_rgba()).copy() + + +@pytest.fixture(autouse=True) +def _close_figures(): + yield + plt.close('all') + + +def _default_box_aspect(): + """The box aspect matplotlib gives a new 3-D axes.""" + fig = plt.figure() + aspect = np.asarray(fig.add_subplot(projection='3d').get_box_aspect()) + plt.close(fig) + return aspect + + +@pytest.mark.parametrize('kwargs', [ + {}, + {'legend': ['a', 'b']}, + {'legend': ['a', 'b'], 'title': 'A title'}, + {'legend': ['a', 'b'], 'colorbar': True}, +]) +def test_static_cube_that_fits_keeps_matplotlibs_box_aspect(kwargs): + rng = np.random.default_rng(0) + data = [rng.standard_normal((40, 3)).cumsum(axis=0) for _ in range(2)] + fig = hyp.plot(data, show=False, **kwargs) + aspect = np.asarray(fig.axes[0].get_box_aspect()) + # exact: one unit in the last place is the whole defect + assert aspect.tolist() == _default_box_aspect().tolist() + + +def test_static_cube_that_fits_is_drawn_as_matplotlib_lays_it_out(): + """The pixels of `examples/plot_multiindex.py`'s figure are those of + the same figure with matplotlib's own default box aspect.""" + fig = hyp.plot(_multiindex_frame(), legend=True, show=False) + drawn = _pixels(fig) + fig.axes[0].set_box_aspect(None) + reference = _pixels(fig) + differing = int((drawn != reference).any(axis=-1).sum()) + assert differing == 0, f'{differing} pixels differ' + + +def test_cube_under_a_corner_legend_is_still_zoomed_out(): + """The fit still acts where it is needed: a legend in a corner of the + axes has the cube drawn smaller.""" + rng = np.random.default_rng(0) + data = [rng.standard_normal((40, 3)).cumsum(axis=0) for _ in range(10)] + fig = hyp.plot(data, legend=[f'dataset {i}' for i in range(10)], + legend_kwargs={'loc': 'upper left'}, show=False) + aspect = np.asarray(fig.axes[0].get_box_aspect()) + assert (aspect < _default_box_aspect() * 0.999).all() diff --git a/tests/test_stream_labels_1_2_1.py b/tests/test_stream_labels_1_2_1.py new file mode 100644 index 00000000..b9176654 --- /dev/null +++ b/tests/test_stream_labels_1_2_1.py @@ -0,0 +1,821 @@ +"""`labels=` on streaming plots (1.2.1, owner decision 2026-11-23). + +A stream's labels are placed causally, once per emitted frame, by the +placement rule of every other hypertools label. Everything here runs a +real generator through `hyp.plot`, saves real frames, and reads the +labels back from the figure as each frame left it: the generator that +feeds the stream looks at the figure before it yields its next sample +(with ``stream_chunk=1`` that is the state of the frame just saved). + +Nothing is compared against an absolute font metric: boxes are the ones +matplotlib drew, and bounds are stated in the library's own units. +""" +import gc +import warnings + +import matplotlib +import matplotlib.figure +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import pytest +from mpl_toolkits.mplot3d import proj3d +from PIL import Image + +import hypertools as hyp +from hypertools.plot import matplotlib_backend as mb + +matplotlib.use('Agg') + +IGNORED = 'no streaming implementation' + + +@pytest.fixture(autouse=True) +def _close_figures(): + plt.close('all') + yield + plt.close('all') + + +# --------------------------------------------------------------- helpers + +def _points(n, d, seed=0, centers=3, spread=0.06): + """`n` samples of `d` features inside the unit box: the first eight + span it (so the display box fitted on them holds every later + sample), the others arrive near one of a few centers, next to each + other.""" + rng = np.random.default_rng(seed) + head = rng.uniform(-1.0, 1.0, size=(8, d)) + head[0], head[1] = -1.0, 1.0 + mids = rng.uniform(-0.45, 0.45, size=(centers, d)) + rest = (mids[rng.integers(0, centers, size=max(n - 8, 0))] + + rng.normal(0.0, spread, size=(max(n - 8, 0), d))) + return np.vstack([head, rest])[:n] + + +def _stream_labels(ax): + return [text for text in ax.texts if getattr(text, '_hyp_stream', False)] + + +def _shown_points(ax): + """Where the streamed line's vertices are, in the axes' 2-D data + coordinates (projected with the camera for a 3-D axes).""" + line = ax.lines[0] + if hasattr(ax, 'get_proj'): + x, y, z = (np.asarray(v, dtype=float) for v in line.get_data_3d()) + x2, y2, _ = proj3d.proj_transform(x, y, z, ax.get_proj()) + return np.column_stack([x2, y2]) + return np.column_stack([np.asarray(v, dtype=float) + for v in line.get_data()]) + + +def _snapshot(ax, consumed): + """What the frame just drawn shows: per label (by sample index) its + text, its anchor, its offset and the box matplotlib drew.""" + fig = ax.get_figure() + points = _shown_points(ax) + labels = {} + for label in _stream_labels(ax): + labels[label._hyp_global_idx] = { + 'text': label.get_text(), + 'xy': np.array(label.xy, dtype=float), + 'offset': np.array(label.xyann, dtype=float), + 'box': np.array(label.get_bbox_patch().get_window_extent() + .extents, dtype=float), + } + title = ax.title.get_window_extent().extents \ + if ax.title.get_text() else None + return {'consumed': consumed, 'first': consumed - len(points), + 'points': points, 'labels': labels, 'title': title, + 'canvas': (fig.bbox.width, fig.bbox.height)} + + +def _live_figures(): + gc.collect() + # `type()`, not `isinstance()`: the scan meets every tracked object, + # weak proxies of collected objects among them, and `isinstance` + # asks a proxy for its referent's class, which raises ReferenceError + # once the referent is gone. + return [thing for thing in gc.get_objects() + if issubclass(type(thing), matplotlib.figure.Figure)] + + +def _recorded(samples, frames, start, ax=None, poke=None): + """Yield `samples`; before each one from `start` on, record the + figure as the last frame left it. `poke(k, ax)` may change the + figure (turn the camera, draw it again) after the record is taken.""" + known = {id(figure) for figure in _live_figures()} if ax is None else () + axes = ax + for k, row in enumerate(samples): + if k >= start: + if axes is None: + # the figure `hyp.plot` made for this stream (it is not + # one of pyplot's while the stream runs) + (figure,) = [figure for figure in _live_figures() + if id(figure) not in known and figure.axes + and figure.axes[0].lines] + axes = figure.axes[0] + frames.append(_snapshot(axes, k)) + if poke is not None: + poke(k, axes) + yield row + + +def _run(samples, tmp_path, name='s.gif', ax=None, poke=None, init=8, + **kwargs): + frames = [] + kwargs.setdefault('frame_rate', 30) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + fig = hyp.plot(_recorded(samples, frames, init + 1, ax, poke), + kwargs.pop('fmt', 'o'), stream_init=init, + stream_chunk=kwargs.pop('stream_chunk', 1), + show=False, + save_path=str(tmp_path / name), + **({'ax': ax} if ax is not None else {}), **kwargs) + if fig.stream_info['error'] is not None: + raise fig.stream_info['error'] + return fig, frames, caught + + +def _overlap(a, b, slack=0.5): + return (min(a[2], b[2]) - max(a[0], b[0]) > slack + and min(a[3], b[3]) - max(a[1], b[1]) > slack) + + +def _pairs(frame): + boxes = [one['box'] for _i, one in sorted(frame['labels'].items())] + return sum(_overlap(boxes[i], boxes[j]) + for i in range(len(boxes)) for j in range(i)) + + +def _moves(frames): + """Per label, its nonzero offset steps from one frame to the next.""" + steps = {} + for before, after in zip(frames, frames[1:]): + for index, one in after['labels'].items(): + if index in before['labels']: + step = one['offset'] - before['labels'][index]['offset'] + if np.hypot(*step) > 1e-9: + steps.setdefault(index, []).append(step) + return steps + + +def _turn_backs(frames): + return sum(float(np.dot(a, b)) < 0.0 + for steps in _moves(frames).values() + for a, b in zip(steps, steps[1:])) + + +def _largest_jump(frames): + return max([float(np.hypot(*step)) for steps in _moves(frames).values() + for step in steps] or [0.0]) + + +def _every_fifth(index, sample): + return f'p{index}' if index % 5 == 0 else None + + +# --------------------------------------------------- the forms of labels= + +FORMS = { + 'callable': lambda names: (lambda index, sample: names[index]), + 'list': list, + 'tuple': tuple, + 'array': lambda names: np.array(names, dtype=object), + 'series': lambda names: pd.Series(names, dtype=object), + 'iterator': iter, + 'generator': lambda names: (name for name in names), +} + + +@pytest.mark.parametrize('form', sorted(FORMS)) +@pytest.mark.parametrize('ndims', [2, 3]) +def test_every_form_of_labels_draws_the_same_labels(form, ndims): + data = _points(30, ndims) + names = [f'n{i}' if i % 4 == 0 else None for i in range(30)] + fig = hyp.plot(iter(data), 'o', stream_init=10, stream_chunk=5, + ndims=ndims, labels=FORMS[form](names), show=False) + assert fig.stream_info['labels'] == names + drawn = {label._hyp_global_idx: label.get_text() + for label in _stream_labels(fig.axes[0])} + assert drawn == {i: name for i, name in enumerate(names) + if name is not None} + + +def test_a_callable_gets_the_index_and_the_sample_as_yielded(): + rows = [{'name': f'row {i}', 'a': float(i % 7), 'b': float(i % 5), + 'c': float(i % 3)} for i in range(24)] + seen = [] + + def label(index, sample): + seen.append((index, sample)) + return sample['name'] if index in (0, 11, 23) else None + + fig = hyp.plot(iter(rows), 'o', stream_init=8, stream_chunk=4, ndims=2, + labels=label, show=False) + assert [index for index, _ in seen] == list(range(24)) + assert all(sample is rows[index] for index, sample in seen) + assert sorted(label.get_text() + for label in _stream_labels(fig.axes[0])) \ + == ['row 0', 'row 11', 'row 23'] + + +def test_an_endless_label_iterator_is_consumed_in_step_with_the_samples(): + pulled = [] + + def names(): + k = 0 + while True: + pulled.append(k) + yield f'#{k}' + k += 1 + + fig = hyp.plot(iter(_points(20, 2)), 'o', stream_init=8, stream_chunk=3, + ndims=2, labels=names(), show=False) + assert pulled == list(range(20)) + assert fig.stream_info['labels'] == [f'#{k}' for k in range(20)] + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_labels_shorter_than_the_stream_label_the_first_samples(ndims): + fig = hyp.plot(iter(_points(25, ndims)), 'o', stream_init=10, + stream_chunk=5, ndims=ndims, labels=['a', None, 'c'], + show=False) + assert fig.stream_info['labels'] == ['a', None, 'c'] + [None] * 22 + assert {label._hyp_global_idx: label.get_text() + for label in _stream_labels(fig.axes[0])} == {0: 'a', 2: 'c'} + + +@pytest.mark.parametrize('labels', [ + [None] * 25, lambda index, sample: None, [], ['', ' ', float('nan')], +], ids=['all None', 'callable returning None', 'empty list', + 'blank and NaN']) +def test_no_label_is_drawn_for_none(labels): + fig = hyp.plot(iter(_points(25, 3)), 'o', stream_init=10, + stream_chunk=5, labels=labels, show=False) + assert fig.stream_info['labels'] == [None] * 25 + assert not fig.axes[0].texts + assert fig.stream_info['n_samples'] == 25 + + +def test_without_labels_nothing_is_recorded_or_drawn(): + fig = hyp.plot(iter(_points(25, 3)), 'o', stream_init=10, + stream_chunk=5, show=False) + assert fig.stream_info['labels'] is None + assert not fig.axes[0].texts + + +@pytest.mark.parametrize('labels', ['name', 5, True], + ids=['a bare string', 'a number', 'True']) +def test_an_unusable_labels_raises_before_a_sample_is_consumed(labels): + consumed = [] + + def source(): + for row in _points(20, 3): + consumed.append(1) + yield row + + with pytest.raises(TypeError, match='labels='): + hyp.plot(source(), 'o', stream_init=10, labels=labels, show=False) + assert not consumed + + +# ------------------------------------------------ the labels on the frames + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_twelve_labels_follow_their_points_and_stay_clear(ndims, tmp_path): + """Samples arrive next to each other (three small clusters), every + fifth one labeled: 12 labels by the end. + + Every frame: each label is anchored at its own sample's drawn + position; no label lies on the title or off the canvas. Over the + stream: no label turns back, and no two labels overlap on any frame + (measured: 0 pairs on every frame, 2-D and 3-D, matplotlib 3.10 and + 3.11; a new label takes a free place and the others stay).""" + data = _points(60, ndims, seed=1) + fig, frames, caught = _run(data, tmp_path, ndims=ndims, + labels=_every_fifth, + title='Twelve labels on a stream') + assert not [w for w in caught if IGNORED in str(w.message)] + assert len(frames) == 60 - 9 + assert len(frames[-1]['labels']) == 12 + width, height = frames[0]['canvas'] + for frame in frames: + assert frame['first'] == 0 + for index, one in frame['labels'].items(): + assert one['text'] == f'p{index}' + np.testing.assert_allclose( + one['xy'], frame['points'][index - frame['first']], + atol=1e-9) + box = one['box'] + assert box[0] >= -0.5 and box[1] >= -0.5 + assert box[2] <= width + 0.5 and box[3] <= height + 0.5 + assert not _overlap(box, frame['title']) + assert sorted(frame['labels']) == [ + i for i in range(frame['consumed']) if i % 5 == 0] + assert _turn_backs(frames) == 0 + assert max(_pairs(frame) for frame in frames) == 0 + # ... nor do two boxes touch: a new label is given clear space round + # it (`_LABEL_CLEARANCE_PT`, less the half point a box is rounded by) + clear = (mb._LABEL_CLEARANCE_PT - 0.5) * fig.dpi / 72.0 + boxes = [one['box'] for _i, one in sorted(frames[-1]['labels'].items())] + for i, a in enumerate(boxes): + for b in boxes[:i]: + apart = max(a[0] - b[2], b[0] - a[2], a[1] - b[3], b[1] - a[3]) + assert apart >= clear + # a label that is there stays where it is while new ones arrive + assert _largest_jump(frames) == 0.0 + + +def test_labels_follow_their_points_when_the_view_turns(tmp_path): + """The camera is turned twice while the stream runs (as a reader + turning the plot would). On every frame after it each label is + still anchored at its point's projection for the camera of that + frame; the labels that have to change place glide (no jump larger + than a glide's largest step) and none turns back.""" + data = _points(70, 3, seed=2) + + def turn(k, ax): + if k in (30, 50): + ax.view_init(elev=ax.elev + 12, azim=ax.azim + 55) + + fig, frames, _ = _run(data, tmp_path, ndims=3, labels=_every_fifth, + title='Turned while streaming', poke=turn) + width, height = frames[0]['canvas'] + for frame in frames: + for index, one in frame['labels'].items(): + np.testing.assert_allclose( + one['xy'], frame['points'][index], atol=1e-9) + box = one['box'] + assert box[0] >= -0.5 and box[1] >= -0.5 + assert box[2] <= width + 0.5 and box[3] <= height + 0.5 + assert not _overlap(box, frame['title']) + moves = _moves(frames) + assert moves, 'the turn was meant to make some label change place' + assert _turn_backs(frames) == 0 + # a glide takes `ease` updates (smoothstep: its largest step is 1.5 + # times the mean one), over at most the way from one side of the + # point to the other at the furthest reach + ease = max(mb._STREAM_LABEL_EASE_MIN, + round(mb._STREAM_LABEL_EASE_SECONDS * 30)) + sizes = np.array([mb._label_size_pt(label) + for label in _stream_labels(fig.axes[0])]) + furthest = 2 * (max(mb._LABEL_REACHES_PT) + + 0.5 * float(np.hypot(*sizes.max(axis=0)))) + assert _largest_jump(frames) <= 1.5 * furthest / ease + # every change of place is spread over a glide's worth of frames + assert min(len(steps) for steps in moves.values()) >= ease - 2 + # A turn throws the points onto each other at once, and the future + # was not known: on the frame of the turn labels overlap (measured: + # 4 pairs after the second turn, 0 after the first), and they are + # clear again within one glide. No pair on any other frame, and + # never more pairs than the turn itself made. + pairs = {frame['consumed']: _pairs(frame) for frame in frames} + for turned in (31, 51): + after = [pairs[k] for k in range(turned, turned + ease + 1)] + assert max(after) == after[0] <= 6 + assert after[-1] == 0 + assert not [k for k, count in pairs.items() if count + and not (31 <= k <= 31 + ease or 51 <= k <= 51 + ease)] + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_a_label_leaves_with_its_point_under_stream_window(ndims, tmp_path): + data = _points(60, ndims, seed=3) + fig, frames, _ = _run(data, tmp_path, ndims=ndims, stream_window=15, + labels=lambda index, sample: ( + f'p{index}' if index % 3 == 0 else None), + fmt='-') + ax = fig.axes[0] + for frame in frames: + shown = [i for i in range(frame['first'], frame['consumed']) + if i % 3 == 0] + assert len(frame['points']) == min(15, frame['consumed']) + assert sorted(frame['labels']) == shown + for index, one in frame['labels'].items(): + np.testing.assert_allclose( + one['xy'], frame['points'][index - frame['first']], + atol=1e-9) + # the returned figure holds the last window's labels and no others + assert sorted(label._hyp_global_idx for label in _stream_labels(ax)) \ + == [i for i in range(45, 60) if i % 3 == 0] + assert len(ax.texts) == 5 + assert len(ax._hyp_labels_and_points) == 5 + # ... while every consumed sample's label is kept in stream_info + assert fig.stream_info['labels'] == [ + f'p{i}' if i % 3 == 0 else None for i in range(60)] + assert _turn_backs(frames) == 0 + assert max(_pairs(frame) for frame in frames) == 0 + + +@pytest.mark.parametrize('ndims,window', [(2, None), (3, None), (3, 20)]) +def test_the_saved_frames_are_the_same_run_to_run(ndims, window, tmp_path): + saved = [] + for run in ('a', 'b'): + plt.close('all') + path = tmp_path / f'{run}.gif' + hyp.plot(iter(_points(50, ndims, seed=4)), '-o', stream_init=10, + stream_chunk=2, ndims=ndims, stream_window=window, + labels=lambda index, sample: ( + f'p{index}' if index % 4 == 0 else None), + title='Twice the same', save_path=str(path), show=False) + with Image.open(path) as gif: + frames = [] + for k in range(gif.n_frames): + gif.seek(k) + frames.append((np.array(gif.convert('RGB')), + gif.info.get('duration'))) + saved.append((path.read_bytes(), frames)) + (bytes_a, frames_a), (bytes_b, frames_b) = saved + assert len(frames_a) == len(frames_b) > 10 + for (image_a, time_a), (image_b, time_b) in zip(frames_a, frames_b): + assert time_a == time_b + assert np.array_equal(image_a, image_b) + assert bytes_a == bytes_b + + +def test_the_labels_are_stepped_per_frame_and_not_per_draw(tmp_path): + """Drawing the figure more often (a GUI repaints whenever it likes) + changes nothing: the labels of every frame are where they are + without the extra draws.""" + data = _points(60, 3, seed=5) + + def turn(k, ax): + if k == 25: + ax.view_init(elev=ax.elev + 10, azim=ax.azim + 60) + + def turn_and_draw(k, ax): + turn(k, ax) + for _ in range(k % 3): + ax.get_figure().canvas.draw() + + _, plain, _ = _run(data, tmp_path, 'plain.gif', ndims=3, + labels=_every_fifth, poke=turn) + plt.close('all') + _, drawn, _ = _run(data, tmp_path, 'drawn.gif', ndims=3, + labels=_every_fifth, poke=turn_and_draw) + assert len(plain) == len(drawn) + assert _moves(plain), 'the turn was meant to make some label move' + for one, other in zip(plain, drawn): + assert sorted(one['labels']) == sorted(other['labels']) + for index in one['labels']: + np.testing.assert_array_equal(one['labels'][index]['offset'], + other['labels'][index]['offset']) + assert (tmp_path / 'plain.gif').read_bytes() \ + == (tmp_path / 'drawn.gif').read_bytes() + + +# ------------------------------------------------------------ edge inputs + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_a_stream_that_ends_during_stream_init_is_labeled(ndims, tmp_path): + path = tmp_path / 'short.gif' + fig = hyp.plot(iter(_points(12, ndims)), 'o', stream_init=100, + ndims=ndims, labels=lambda i, s: f'p{i}' if i % 4 == 0 + else None, save_path=str(path), show=False) + assert fig.stream_info['n_samples'] == 12 + assert sorted(label.get_text() + for label in _stream_labels(fig.axes[0])) \ + == ['p0', 'p4', 'p8'] + assert path.stat().st_size > 0 + + +def test_stream_max_smaller_than_stream_init_labels_only_those_samples(): + asked = [] + + def label(index, sample): + asked.append(index) + return f'p{index}' + + fig = hyp.plot(iter(_points(40, 3)), 'o', stream_init=30, stream_max=6, + labels=label, show=False) + assert asked == list(range(6)) + assert fig.stream_info['n_samples'] == 6 + assert fig.stream_info['labels'] == [f'p{i}' for i in range(6)] + assert len(_stream_labels(fig.axes[0])) == 6 + + +@pytest.mark.parametrize('projection', [None, '3d']) +def test_labels_go_into_the_axes_the_caller_supplied(projection, tmp_path): + ndims = 3 if projection else 2 + canvas = plt.figure(figsize=(10, 5)) + other = canvas.add_subplot(1, 2, 1) + other.plot([0, 1], [0, 1]) + ax = canvas.add_subplot(1, 2, 2, projection=projection) + fig, frames, _ = _run(_points(40, ndims, seed=6), tmp_path, ax=ax, + ndims=ndims, labels=_every_fifth) + assert fig is canvas + assert not other.texts + assert len(_stream_labels(ax)) == 8 + width, height = frames[0]['canvas'] + left_panel = other.get_window_extent().extents + for frame in frames: + for index, one in frame['labels'].items(): + np.testing.assert_allclose(one['xy'], frame['points'][index], + atol=1e-9) + box = one['box'] + assert box[0] >= -0.5 and box[1] >= -0.5 + assert box[2] <= width + 0.5 and box[3] <= height + 0.5 + # the next panel is an obstacle, as in a static figure + assert not _overlap(box, left_panel) + assert max(_pairs(frame) for frame in frames) == 0 + assert _turn_backs(frames) == 0 + + +def test_stream_labels_keep_off_a_static_plot_s_labels_in_the_same_axes( + tmp_path): + canvas, ax = plt.subplots(figsize=(7, 6)) + still = _points(40, 2, seed=7)[8:12] + hyp.plot(still, 'o', ax=ax, labels=['still a', 'still b', 'still c', + 'still d'], show=False) + canvas.canvas.draw() + static = [text for text in ax.texts] + assert len(static) == 4 + fig, frames, _ = _run(_points(40, 2, seed=7), tmp_path, ax=ax, ndims=2, + labels=_every_fifth) + assert len(_stream_labels(ax)) == 8 + assert all(text.axes is ax for text in static) + canvas.canvas.draw() + theirs = [text.get_bbox_patch().get_window_extent().extents + for text in static] + ours = [text.get_bbox_patch().get_window_extent().extents + for text in _stream_labels(ax)] + assert not any(_overlap(a, b) for a in ours for b in theirs) + + +def test_label_alpha_is_honored_on_a_stream(): + fig = hyp.plot(iter(_points(20, 3)), 'o', stream_init=10, + labels=['a', 'b'], label_alpha=0.9, show=False) + assert [label.get_bbox_patch().get_alpha() + for label in _stream_labels(fig.axes[0])] == [0.9, 0.9] + with pytest.raises(ValueError, match='label_alpha'): + hyp.plot(iter(_points(20, 3)), 'o', stream_init=10, labels=['a'], + label_alpha=3, show=False) + + +def test_a_labels_callable_that_raises(): + def early(index, sample): + raise KeyError('no such field') + + with pytest.raises(KeyError): + hyp.plot(iter(_points(30, 3)), 'o', stream_init=10, labels=early, + show=False) + + def late(index, sample): + if index >= 22: + raise KeyError('no such field') + return f'p{index}' if index % 5 == 0 else None + + with pytest.warns(RuntimeWarning, match='streaming stopped early'): + fig = hyp.plot(iter(_points(40, 3)), 'o', stream_init=10, + stream_chunk=5, labels=late, show=False) + info = fig.stream_info + assert isinstance(info['error'], KeyError) + # the samples of the chunk BEFORE the one that failed are kept + assert info['n_samples'] == 22 == len(info['labels']) + assert len(info['data'][0]) == len(info['xform_data'][0]) == 22 + assert sorted(label.get_text() + for label in _stream_labels(fig.axes[0])) \ + == ['p0', 'p10', 'p15', 'p20', 'p5'] + + +def _in_step(fig, count): + """`count` samples are kept, and label k is on sample k.""" + info = fig.stream_info + assert info['n_samples'] == count + assert info['labels'] == [f'p{k}' for k in range(count)] + assert len(info['data'][0]) == len(info['xform_data'][0]) == count + np.testing.assert_array_equal(info['data'][0][:, 0], np.arange(count)) + ax = fig.axes[0] + points = _shown_points(ax) + assert len(points) == count + labels = _stream_labels(ax) + assert [label._hyp_global_idx for label in labels] == list(range(count)) + for label in labels: + assert label.get_text() == f'p{label._hyp_global_idx}' + np.testing.assert_allclose(label.xy, points[label._hyp_global_idx], + atol=1e-9) + + +def _row(k, d=2): + return [float(k), float(k % 2), float(k % 3)][:d] + + +def _counted(count=12, d=2): + return iter([_row(k, d) for k in range(count)]) + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_a_label_error_in_the_middle_of_a_chunk_keeps_the_samples_before_it( + ndims): + """Review of 237e9111: the labels of a chunk were built in one go + before anything was kept, so a callable that raised for sample 4 + (chunk 3..5) lost sample 3 and its label too.""" + def label(index, sample): + if index == 4: + raise ValueError('no label for sample 4') + return f'p{index}' + + with pytest.warns(RuntimeWarning, match='streaming stopped early'): + fig = hyp.plot(_counted(d=ndims), 'o', reduce=None, ndims=ndims, + stream_init=3, stream_chunk=3, labels=label, + show=False) + assert isinstance(fig.stream_info['error'], ValueError) + assert fig.stream_info['truncated'] is True + _in_step(fig, 4) + + +def test_a_label_iterator_that_raises_keeps_the_samples_before_it(): + def names(): + for k in range(7): + yield f'p{k}' + raise LookupError('the names ran dry') + + with pytest.warns(RuntimeWarning, match='streaming stopped early'): + fig = hyp.plot(_counted(), 'o', reduce=None, ndims=2, stream_init=3, + stream_chunk=3, labels=names(), show=False) + assert isinstance(fig.stream_info['error'], LookupError) + _in_step(fig, 7) + + +def test_a_label_error_inside_stream_init_keeps_the_samples_before_it(): + """Like a bad sample inside the head: the models are fitted on the + samples before it and the figure is returned with them.""" + def label(index, sample): + if index == 5: + raise ValueError('no label for sample 5') + return f'p{index}' + + with pytest.warns(RuntimeWarning, + match='while consuming the first stream_init'): + fig = hyp.plot(_counted(), 'o', reduce=None, ndims=2, stream_init=8, + stream_chunk=3, labels=label, show=False) + assert isinstance(fig.stream_info['error'], ValueError) + _in_step(fig, 5) + + +def test_a_source_that_dies_mid_chunk_leaves_the_labels_in_step(): + asked = [] + + def source(): + for k in range(8): + yield _row(k) + raise ConnectionError('the source went away') + + def label(index, sample): + asked.append((index, sample[0])) + return f'p{index}' + + with pytest.warns(RuntimeWarning, match='streaming stopped early'): + fig = hyp.plot(source(), 'o', reduce=None, ndims=2, stream_init=3, + stream_chunk=3, labels=label, show=False) + assert isinstance(fig.stream_info['error'], ConnectionError) + # samples 6 and 7 came before the source died, in an unfinished chunk + _in_step(fig, 8) + assert asked == [(k, float(k)) for k in range(8)] + + +def test_a_bad_sample_mid_chunk_keeps_the_samples_and_labels_before_it(): + rows = [_row(k) for k in range(12)] + rows[7] = ['not', 'a number'] + pulled = [] + + def names(): + k = 0 + while True: + pulled.append(k) + yield f'p{k}' + k += 1 + + with pytest.warns(RuntimeWarning, match='streaming stopped early'): + fig = hyp.plot(iter(rows), 'o', reduce=None, ndims=2, stream_init=3, + stream_chunk=3, labels=names(), show=False) + assert isinstance(fig.stream_info['error'], ValueError) + _in_step(fig, 7) + # no label was pulled for the sample that could not be read + assert pulled == list(range(7)) + + +def test_a_one_feature_stream_that_ends_in_the_head_says_labels_are_not_drawn(): + with pytest.warns(UserWarning, match='labels= is not drawn'): + fig = hyp.plot(iter([[float(v)] for v in range(6)]), stream_init=10, + labels=['a', 'b'], show=False) + assert fig.stream_info['n_samples'] == 6 + + +def test_more_labels_than_are_arranged_warns_once(): + count = mb._STREAM_LABEL_MAX + 12 + data = np.vstack([_points(8, 2), np.random.default_rng(8).uniform( + -1, 1, size=(count + 8, 2))]) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + fig = hyp.plot(iter(data), '.', stream_init=count, stream_chunk=8, + ndims=2, labels=lambda i, s: str(i), show=False) + said = [w for w in caught if 'kept off each other' in str(w.message)] + assert len(said) == 1 + assert str(mb._STREAM_LABEL_MAX) in str(said[0].message) + labels = _stream_labels(fig.axes[0]) + assert len(labels) == len(data) + # the labels beyond the arranged ones hang at the usual place + home = [mb._place_center_offset(mb._LABEL_HOME, mb._label_size_pt(label)) + for label in labels[mb._STREAM_LABEL_MAX:]] + assert [tuple(label.xyann) for label in labels[mb._STREAM_LABEL_MAX:]] \ + == home + + +def test_a_line_and_marker_stream_keeps_no_stale_head_markers(): + """Found while adding stream labels: '-o' drew the head twice, as a + line with its markers off and a markers-only copy that was never + updated. The streamed samples had no marker, and the head's markers + stayed on screen after `stream_window` had scrolled them away.""" + for ndims in (2, 3): + fig = hyp.plot(iter(_points(40, ndims)), '-o', stream_init=10, + stream_chunk=5, stream_window=12, ndims=ndims, + markersize=5, show=False) + ax = fig.axes[0] + assert len(ax.lines) == 1 + assert len(_shown_points(ax)) == 12 + line = ax.lines[0] + assert line.get_marker() == 'o' and line.get_linestyle() == '-' + assert line.get_markevery() is None # a marker on every vertex + assert line.get_markersize() == 5 + # a marker-only and a line-only format are drawn as before + for fmt, marker, style in (('o', 'o', 'None'), ('-', 'None', '-')): + fig = hyp.plot(iter(_points(40, 3)), fmt, stream_init=10, + stream_chunk=5, show=False) + (line,) = fig.axes[0].lines + assert (line.get_marker(), line.get_linestyle()) == (marker, style) + assert line.get_markevery() is None + + +def test_a_stream_into_a_callers_axes_updates_its_own_line(): + """The streamed line was looked up as the first line of the figure's + first axes: with a line already there (in another panel, or in the + same axes) the stream updated that one.""" + canvas = plt.figure(figsize=(10, 5)) + other = canvas.add_subplot(1, 2, 1) + (theirs,) = other.plot([0.0, 1.0], [0.0, 1.0]) + ax = canvas.add_subplot(1, 2, 2) + (mine,) = ax.plot([-1.0, 1.0], [0.5, 0.5]) + fig = hyp.plot(iter(_points(30, 2)), '-', stream_init=10, + stream_chunk=5, ndims=2, ax=ax, show=False) + assert fig is canvas + assert [list(v) for v in theirs.get_data()] == [[0.0, 1.0], [0.0, 1.0]] + assert [list(v) for v in mine.get_data()] == [[-1.0, 1.0], [0.5, 0.5]] + streamed = [line for line in ax.lines if line is not mine] + assert len(streamed) == 1 + assert len(streamed[0].get_xdata()) == 30 + + +# ------------------------------------------------------------ the warnings + +def test_labels_is_no_longer_named_as_ignored(): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + hyp.plot(iter(_points(20, 3)), 'o', stream_init=10, + labels=['a', 'b'], label_alpha=0.7, show=False) + assert not [w for w in caught if IGNORED in str(w.message)] + + with pytest.warns(UserWarning, match=IGNORED) as caught: + hyp.plot(iter(_points(20, 3)), 'o', stream_init=10, + labels=['a', 'b'], head_marker='o', show=False) + message = next(str(w.message) for w in caught + if IGNORED in str(w.message)) + ignored, honored = message.split('Parameters honored for streams:') + assert 'head_marker' in ignored and 'labels' not in ignored + assert 'labels' in honored and 'label_alpha' in honored + + +@pytest.mark.parametrize('name,value', [ + ('head_marker', 'o'), + ('tail_linewidth', 4), ('trail_alpha', 0.5), ('label_anchor', 'last'), +]) +def test_the_other_arguments_still_warn_as_ignored(name, value): + with pytest.warns(UserWarning, match=IGNORED) as caught: + fig = hyp.plot(iter(_points(20, 3)), 'o', stream_init=10, + labels=['a', 'b'], show=False, **{name: value}) + message = next(str(w.message) for w in caught + if IGNORED in str(w.message)) + assert name in message.split('Parameters honored for streams:')[0] + assert len(_stream_labels(fig.axes[0])) == 2 + + +def test_hold_on_a_stream_still_raises(): + """`hold=` is checked before a stream is recognized and asks for an + animated plot, as it did before streams had labels (not changed + here: streaming `hold=` is not built).""" + with pytest.raises(ValueError, match='hold= requires an animated plot'): + hyp.plot(iter(_points(20, 3)), 'o', stream_init=10, + labels=['a', 'b'], hold=1, show=False) + + +def test_a_plotly_request_is_ignored_and_the_labels_are_drawn(): + with pytest.warns(UserWarning, match=IGNORED) as caught: + fig = hyp.plot(iter(_points(20, 3)), 'o', stream_init=10, + labels=['a', 'b'], backend='plotly', show=False) + message = next(str(w.message) for w in caught + if IGNORED in str(w.message)) + assert 'backend' in message.split('Parameters honored')[0] + assert isinstance(fig, matplotlib.figure.Figure) + assert len(_stream_labels(fig.axes[0])) == 2 diff --git a/tests/test_stream_text_1_2_1.py b/tests/test_stream_text_1_2_1.py new file mode 100644 index 00000000..e3e5b5a1 --- /dev/null +++ b/tests/test_stream_text_1_2_1.py @@ -0,0 +1,345 @@ +"""`legend=`, `caption=` and `suptitle=` on streaming plots (1.2.1, owner +decision 2026-11-24: "Add the three now"). + +They are placed once, by the static plot of the first `stream_init` +samples, and stay for the whole stream. Everything here runs a real +generator through `hyp.plot` and reads the figure as each saved frame +left it (the generator that feeds the stream looks at the figure before +it yields its next sample). +""" +import gc +import warnings + +import matplotlib +import matplotlib.figure +import matplotlib.pyplot as plt +import numpy as np +import pytest +from mpl_toolkits.mplot3d import proj3d + +import hypertools as hyp + +IGNORED = 'no streaming implementation' +CAPTION = 'A caption placed once, under the plot, for the whole stream.' +SUPTITLE = 'Suptitle of the stream' + + +@pytest.fixture(autouse=True) +def _close_figures(): + plt.close('all') + yield + plt.close('all') + + +def _points(n, d, seed=0): + """`n` samples of `d` features in the unit box; the first eight span + it, so the display box fitted on them holds every later sample.""" + rng = np.random.default_rng(seed) + data = rng.uniform(-1.0, 1.0, size=(n, d)) + data[0], data[1] = -1.0, 1.0 + return data + + +def _live_figures(): + gc.collect() + return [thing for thing in gc.get_objects() + # `type()`, not `isinstance()`: a weak proxy of a collected + # object met in the scan raises ReferenceError when asked + # for its referent's class. + if issubclass(type(thing), matplotlib.figure.Figure)] + + +def _legend(ax): + fig = ax.get_figure() + return ax.get_legend() or (fig.legends[0] if fig.legends else None) + + +def _vertices_px(ax): + """The streamed line's vertices in display pixels.""" + line = ax.lines[0] + if hasattr(ax, 'get_proj'): + x, y, z = (np.asarray(v, dtype=float) for v in line.get_data_3d()) + x, y, _ = proj3d.proj_transform(x, y, z, ax.get_proj()) + else: + x, y = (np.asarray(v, dtype=float) for v in line.get_data()) + return ax.transData.transform(np.column_stack([x, y])) + + +def _snapshot(ax, consumed): + fig = ax.get_figure() + legend = _legend(ax) + return { + 'consumed': consumed, + 'canvas': (fig.bbox.width, fig.bbox.height), + 'vertices': _vertices_px(ax), + 'legend': None if legend is None + else np.array(legend.get_window_extent().extents), + 'title': np.array(ax.title.get_window_extent().extents) + if ax.title.get_text() else None, + 'texts': {text.get_text(): np.array( + text.get_window_extent().extents) for text in fig.texts}, + 'labels': {label.get_text(): np.array( + label.get_bbox_patch().get_window_extent().extents) + for label in ax.texts if getattr(label, '_hyp_stream', False)}, + } + + +def _recorded(samples, frames, start): + known = {id(figure) for figure in _live_figures()} + axes = None + for k, row in enumerate(samples): + if k >= start: + if axes is None: + (figure,) = [figure for figure in _live_figures() + if id(figure) not in known and figure.axes + and figure.axes[0].lines] + axes = figure.axes[0] + frames.append(_snapshot(axes, k)) + yield row + + +def _run(samples, tmp_path, name='s.gif', **kwargs): + frames = [] + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + fig = hyp.plot(_recorded(samples, frames, 9), kwargs.pop('fmt', '-o'), + stream_init=8, stream_chunk=1, show=False, + save_path=str(tmp_path / name), **kwargs) + if fig.stream_info['error'] is not None: + raise fig.stream_info['error'] + return fig, frames, caught + + +def _overlap(a, b, slack=0.5): + return (min(a[2], b[2]) - max(a[0], b[0]) > slack + and min(a[3], b[3]) - max(a[1], b[1]) > slack) + + +def _inside(box, canvas, slack=0.5): + return (box[0] >= -slack and box[1] >= -slack + and box[2] <= canvas[0] + slack and box[3] <= canvas[1] + slack) + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_legend_caption_and_suptitle_are_drawn_once_and_stay_clear( + ndims, tmp_path): + """All three with a title and labels, on every frame up to the last: + each is inside the canvas, none lies on another or on the title, no + vertex of the streamed line is under the legend, no label lies on + any of them, and none of them moves from frame to frame.""" + data = _points(60, ndims, seed=1) + fig, frames, caught = _run( + data, tmp_path, ndims=ndims, title='A stream with fixed texts', + suptitle=SUPTITLE, caption=CAPTION, legend=['the stream'], + labels=lambda i, s: f'p{i}' if i % 5 == 0 else None) + assert not [w for w in caught if IGNORED in str(w.message)] + assert len(frames) == 60 - 9 + first = frames[0] + assert set(first['texts']) == {CAPTION, SUPTITLE} + assert first['legend'] is not None + for frame in frames: + canvas = frame['canvas'] + fixed = {'legend': frame['legend'], 'title': frame['title'], + **frame['texts']} + for name, box in fixed.items(): + assert _inside(box, canvas), name + np.testing.assert_array_equal( + box, {'legend': first['legend'], 'title': first['title'], + **first['texts']}[name]) + names = sorted(fixed) + for i, a in enumerate(names): + for b in names[:i]: + assert not _overlap(fixed[a], fixed[b]), (a, b) + # the stream's content keeps off the legend, late frames included + legend = frame['legend'] + points = frame['vertices'] + assert len(points) == frame['consumed'] + under = ((points[:, 0] > legend[0]) & (points[:, 0] < legend[2]) + & (points[:, 1] > legend[1]) & (points[:, 1] < legend[3])) + assert not under.any() + # the labels keep off all of it and stay inside the canvas + for text, box in frame['labels'].items(): + assert _inside(box, canvas), text + for name, other in fixed.items(): + assert not _overlap(box, other), (text, name) + assert len(frames[-1]['labels']) == 12 + # the caption is under the plot and the suptitle above the title + assert first['texts'][CAPTION][3] < first['vertices'][:, 1].min() + assert first['texts'][SUPTITLE][1] >= first['title'][3] - 0.5 + + +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('fmt', ['-', '-o', 'o']) +def test_the_legend_key_matches_the_streamed_line(ndims, fmt): + fig = hyp.plot(iter(_points(30, ndims)), fmt, stream_init=10, + stream_chunk=5, ndims=ndims, legend=['the stream'], + markersize=5, linewidth=2, show=False) + ax = fig.axes[0] + legend = _legend(ax) + assert [text.get_text() for text in legend.get_texts()] == ['the stream'] + (key,), line = legend.legend_handles, ax.lines[0] + assert key.get_marker() == line.get_marker() + assert key.get_linestyle() == line.get_linestyle() + assert matplotlib.colors.same_color(key.get_color(), line.get_color()) + assert len(_vertices_px(ax)) == 30 + + +def test_the_styling_arguments_are_honored(): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + fig = hyp.plot(iter(_points(30, 3)), '-o', stream_init=10, + stream_chunk=5, legend=['a'], + legend_kwargs={'title': 'Key'}, legend_colors=['k'], + caption='cap', caption_kwargs={'color': 'gray'}, + suptitle='sup', suptitle_kwargs={'size': 18}, + show=False) + assert not [w for w in caught if IGNORED in str(w.message)] + legend = _legend(fig.axes[0]) + assert legend.get_title().get_text() == 'Key' + assert matplotlib.colors.same_color( + legend.legend_handles[0].get_color(), 'k') + texts = {text.get_text(): text for text in fig.texts} + assert texts['cap'].get_color() == 'gray' + assert texts['sup'].get_size() == 18 + + +@pytest.mark.parametrize('name,value', [ + ('legend', ['a stream']), ('caption', 'A caption'), + ('suptitle', 'A suptitle')]) +def test_each_is_honored_alone_and_no_longer_named_as_ignored(name, value): + for ndims in (2, 3): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + fig = hyp.plot(iter(_points(30, ndims)), '-', stream_init=10, + stream_chunk=5, ndims=ndims, show=False, + **{name: value}) + assert not [w for w in caught if IGNORED in str(w.message)] + if name == 'legend': + assert [t.get_text() for t in _legend(fig.axes[0]).get_texts()] \ + == value + else: + assert [text.get_text() for text in fig.texts] == [value] + plt.close('all') + with pytest.warns(UserWarning, match=IGNORED) as caught: + hyp.plot(iter(_points(30, 3)), '-', stream_init=10, show=False, + head_marker='o', **{name: value}) + message = next(str(w.message) for w in caught + if IGNORED in str(w.message)) + ignored, honored = message.split('Parameters honored for streams:') + assert 'head_marker' in ignored and name not in ignored + assert name in honored + + +@pytest.mark.parametrize('name,value', [ + ('head_marker', 'o'), ('tail_linewidth', 4), ('trail_alpha', 0.5)]) +def test_the_animation_only_arguments_still_warn(name, value): + with pytest.warns(UserWarning, match=IGNORED) as caught: + hyp.plot(iter(_points(30, 3)), '-', stream_init=10, show=False, + legend=['a'], **{name: value}) + message = next(str(w.message) for w in caught + if IGNORED in str(w.message)) + assert name in message.split('Parameters honored for streams:')[0] + + +def test_a_per_frame_caption_raises_before_a_sample_is_consumed(): + """(A '{index}' pattern is refused earlier, as on any data without + a row index: a stream has none.)""" + def caption(ctx): + return 'frame' + + consumed = [] + + def source(): + for row in _points(30, 3): + consumed.append(1) + yield row + + with pytest.raises(TypeError, match='caption= on a streaming plot'): + hyp.plot(source(), '-', stream_init=10, caption=caption, show=False) + assert not consumed + + +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('kwargs,message', [ + ({'legend': ['a', 'b']}, 'legend= was given as a list of length 2'), + ({'legend': ['a'], 'legend_colors': ['r', 'b']}, + 'legend_colors has 2 entries but the legend has 1'), + ({'legend': True, 'legend_colors': ['r', 'b']}, + 'legend_colors has 2 entries but the legend has 1'), +]) +def test_a_wrong_entry_count_raises_before_a_sample_is_consumed( + ndims, kwargs, message): + """A stream is one dataset, so a legend or a color list of another + length is refused with the message of the non-stream path, and the + stream is left whole for the corrected call.""" + consumed = [] + + def source(): + for row in _points(30, ndims): + consumed.append(1) + yield row + + stream = source() + with pytest.raises(ValueError, match=message): + hyp.plot(stream, '-', stream_init=10, ndims=ndims, show=False, + **kwargs) + assert not consumed + fig = hyp.plot(stream, '-', stream_init=10, stream_chunk=5, ndims=ndims, + legend=['a'], legend_colors=['r'], show=False) + assert len(consumed) == 30 + assert len(_vertices_px(fig.axes[0])) == 30 + + +def test_label_color_pairs_define_the_stream_legend_outright(): + fig = hyp.plot(iter(_points(30, 3)), '-', stream_init=10, stream_chunk=5, + legend=['a'], legend_colors=[('x', 'r'), ('y', 'b')], + show=False) + assert [t.get_text() for t in _legend(fig.axes[0]).get_texts()] \ + == ['x', 'y'] + + +@pytest.mark.parametrize('name', ['caption', 'suptitle']) +def test_caption_and_suptitle_refuse_a_callers_axes_as_on_any_plot(name): + """They resize the figure to make their room, so the non-stream path + refuses them with `ax=`; a stream does the same, with the same + message, before a sample is consumed.""" + consumed = [] + + def source(): + for row in _points(30, 2): + consumed.append(1) + yield row + + _, ax = plt.subplots() + with pytest.raises(ValueError, match=f'{name}= is drawn') as stream: + hyp.plot(source(), '-', stream_init=10, ndims=2, ax=ax, show=False, + **{name: 'text'}) + assert not consumed + _, ax = plt.subplots() + with pytest.raises(ValueError, match=f'{name}= is drawn') as static: + hyp.plot(_points(30, 2), '-', ax=ax, show=False, **{name: 'text'}) + assert str(stream.value) == str(static.value) + + +def test_a_legend_goes_into_the_axes_the_caller_supplied(): + canvas, ax = plt.subplots() + fig = hyp.plot(iter(_points(30, 2)), '-o', stream_init=10, + stream_chunk=5, ndims=2, ax=ax, legend=['the stream'], + show=False) + assert fig is canvas + assert [t.get_text() for t in _legend(ax).get_texts()] == ['the stream'] + + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_the_saved_frames_are_the_same_run_to_run(ndims, tmp_path): + saved = [] + for run in ('a', 'b'): + plt.close('all') + path = tmp_path / f'{run}.gif' + hyp.plot(iter(_points(40, ndims, seed=4)), '-o', stream_init=10, + stream_chunk=2, ndims=ndims, legend=['the stream'], + caption=CAPTION, suptitle=SUPTITLE, title='Twice the same', + labels=lambda i, s: f'p{i}' if i % 4 == 0 else None, + save_path=str(path), show=False) + saved.append(path.read_bytes()) + assert saved[0] == saved[1] and len(saved[0]) > 1000