Skip to content

Commit a9397b6

Browse files
mmschlkclaude
andauthored
FIxLIP demo: a write-up that explains the demo step by step (#660)
* docs(fixlip demo): a write-up that explains the demo step by step The page of the FIxLIP demo now has the demo on top and a write-up below it, in the style of the paper: why similarity is explained, the encoders, why its explanation needs interactions, related work and its shortcomings, the game, the explanation, conditioning, cliques, how FIxLIP is computed, the paper's three metrics, CLIP against SigLIP 2, limitations, and the code. 15 static figures illustrate it on the demo's first image-text pair for SigLIP 2. compute/evaluate.py evaluates the model on the masks they show (figures.json), and compute/figures.py draws them from the demo's data for the light and the dark theme. A page names the light file, and the demos' extension adds the dark one, each shown in its theme. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs: changelog entry for the FIxLIP write-up Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip demo): figures that follow the demo's image, the paper's plots, amber The figures of the write-up are no longer static images of the first pair. They are drawn in the browser by assets/figures.js and show the image-text pair chosen in the demo. Every figure has its own selector, which chooses the pair for the whole page, and a note that reads off its numbers for the chosen pair. On small screens the selector becomes a swipe with dots. The demo and the figures tell each other about a choice with the event "fixlip-demo-image". - new directive shapiq-demo-figure, which replaces the light and dark image pairs - compute/evaluate.py evaluates SigLIP 2 on the masks of the figures for all five photos and writes assets/figures-data.js - compute/paper.py reads the data of the paper's plots (faithfulness, insertion and deletion, runtime) from its vector figures, and the page draws them again - Figure 2 of the paper is shown as it is - amber joins the design tokens of the docs and replaces purple on the page, and the page's links are underlined in amber - the text holds for every pair, and statements about all five pairs are verified Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip demo): a neutral note on the largest main effect Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip demo): figures narrower than the text, numbered captions The figures of the page are inset to 38rem and centered in the text column. On a page with a demo's figures, the extension numbers the captions of all figures and tables in the order of the page. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip demo): work in a review round on the write-up The text refers to its figures by number (new role shapiq-figure), and it no longer describes one pair next to figures that follow the demo. Corrections against the paper: the sign of the elephant and small interaction per model, the first-order conversion, the budgets of the two estimators, the baselines in the faithfulness results, the choice of p, and the limitations. Figures: notes that hold for every pair, four masks for the game, the 12 strongest interactions as in the demo, the paper's curves drawn in the direction of the demo's, speedups in the runtime plot, larger dots and a swipe hint on phones. On this page the demo uses amber as well, and its texts use the terms of the write-up. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip demo): two figures with a slider, three figures less, a computed pointing game The figure on cliques has a slider for the size of the clique and a chart of its value against the gain on the model. The figure on insertion and deletion has a slider for the number of tokens kept and shows the two subsets of this size. The browser finds them with the demo's greedy search, which was checked against the search in Python for every size. The three views of one explanation and the grid of masked images and texts are removed, and the figure on the two modalities is merged into the figure on masked inputs. The left panel of the pointing game is computed. compute/pointing.py explains four photos of the demo in one image for SigLIP 2, and the figure shows the interactions of each name with the patches. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip demo): a plot that overlays ticked methods, textual citations The figure with the insertion and deletion curves of the methods gets a plot on top that overlays the methods ticked in the small plots below. Every method keeps one color, which is told apart from the other six on both surfaces, also with a red-green color vision deficiency. The plot reads off the values under the pointer. The text no longer refers to "the paper". It cites the authors in the text (cite:t) or names them as the authors. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip demo): figures of one height that fade between pairs, numbered sections and equations The figures keep their height for every pair and fade from one pair to the next. The notes below the figures are gone: what they said is in the figure, its caption or the text. The figure on regions and words is dropped. Every plot has a label on both axes. The equations follow the notation of the paper and are numbered, and the sections are numbered with subsections. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip demo): a summary in a box, a divider under the demo The two paragraphs under the demo give way to a divider. The first section is the summary of the page, set like an abstract in a box in the amber of the docs. It has no number, so the sections are numbered from Background. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip demo): repair a comment in the figures' stylesheet The rule that sets the number of an equation next to it was lost behind a damaged comment. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): part-by-part transitions, a slider in the demo, direct titles - A figure changes from one pair to the next part by part: what is the same stays, a photo fades in over the one before, a text fades out before the next one fades in, and the dot of a chart moves. A part with many changes fades as a whole. - The demo sets the size of its clique with a slider in place of two buttons. - The sliders are drawn by the style sheet and keep their color while pressed. - Caption markers are set in the amber of the plots. - The link of an equation no longer moves the equation when it appears. - Sections are not numbered, their titles are direct and in title case. - Every row of Table 1 can be read on its own. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): name the insertion and deletion curves, subsets under the chart - The figure of the pair's curves names its curves as insertion (read from the left) and deletion (read from the right) and its two subsets as the tokens inserted and the tokens left by the deletion. The figure of the paper's curves uses the same names. - The two subsets lie side by side under the chart, each with its text next to its photo, so that no room stays empty next to the chart. - The text gives both curves as the authors define them. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): a summary of the page and an introduction The box under the demo now sums up the page like an abstract: what FIxLIP is, what the page covers and its main finding. The three paragraphs that motivate the problem are the Introduction again. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): the embeddings that SigLIP 2 computes in the figure of the encoders The figure showed a sketch of two vectors. It now shows the first four of the 768 values of the image embedding and of the text embedding of the chosen pair, of unit length, as column vectors. compute/evaluate.py writes them to figures-data.js. Their dot product is the similarity of the pair. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): align the figures and tighten the limitations A review of the alignment in all figures, measured in the browser at desktop, tablet and phone width, and Max's comments on the page. - Figure 1: inputs, encoders and embeddings lie on one line per branch, the labels hang under them, and the bracket of the similarity runs from the middle of one embedding to the middle of the other. On a phone both labels share a line, both encoders have one width, and a bracket joins the branches. - Figure 8: the slider lies under the axis of the chart, and the plot is as high as the photo next to it. Figure 15: the same height rule, and a name keeps its place when another one turns bold. - Legends, titles and readings lie over the middle of the plot and not of the drawing with its margins. Stacked readings share one edge. - Figure 11 is square. Figure 13: the track of the slider ends where the axis ends, and its label stays in place. Figure 14: a last row that is not full lies in the middle. - Table 1: cells start on one line, as wide as a figure, and its caption has a bold lead. Figure 4 has no inset on a light page. - On a phone, the header of a figure shows the photo of the pair, and stacked parts have one distance in all figures. - Limitations as six short points with the page's own numbers. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): larger texts in the figures on a narrow page On a phone, the labels, tokens, legends and chart texts of the figures were 11 to 13 px. They follow one scale now (--fixlip-type), which is an eighth larger where a figure is narrow, and the captions are 15 px. The charts scale their margins with it, the header of a figure keeps the room of a label of two lines, and the names of the encoders and of the pointing game stay on one line. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): the comments on the writing, first part The demo calls the patches and words features, drops the line on the model and shows the photo's credit small under the demo. The introduction has two paragraphs and names more applications. The background gives the signature of the model, describes vision-language encoders in general before CLIP and SigLIP, and reads a similarity score relative to matching and unrelated pairs. The section on interactions is one argument. The axis of the figure on the scales reaches beyond its outer ticks. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): the comments on the writing, second part The figure of the encoders carries the notation of the text with the numbers of the pair. The axis of the figure on the scales ends inside its outer tenths. The introduction ends on what the model sees as similar, and the section on interactions cites Liang et al. at its start. The title of the page no longer starts with the name of the method. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): the comments on the writing, third part The table of the families of methods is deleted. The text and the figures call the image-text pairs of the demo examples. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): split the figure of the masks in two The masks of one modality alone stay in the section on interactions. The masks without an object and the random masks move to the section on the game. The figure of the encoders keeps the signatures and plain labels. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): call the game the vision-language game Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): amber braces under the two masked inputs of the game The equation of the game names its two arguments as the masked image and the masked text. The braces take their color from style rules, which hold for both the SVG and the HTML output of MathJax and follow the theme. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): say that removal is a choice and join the paragraph on the masks Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): drop the note on the logit scale Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): the explanation as a named definition before the game The definition of an explanation is set in a box that the page numbers and links, with the new directive shapiq-definition. The additive model moves into the section on the game, and the rest of the former section is now Interpreting the FIxLIP Explanation. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): say the first-order conversion and the additive model in words Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): set the words red and blue in the colors of the figures Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): lead from the definition of an explanation into the game Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): the game, the p-faithfulness and the FIxLIP explanation as definitions Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs: the number of a definition in the amber of its box Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): lead up to the game at the end of the section intro Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): define an explanation by its three parts, without the basis Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): open the section on interpreting without a paragraph name Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): say things in general instead of pointing at the demo Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): general statements instead of the authors and of we Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): keep the setup of the experiments out of the running text Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): say the two faithfulness metrics in words and give the R^2 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): define the explanation completely before interpreting it The definitions of the p-faithfulness and of the FIxLIP explanation move into the section that defines the method. Interpreting the explanation is a section of its own, and the section on computing keeps the estimation. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): align the braces of Definition 1 and drop two filler phrases The three braced terms of Definition 1 get the depth of the deepest term and the three labels the same strut, so that the braces and the labels sit on one line. The sentence that calls the first-order conversion simple and a "Note that" are removed. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): lead the game with the player set and the value function The section on the vision-language game opens with the cooperative game as a tuple of a player set and a value function. Definition 2 states the game as this tuple. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): move the equal weights of p = 0.5 to the paragraph on masking Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): caption of the masking figure names its rows and the dashed lines Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): Definition 2 names the image and text tokens and its two terms Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs: changelog entry names the definition boxes of the FIxLIP page Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): the p in the lead of a caption is bold italic text A math symbol between the bold parts of a caption lead took the muted color of the caption. The role fixlip-lead sets the symbol in italics with the weight and the color of the lead. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): captions say on which side a panel lies The captions of the interaction measured on the model, of the faithfulness of the methods and of the pointing game name their panels with (left) and (right) or (top) and (bottom). Where the panels stack on a narrow figure, the caption shows the word for the stacked layout (roles fixlip-wide and fixlip-narrow, switched by the container query of the figures). The text refers to the panels of the pointing game as the first and the second. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): the page speaks for the method and cites it in a box at the end The text no longer points at the FIxLIP paper after every statement. FIxLIP and the explanation are the subjects, results are told apart by their scope (the five examples, or 1,000 image-text pairs from MS COCO), and shapiq is named where it computes. The paper is cited where FIxLIP is introduced, for the two formal results on the cross-modal estimator, and in a new box "Citation" at the end, which lists what is taken from the paper and gives a BibTeX entry. The source credits of the redrawn figures move into this box. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip demo): Figure 4 compares the methods on the chosen example The static image of the paper's comparison of GAME, Grad-ECLIP, exCLIP and FIxLIP is replaced by a live figure for CLIP (ViT-B/32) that follows the example chosen on the page. - compute/baselines.py explains the five photos with GAME, Grad-ECLIP and exCLIP on the Hugging Face CLIPModel, with the settings of FIxLIP's repository, and writes the part "baselines" of assets/figures-data.js. The other parts of the file are unchanged. - assets/figures.js draws the figure "methods" with the existing helpers. The FIxLIP panel is the demo's explanation of CLIP. No other figure changes. - The image figures/paper-methods.webp and its CSS are removed, and the Citation box no longer lists the figure as taken from the paper. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip demo): the demo has the first screen of its page to itself The demo and a link to the write-up sit in a block that reaches to the end of the screen (.fixlip-opening). The demo is centered in the room under the lead, and the write-up starts below the screen. - The link "Read the write-up" with an arrow scrolls to the Summary box. Where the demo is higher than the screen, the link stays at the lower edge of the screen over a fade until the end of the demo is reached. On a phone it follows the demo. - figures.js measures where the block starts, so that it ends with the screen at any width. - In print the block has no minimal height and the link is hidden. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip demo): a way from the demo into the write-up - The link to the write-up is slimmer: a smaller, lighter label and a thin arrow. - The divider after the demo is a thin line down a stretch of empty page (42 % of the screen height, between 9 and 24 rem), from nothing to the amber of the Summary box that it ends at. - With figures.js the line is drawn as the page is scrolled, and the Summary box fades in and comes up into its place while it enters the screen. Links to the box land where it ends up. - With reduced motion, without JavaScript and in print, the line and the box are simply there. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): drop the note on joint work from the citation box Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): snap between the demo and the summary The start of the page has two places to rest, the demo and the summary. With a mouse or a trackpad, the page gives a little under a scroll and then travels to the other place by itself. The link under the demo travels the same way. The line and the fade of the last round are gone. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): first page with the demo, the write-up slides over it The title and the demo stay in place on a wide screen and recede while the write-up slides over them like a sheet. This replaces the snap. The title is centered on one line, the lead before the demo is gone, and the note behind the demo's i is rewritten with links into the write-up. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc * docs(fixlip): no changelog entry for the write-up Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019qiuyCA3ZwoP9HdB6UGfZc --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 4d53802 commit a9397b6

20 files changed

Lines changed: 6373 additions & 254 deletions

‎docs/source/_ext/shapiq_demos.py‎

Lines changed: 233 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,43 @@
3838
The assets are copied before the pages are written, so that Sphinx adds its checksums to the links
3939
of ``demo.css`` and ``demo.js``, and they are dependencies of the pages that embed the demo, so that a
4040
change to them writes these pages again.
41+
42+
The ``shapiq-demo-figure`` directive adds a figure that a demo's script draws on the page, e.g.
43+
one that follows what the demo shows. Its arguments are the demo and the name of the figure, and
44+
its content is the caption::
45+
46+
.. shapiq-demo-figure:: fixlip masks
47+
:alt: What the figure shows.
48+
49+
**The game assigns a similarity to every mask.** The caption.
50+
51+
It writes ``<figure class="<demo>-figure" data-figure="<name>" data-root="...">`` with an empty
52+
stage, which is labeled with the alt text and shows it without JavaScript, and the caption. A page
53+
with such figures gets ``figures.css``, the demo's ``data.js``, ``figures-data.js`` (if the demo has
54+
one) and ``figures.js`` of the demo's assets. Outside HTML, only the caption is kept.
55+
56+
On a page with such figures, the captions are numbered in the order of the page. The figures of
57+
the directive and the ``figure`` directives with a caption count as ``Figure 1``, ``Figure 2``,
58+
and so on, and the tables with a title as ``Table 1``, and so on. The other pages of the docs keep
59+
their captions as they are. The role ``shapiq-figure`` refers to a figure or a table of the page by
60+
its number, as a link. Its target is the name of a demo's figure, or the ``:name:`` of a ``figure``
61+
or a table::
62+
63+
:shapiq-figure:`masks` shows eight masks.
64+
65+
The ``shapiq-definition`` directive sets a central definition in a box of its own. Its argument is
66+
the name of the definition, its content the statement, and its ``:name:`` what refers to it::
67+
68+
.. shapiq-definition:: Explanation
69+
:name: fixlip-def-explanation
70+
71+
An explanation assigns ...
72+
73+
The definitions of a page are numbered in its order, as ``Definition 1 (Explanation)``, and so on,
74+
and the title of a box links to it. The role ``shapiq-statement`` refers to a definition by its
75+
number, as a link. Its target is the ``:name:`` of the box::
76+
77+
:shapiq-statement:`fixlip-def-explanation` covers main effects and interactions.
4178
"""
4279

4380
from __future__ import annotations
@@ -50,6 +87,7 @@
5087

5188
from docutils import nodes
5289
from docutils.parsers.rst import directives
90+
from sphinx.util import logging
5391
from sphinx.util.docutils import SphinxDirective
5492
from sphinx.util.osutil import relative_uri
5593

@@ -58,8 +96,14 @@
5896
from sphinx.util.typing import ExtensionMetadata
5997
from sphinx.writers.html5 import HTML5Translator
6098

99+
logger = logging.getLogger(__name__)
100+
61101
_ASSETS = ("demo.js", "demo.css") # the files that every demo's assets folder has
62102
_DATA = "data.js" # the demo's data, which its script loads, if it has any
103+
_FIGURES = ("figures.js", "figures.css") # the files of a demo with figures on a page
104+
_FIGURES_DATA = "figures-data.js" # what the figures show beyond the demo's data, if anything
105+
_STATEMENTS = ("definition",) # the kinds of statements that get a box, as ``shapiq-<kind>``
106+
_STATEMENT = "shapiq-statement" # the class of a box and the name of the role that refers to one
63107

64108

65109
class DemoNode(nodes.General, nodes.Element):
@@ -101,6 +145,65 @@ def run(self) -> list[nodes.Node]:
101145
return [node]
102146

103147

148+
class FigureNode(nodes.General, nodes.Element):
149+
"""A figure that a demo's script draws; its children are the caption."""
150+
151+
152+
class FigureDirective(SphinxDirective):
153+
"""Add a figure of a demo: ``.. shapiq-demo-figure:: <demo> <name>``, with its caption."""
154+
155+
required_arguments = 2
156+
has_content = True
157+
option_spec: ClassVar[dict[str, Any]] = {
158+
"alt": directives.unchanged_required, # what the figure shows, in words
159+
}
160+
161+
def run(self) -> list[nodes.Node]:
162+
"""Return the figure with its parsed caption, after checking the demo's assets."""
163+
demo, name = self.arguments
164+
assets = Path(self.env.srcdir) / "demos" / demo / "assets"
165+
if missing := [file for file in _FIGURES if not (assets / file).is_file()]:
166+
msg = f"the demo {demo!r} has no {', '.join(missing)} in demos/{demo}/assets"
167+
raise self.error(msg)
168+
for file in (*_FIGURES, _DATA, _FIGURES_DATA):
169+
if (assets / file).is_file():
170+
self.env.note_dependency(str(assets / file))
171+
node = FigureNode(demo=demo, figure=name, alt=self.options.get("alt", ""))
172+
node["ids"].append(f"{demo}-figure-{name}")
173+
self.state.nested_parse(self.content, self.content_offset, node)
174+
return [node]
175+
176+
177+
class StatementDirective(SphinxDirective):
178+
"""Set a statement in a box: ``.. shapiq-definition:: <name>``, with the statement."""
179+
180+
required_arguments = 1
181+
final_argument_whitespace = True
182+
has_content = True
183+
option_spec: ClassVar[dict[str, Any]] = {
184+
"name": directives.unchanged, # what the role and ``:ref:`` refer to
185+
}
186+
187+
def run(self) -> list[nodes.Node]:
188+
"""Return the box with its title, which is numbered when the page is written."""
189+
kind = self.name.removeprefix("shapiq-")
190+
node = nodes.container(classes=[_STATEMENT, f"{_STATEMENT}-{kind}"], statement=kind)
191+
name, messages = self.state.inline_text(self.arguments[0], self.lineno)
192+
title = nodes.paragraph("", "", classes=[f"{_STATEMENT}-title"])
193+
title += nodes.inline("", "", nodes.Text("("), *name, nodes.Text(")"))
194+
node += title
195+
self.state.nested_parse(self.content, self.content_offset, node)
196+
self.add_name(node)
197+
return [node, *messages]
198+
199+
200+
class FigureReference(nodes.Inline, nodes.Element):
201+
"""A reference to a numbered figure, table or statement, resolved when the page is written."""
202+
203+
204+
_CAPTIONED = (FigureNode, nodes.figure, nodes.table) # what a page with figures numbers
205+
206+
104207
def _visit_demo(self: HTML5Translator, node: DemoNode) -> None:
105208
page = self.builder.get_target_uri(self.builder.current_docname)
106209
root = relative_uri(page, f"_static/demos/{node['demo']}/")
@@ -126,6 +229,99 @@ def _skip_demo(self: nodes.NodeVisitor, node: DemoNode) -> None: # noqa: ARG001
126229
raise nodes.SkipNode
127230

128231

232+
def _visit_figure(self: HTML5Translator, node: FigureNode) -> None:
233+
page = self.builder.get_target_uri(self.builder.current_docname)
234+
root = relative_uri(page, f"_static/demos/{node['demo']}/")
235+
name = f"{node['demo']}-figure"
236+
self.body.append(
237+
self.starttag(
238+
node, "figure", CLASS=name, **{"data-figure": node["figure"], "data-root": root}
239+
)
240+
)
241+
alt = escape(node["alt"])
242+
self.body.append(
243+
f'<div class="{name}-stage" role="group" aria-label="{alt}">'
244+
f'<noscript><p class="{name}-missing">{alt}</p></noscript></div>\n<figcaption>\n'
245+
)
246+
247+
248+
def _depart_figure(self: HTML5Translator, node: FigureNode) -> None: # noqa: ARG001
249+
self.body.append("</figcaption>\n</figure>\n")
250+
251+
252+
def _keep_caption(self: nodes.NodeVisitor, node: FigureNode) -> None:
253+
"""Outside HTML, a figure is its caption."""
254+
255+
256+
def _figure_role(
257+
name: str, # noqa: ARG001
258+
rawtext: str,
259+
text: str,
260+
lineno: int, # noqa: ARG001
261+
inliner: object, # noqa: ARG001
262+
options: dict[str, Any] | None = None, # noqa: ARG001
263+
content: list[str] | None = None, # noqa: ARG001
264+
) -> tuple[list[nodes.Node], list[nodes.system_message]]:
265+
"""Refer to a numbered part of the page: ``:shapiq-figure:`<name>```, or a statement."""
266+
return [FigureReference(rawtext, target=text.strip())], []
267+
268+
269+
def _number_captions(app: Sphinx, doctree: nodes.document, docname: str) -> None:
270+
"""Number the captions and the statements of a page, and link the references to them."""
271+
labels: dict[str, tuple[str, str]] = {} # the name of a numbered part: its number and id
272+
if next(iter(doctree.findall(FigureNode)), None) is not None:
273+
counts = {"Figure": 0, "Table": 0}
274+
for node in list(doctree.findall(lambda n: isinstance(n, _CAPTIONED))):
275+
kind = "Table" if isinstance(node, nodes.table) else "Figure"
276+
# the caption is the title of a table, the caption of a figure, or the first
277+
# paragraph of a demo's figure
278+
holder = (
279+
nodes.title
280+
if kind == "Table"
281+
else nodes.paragraph
282+
if isinstance(node, FigureNode)
283+
else nodes.caption
284+
)
285+
caption = next((child for child in node.children if isinstance(child, holder)), None)
286+
if caption is None:
287+
continue
288+
counts[kind] += 1
289+
label = f"{kind} {counts[kind]}"
290+
caption.insert(0, nodes.inline("", f"{label}. ", classes=["caption-number"]))
291+
names = [node["figure"]] if isinstance(node, FigureNode) else node["names"]
292+
for name in names:
293+
labels[name] = (label, node["ids"][0] if node["ids"] else "")
294+
counts = dict.fromkeys(_STATEMENTS, 0)
295+
for node in list(doctree.findall(nodes.container)):
296+
if (kind := node.get("statement")) not in counts:
297+
continue
298+
counts[kind] += 1
299+
label = f"{kind.capitalize()} {counts[kind]}"
300+
target = node["ids"][0] if node["ids"] else ""
301+
title = node.children[0]
302+
title.insert(0, [nodes.strong("", label), nodes.Text(" ")])
303+
if target and app.builder.format == "html":
304+
link = (
305+
f'<a class="headerlink" href="#{escape(target)}" title="Link to this {kind}">¶</a>'
306+
)
307+
title += nodes.raw("", link, format="html")
308+
for name in node["names"]:
309+
labels[name] = (label, target)
310+
for reference in list(doctree.findall(FigureReference)):
311+
label, target = labels.get(reference["target"], ("", ""))
312+
if not label:
313+
logger.warning(
314+
"no numbered figure, table or statement %r on this page",
315+
reference["target"],
316+
location=(docname, reference.line),
317+
)
318+
reference.replace_self(nodes.Text(reference["target"]))
319+
elif target and app.builder.format == "html":
320+
reference.replace_self(nodes.reference("", label, refid=target, internal=True))
321+
else:
322+
reference.replace_self(nodes.Text(label))
323+
324+
129325
def _add_assets(
130326
app: Sphinx,
131327
pagename: str, # noqa: ARG001
@@ -136,14 +332,25 @@ def _add_assets(
136332
"""Add the stylesheet and the script of every demo of a page to it."""
137333
if doctree is None:
138334
return
139-
for name in sorted({node["demo"] for node in doctree.findall(DemoNode)}):
140-
# the stylesheet after html_css_files, whose tokens.css it uses
141-
app.add_css_file(f"demos/{name}/demo.css", priority=900)
142-
# the data, if any, just before the script and loaded alongside it (not by it, once it has
143-
# run): the script uses the data on the page, and loads it itself where it is missing
144-
if (Path(app.srcdir) / "demos" / name / "assets" / _DATA).is_file():
145-
app.add_js_file(f"demos/{name}/{_DATA}", loading_method="defer", priority=499)
146-
app.add_js_file(f"demos/{name}/demo.js", loading_method="defer")
335+
demos = {node["demo"] for node in doctree.findall(DemoNode)}
336+
figures = {node["demo"] for node in doctree.findall(FigureNode)}
337+
for name in sorted(demos | figures):
338+
assets = Path(app.srcdir) / "demos" / name / "assets"
339+
# the stylesheets after html_css_files, whose tokens.css they use
340+
if name in demos:
341+
app.add_css_file(f"demos/{name}/demo.css", priority=900)
342+
if name in figures:
343+
app.add_css_file(f"demos/{name}/figures.css", priority=900)
344+
# the data, if any, just before the scripts and loaded alongside them (not by them, once
345+
# they have run): a script uses the data on the page, and loads it itself where it is missing
346+
data = [_DATA, *([_FIGURES_DATA] if name in figures else [])]
347+
for file in data:
348+
if (assets / file).is_file():
349+
app.add_js_file(f"demos/{name}/{file}", loading_method="defer", priority=499)
350+
if name in demos:
351+
app.add_js_file(f"demos/{name}/demo.js", loading_method="defer")
352+
if name in figures:
353+
app.add_js_file(f"demos/{name}/figures.js", loading_method="defer")
147354

148355

149356
def _copy_assets(app: Sphinx, env: object) -> None: # noqa: ARG001
@@ -156,7 +363,7 @@ def _copy_assets(app: Sphinx, env: object) -> None: # noqa: ARG001
156363

157364

158365
def setup(app: Sphinx) -> ExtensionMetadata:
159-
"""Register the directive, its node and the assets."""
366+
"""Register the directives, their nodes and roles, and the assets."""
160367
skip = (_skip_demo, None)
161368
app.add_node(
162369
DemoNode,
@@ -166,12 +373,28 @@ def setup(app: Sphinx) -> ExtensionMetadata:
166373
man=skip,
167374
texinfo=skip,
168375
)
376+
keep = (_keep_caption, _keep_caption)
377+
app.add_node(
378+
FigureNode,
379+
html=(_visit_figure, _depart_figure),
380+
latex=keep,
381+
text=keep,
382+
man=keep,
383+
texinfo=keep,
384+
)
169385
app.add_directive("shapiq-demo", DemoDirective)
386+
app.add_directive("shapiq-demo-figure", FigureDirective)
387+
app.add_node(FigureReference)
388+
app.add_role("shapiq-figure", _figure_role)
389+
for kind in _STATEMENTS:
390+
app.add_directive(f"shapiq-{kind}", StatementDirective)
391+
app.add_role(_STATEMENT, _figure_role)
392+
app.connect("doctree-resolved", _number_captions)
170393
app.connect("html-page-context", _add_assets)
171394
app.connect("env-updated", _copy_assets)
172395
return {
173396
"version": "1.0",
174-
"env_version": 2, # the nodes carry a version: environments of earlier builds are read again
397+
"env_version": 8, # pages are read again where what the extension writes to them changed
175398
"parallel_read_safe": True,
176399
"parallel_write_safe": True,
177400
}

‎docs/source/_static/css/custom.css‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,62 @@ html.shapiq-logo-pulling * {
111111
color: var(--color-brand-primary);
112112
}
113113

114+
/* -- Statements --------------------------------------------------------------------------------- */
115+
116+
/* A central definition of a page is set in a box of its own (see _ext/shapiq_demos.py), with an
117+
amber line at its left. Its number and its name are a line of their own, which links to it.
118+
The selector outweighs the one that takes the padding from every container of docutils. */
119+
div.docutils.shapiq-statement {
120+
margin: 1.5rem 0;
121+
padding: 0.9rem 1.25rem 0.3rem;
122+
border: 1px solid var(--color-background-border);
123+
border-left: 4px solid var(--shapiq-amber);
124+
border-radius: var(--shapiq-radius-small);
125+
background: var(--color-background-secondary);
126+
}
127+
128+
.shapiq-statement:target {
129+
background: var(--shapiq-amber-soft);
130+
}
131+
132+
.shapiq-statement > p {
133+
margin: 0 0 0.6rem;
134+
}
135+
136+
.shapiq-statement > .shapiq-statement-title {
137+
font-weight: 600;
138+
}
139+
140+
/* the number has the amber of the line at the left and of the captions' numbers */
141+
.shapiq-statement > .shapiq-statement-title > strong {
142+
font-weight: 700;
143+
color: var(--shapiq-amber);
144+
}
145+
146+
/* the link to a statement shows up when the pointer is over its box, and always without a pointer */
147+
.shapiq-statement > .shapiq-statement-title > .headerlink {
148+
margin-left: 0.4rem;
149+
font-weight: 400;
150+
color: var(--color-foreground-muted);
151+
text-decoration: none;
152+
visibility: hidden;
153+
}
154+
155+
.shapiq-statement:hover > .shapiq-statement-title > .headerlink,
156+
.shapiq-statement > .shapiq-statement-title > .headerlink:focus-visible {
157+
visibility: visible;
158+
}
159+
160+
@media (hover: none) {
161+
.shapiq-statement > .shapiq-statement-title > .headerlink {
162+
visibility: visible;
163+
}
164+
}
165+
166+
.shapiq-statement .math-wrapper {
167+
margin: 0.6rem 0;
168+
}
169+
114170
/* -- sphinx-design ------------------------------------------------------------------------------ */
115171

116172
.sd-card {

‎docs/source/_static/css/tokens.css‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@
66
--shapiq-blue: #4567f2;
77
--shapiq-blue-light: #82a9e7;
88
--shapiq-lavender: #b3c2e5;
9+
/* the docs' color: amber itself for lines and fills, its ink for text (5:1 on the page and on
10+
its soft tint), its soft tint for highlights */
11+
--shapiq-amber: #f5a300;
12+
--shapiq-amber-ink: #8c5800;
13+
--shapiq-amber-soft: rgba(245, 163, 0, 0.16);
914
--brand-ink-red: #ff2763; /* probly × shapiq family red */
1015
--brand-ink-blue: #285bff; /* probly × shapiq family blue */
1116
/* the logo's attribution scale (red 5 and 4, blue 3 and 2), through shapiq's violet */
@@ -27,6 +32,8 @@ body[data-theme="dark"] {
2732
--shapiq-surface-raised: #22252e;
2833
--shapiq-border: #343846;
2934
--shapiq-text-muted: #a3a9ba;
35+
--shapiq-amber-ink: #ffc24d;
36+
--shapiq-amber-soft: rgba(245, 163, 0, 0.18);
3037
--shapiq-shadow: 0 1px 2px rgba(0, 0, 0, 0.3), 0 4px 16px rgba(0, 0, 0, 0.25);
3138
--shapiq-shadow-hover: 0 2px 4px rgba(0, 0, 0, 0.35), 0 12px 32px rgba(0, 0, 0, 0.4);
3239
}
@@ -37,6 +44,8 @@ body[data-theme="dark"] {
3744
--shapiq-surface-raised: #22252e;
3845
--shapiq-border: #343846;
3946
--shapiq-text-muted: #a3a9ba;
47+
--shapiq-amber-ink: #ffc24d;
48+
--shapiq-amber-soft: rgba(245, 163, 0, 0.18);
4049
--shapiq-shadow: 0 1px 2px rgba(0, 0, 0, 0.3), 0 4px 16px rgba(0, 0, 0, 0.25);
4150
--shapiq-shadow-hover: 0 2px 4px rgba(0, 0, 0, 0.35), 0 12px 32px rgba(0, 0, 0, 0.4);
4251
}

0 commit comments

Comments
 (0)