% \iffalse meta-comment
%
% Copyright (C) 2016-2026 by Paul Gaborit
% -----------------------------------
%
% This work may be distributed and/or modified under the conditions of
% the LaTeX Project Public License, either version 1.3 of this license
% or (at your option) any later version.  The latest version of this
% license is in
%
% <http://www.latex-project.org/lppl.txt>
%
% and version 1.3 or later is part of all distributions of LaTeX version
% 2005/12/01 or later.
% 
% This work has the LPPL maintenance status “maintained”.
% 
% The Current Maintainer of this work is Paul Gaborit.
% 
% This work consists of the files sankey.dtx, sankey.ins and the derived
% files sankey.sty, tikzlibrarydubins.code.tex, sankey-doc-preamble.sty,
% sankey-example1.tex, sankey-example2.tex, sankey-example3.tex,
% sankey-example3-variation.tex, sankey-example4.tex,
% sankey-example-energy.tex, sankey-example-paper.tex,
% sankey-example-water.tex
%
%
% \fi
%
% \iffalse
%
%<*driver>
\documentclass[a4paper,10pt,draft]{ltxdoc}
\SetupDoc{reportchangedates}
\usepackage{sankey-doc-preamble}
\EnableCrossrefs
\CodelineIndex
\RecordChanges
\begin{document}
\DocInput{sankey.dtx}
\end{document}
%</driver>
% \fi
%
% \GetFileInfo{\jobname.dtx}
%
% \DoNotIndex{\newcommand,\newenvironment}
% \DoNotIndex{\#,\$,\%,\&,\@,\\,\{,\},\^,\_,\~,\ }
% \DoNotIndex{\begingroup,\endgroup,\begin,\end}
% \DoNotIndex{\def,\edef,\gdef,\xdef,\ifx,\else,\string,\relax}
% \DoNotIndex{\csname,\endcsname,\ifcsdef,\expandafter,\ifnumgreater}
% \DoNotIndex{\NewDocumentCommand,\NewDocumentEnvironment,\IfBooleanTF}
% \DoNotIndex{\NewCommandCopy,\NewExpandableDocumentCommand}
% \DoNotIndex{\NeedsTeXFormat,\ProvidesPackage,\RequirePackage,\PackageError,\PackageWarning}
% \DoNotIndex{\newtoggle,\toggletrue,\togglefalse,\iftoggle,\ifdefempty,\ifundef,\ifdefstrequal}
% \DoNotIndex{\ifbool,\ifdef,\ifnumequal,\colorlet,\fpeval,\inteval,\newbool}
% \DoNotIndex{\pgfmathsetmacro,\pgfdeclarelayer,\pgfdeclareshape,\pgfkeys,\pgfset,\usetikzlibrary}
% \DoNotIndex{\the,\pgf@x,\pgf@y,\tikz@scan@one@point,\pgfutil@firstofone}
% \DoNotIndex{\pgfsetlayers,\inheritsavedanchors,\inheritanchor,\inheritanchorborder,\anchor,\pgf@process,\northeast,\southwest}
% \DoNotIndex{\pgfmathresult,\pgfinterruptpath,\endpgfinterruptpath,\pgfkeysvalueof,\pgfmathtruncatemacro,\pgfmathparse}
% \DoNotIndex{\tikzset,\pgfextra,\pgflinewidth,\foreach,\coordinate}
% \DoNotIndex{\path,\node,\pgfmathprintnumber,\n,\p,\x,\y}
% \DoNotIndex{\tiny,\ttfamily,\space}
%
% \title{The \textsf{sankey} package\\
% Draw Sankey diagrams via TikZ}
%
% \author{Paul Gaborit
% (\href{mailto:paul.gaborit@gmail.com}{\texttt{paul.gaborit@gmail.com}})}
% \date{\fileversion{} -- \filedate{}}
%
% \GetFileInfo{sankey.sty}
%
% \def\manualparts{
% \begin{quote}
%   This manual contains three parts:
%   \nameref{usermanual} (p.\pageref{usermanual}),
%   \nameref{examples} (p.\pageref{examples})
%   and \nameref{implementation} (p.\pageref{implementation}).
% \end{quote}
% }
%
% \maketitle
%
% \hypersetup{
%  pdftitle=How to use the sankey package to build Sankey diagrams (\fileversion),
%  pdfauthor=Paul Gaborit,
% }
%
% \def\ttintitle#1{\textmd{\textcolor{red!50!black}{\texttt{#1}}}}
%
%
% \begin{abstract}
%   The \code{sankey} package provides macros and environments to
%   build \emph{Sankey
%   diagrams}\footnote{\url{https://en.wikipedia.org/wiki/Sankey_diagram}},
%   i.e.  \emph{flow diagrams} in which the width of the arrows is
%   proportional to the flow rate.  The initial idea for the first
%   implementation came out from
%   \href{https://tex.stackexchange.com/q/40159/14500}{this question} on
%   \href{https://tex.stackexchange.com/}{TeX.StackExchange}.
%   
%
% \end{abstract}
%
%
% \manualparts
%
% \clearpage
%
% \manualparts
%
% \begin{quote}
%   {\footnotesize Note: the \code{sankey.dtx} and \code{sankey.ins}
%   files are attachments of the current PDF document.\par}
% \end{quote}
% 
%^^A % ------------------------------------------------------------
% \part{User manual}
% \label{usermanual}
%^^A % ------------------------------------------------------------
%
% \changes{v3.0.2}{2025/01/10}{Update for new version of \protect\code{ltxdoc} class}
% 
% \changes{v3.0.2}{2025/01/10}{Fixed extra parentheses in some code examples}
%
% {
%   \setlength{\parskip}{0pt}
%   \localtableofcontents
% }
%
% \clearpage
% 
%^^A % ------------------------------------------------------------
% \section{Preamble}
%^^A % ------------------------------------------------------------
%
% To use the \code{sankey} package, insert the following line in your preamble:
%
% \begin{lstlisting}[style=LaTeXsmall]
% \usepackage{sankey}
% \end{lstlisting}
%
% {\small Note: the
% \code{sankey} package requires automatically the
% \code{xparse}, \code{etoolbox}, \code{xfp} and
% \code{tikz} packages, as well as the \code{calc},
% \code{decorations.markings}, \code{positioning} and
% \code{dubins} (cf. \vref{sec:dubins}) TikZ libraries.\par}
%
%
%^^A % ------------------------------------------------------------
% \section{The \ttintitle{sankeydiagram} environment}
%^^A % ------------------------------------------------------------
%
% \DescribeEnv{sankeydiagram} %
% A \code{sankeydiagram} environment nested in a \code{tikzpicture}
% environment activates the sankey macros:
%
% \begin{lstlisting}[style=LaTeXsmall]
% \begin{tikzpicture}
%   \begin{sankeydiagram}[... options ...]
%     ... sankey macros ...
%   \end{sankeydiagram}  
% \end{tikzpicture}
% \end{lstlisting}
%
%^^A % ------------------------------------------------------------
% \section{Tutorial}
% \label{sec:tutorial}
%^^A % ------------------------------------------------------------
%
% \changes{v3.1.0}{2026/11/29}{Add a tutorial}
%
% This tutorial builds, step by step, a small Sankey diagram: an income
% (100 units) split into housing (40), food (25), other expenses (20)
% and savings (15). The last steps add a second source of income. Each
% step shows the complete code and its result
% (the gray grid and the axes are only drawn in this manual; the unit
% of the grid is 5\,mm).
%
%^^A % ------------------------------------------------------------
% \subsection{Step 1: the first Sankey node}
%^^A % ------------------------------------------------------------
%
% A Sankey diagram is drawn by a \code{sankeydiagram} environment nested
% in a \code{tikzpicture} environment. The \code{ratio} option sets the
% scale: here, a quantity of 100 is drawn with a width of 2\,cm. The
% \code{debug} option shows the Sankey nodes (their names, their
% \code{left} and \code{right} anchors and their direction). The
% \code{start style} and \code{end style} options choose the shapes of
% the starts and ends of flows.
%
% A \emph{Sankey node} is a TikZ node with a name, a quantity (its
% width), a position (its \code{at} key, the origin by default) and a
% direction (its \code{angle}, $0$ by default: the flow goes to the
% right). The \code{\sankeynodestart} macro creates
% a Sankey node and draws the start of the flow:
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[ratio=2cm/100,debug,
%     start style=simple,end style=arrow]
%     \sankeynodestart{name=income,quantity=100}
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
%
%^^A % ------------------------------------------------------------
% \subsection{Step 2: move forward}
%^^A % ------------------------------------------------------------
%
% The \code{\sankeyadvance} macro moves a Sankey node forward (in its
% direction) and draws the flow between its previous and its new
% positions. The node keeps its name (its previous position is still
% available under the name \code{income-old}):
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[ratio=2cm/100,debug,
%     start style=simple,end style=arrow]
%     \sankeynodestart{name=income,quantity=100}
%     \sankeyadvance{income}{2cm}
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
%
%^^A % ------------------------------------------------------------
% \subsection{Step 3: split the flow}
%^^A % ------------------------------------------------------------
%
% The \code{\sankeyfork} macro splits a Sankey node into several Sankey
% nodes, from its left side to its right side (here, from top to bottom).
% Each new node is given by a \emph{quantity/name} pair and the sum of
% the quantities must be equal to the quantity of the split node:
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[ratio=2cm/100,debug,
%     start style=simple,end style=arrow]
%     \sankeynodestart{name=income,quantity=100}
%     \sankeyadvance{income}{2cm}
%     \sankeyfork{income}{40/housing,25/food,20/other,15/savings}
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
%
%^^A % ------------------------------------------------------------
% \subsection{Step 4: link nodes}
%^^A % ------------------------------------------------------------
%
% The \code{\sankeynodeend} macro creates a Sankey node and draws the end
% of a flow. The \code{\sankeydubins} macro draws a flow of constant
% width between two Sankey nodes with the same quantity: the shortest
% path whose radius of curvature is never smaller than the
% \code{minimum radius} option (5\,mm by default). The positions of the
% new nodes are relative to the nodes created by \code{\sankeyfork}:
% they use the syntax of the \code{positioning} TikZ library (loaded by
% the \code{sankey} package) with distances measured between the
% centers of the nodes. The \code{\sankeyset}
% macro changes options in the middle of a diagram: here, a larger
% minimum radius gives smoother links:
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[ratio=2cm/100,debug,
%     start style=simple,end style=arrow]
%     \sankeynodestart{name=income,quantity=100}
%     \sankeyadvance{income}{2cm}
%     \sankeyfork{income}{40/housing,25/food,20/other,15/savings}
%     \sankeynodeend{name=housing-end,quantity=40,
%       above right={1cm and 4cm of housing}}
%     \sankeynodeend{name=food-end,quantity=25,
%       above right={.35cm and 4cm of food}}
%     \sankeynodeend{name=other-end,quantity=20,
%       below right={.3cm and 4cm of other}}
%     \sankeyset{minimum radius=15mm}
%     \sankeydubins{housing}{housing-end}
%     \sankeydubins{food}{food-end}
%     \sankeydubins{other}{other-end}
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
%
%^^A % ------------------------------------------------------------
% \subsection{Step 5: turn}
%^^A % ------------------------------------------------------------
%
% The \code{\sankeyturnright} and \code{\sankeyturnleft} macros move a
% Sankey node by turning (here, 90 degrees to the right). Like all
% Sankey macros, they accept options: here, a smaller minimum radius for
% this turn only. The
% \code{\sankeyend} macro draws the end of the flow of an existing Sankey
% node:
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[ratio=2cm/100,debug,
%     start style=simple,end style=arrow]
%     \sankeynodestart{name=income,quantity=100}
%     \sankeyadvance{income}{2cm}
%     \sankeyfork{income}{40/housing,25/food,20/other,15/savings}
%     \sankeynodeend{name=housing-end,quantity=40,
%       above right={1cm and 4cm of housing}}
%     \sankeynodeend{name=food-end,quantity=25,
%       above right={.35cm and 4cm of food}}
%     \sankeynodeend{name=other-end,quantity=20,
%       below right={.3cm and 4cm of other}}
%     \sankeyset{minimum radius=15mm}
%     \sankeydubins{housing}{housing-end}
%     \sankeydubins{food}{food-end}
%     \sankeydubins{other}{other-end}
%     \sankeyturnright[minimum radius=2mm]{savings}{90}
%     \sankeyadvance{savings}{5mm}
%     \sankeyend{savings}
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
%
%^^A % ------------------------------------------------------------
% \subsection{Step 6: styles}
%^^A % ------------------------------------------------------------
%
% The \code{fill} and \code{draw} styles define how the flows are filled
% and drawn. Here, a new
% \code{color} style sets the \code{fill} style and it is used as an
% option of each macro (every Sankey macro accepts options). The
% \code{debug} option is removed:
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[ratio=2cm/100,
%     start style=simple,end style=arrow,
%     draw/.style={draw=none},
%     color/.style={fill/.style={fill=#1}}]
%     \sankeynodestart[color=gray!40]{name=income,quantity=100}
%     \sankeyadvance[color=gray!40]{income}{2cm}
%     \sankeyfork{income}{40/housing,25/food,20/other,15/savings}
%     \sankeynodeend[color=red!40]{name=housing-end,quantity=40,
%       above right={1cm and 4cm of housing}}
%     \sankeynodeend[color=orange!50]{name=food-end,quantity=25,
%       above right={.35cm and 4cm of food}}
%     \sankeynodeend[color=blue!30]{name=other-end,quantity=20,
%       below right={.3cm and 4cm of other}}
%     \sankeyset{minimum radius=15mm}
%     \sankeydubins[color=red!40]{housing}{housing-end}
%     \sankeydubins[color=orange!50]{food}{food-end}
%     \sankeydubins[color=blue!30]{other}{other-end}
%     \sankeyturnright[color=green!40,minimum radius=2mm]{savings}{90}
%     \sankeyadvance[color=green!40]{savings}{5mm}
%     \sankeyend[color=green!40]{savings}
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
%
%^^A % ------------------------------------------------------------
% \subsection{Step 7: labels}
%^^A % ------------------------------------------------------------
%
% Sankey nodes are TikZ nodes: their \code{center}, \code{left} and
% \code{right} anchors can be used to place labels with the usual TikZ
% \code{\node} command. The \code{\sankeygetnodeqty} macro gives the
% quantity of a Sankey node (so, the values are not written twice):
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[ratio=2cm/100,
%     start style=simple,end style=arrow,
%     draw/.style={draw=none},
%     color/.style={fill/.style={fill=#1}}]
%     \sankeynodestart[color=gray!40]{name=income,quantity=100}
%     \sankeyadvance[color=gray!40]{income}{2cm}
%     \sankeyfork{income}{40/housing,25/food,20/other,15/savings}
%     \sankeynodeend[color=red!40]{name=housing-end,quantity=40,
%       above right={1cm and 4cm of housing}}
%     \sankeynodeend[color=orange!50]{name=food-end,quantity=25,
%       above right={.35cm and 4cm of food}}
%     \sankeynodeend[color=blue!30]{name=other-end,quantity=20,
%       below right={.3cm and 4cm of other}}
%     \sankeyset{minimum radius=15mm}
%     \sankeydubins[color=red!40]{housing}{housing-end}
%     \sankeydubins[color=orange!50]{food}{food-end}
%     \sankeydubins[color=blue!30]{other}{other-end}
%     \sankeyturnright[color=green!40,minimum radius=2mm]{savings}{90}
%     \sankeyadvance[color=green!40]{savings}{5mm}
%     \sankeyend[color=green!40]{savings}
%     \tikzset{every node/.style={font=\small\sffamily}}
%     \node[anchor=east] at ([xshift=-3pt]income-old.center)
%     {Income (\sankeygetnodeqty{income})};
%     \foreach \flow/\text in {housing/Housing,food/Food,other/Other}{
%       \node[anchor=west] at ([xshift=12pt]\flow-end.center)
%       {\text\ (\sankeygetnodeqty{\flow-end})};
%     }
%     \node[anchor=north] at ([yshift=-12pt]savings.center)
%     {Savings (\sankeygetnodeqty{savings})};
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
%
%^^A % ------------------------------------------------------------
% \subsection{Step 8: merge two flows}
%^^A % ------------------------------------------------------------
%
% Now, the income comes from two sources: a salary (80) and other
% incomes (20). To merge two flows, the merged Sankey node is created
% \emph{already split}: the \code{forked} key of \code{\sankeynode}
% creates the \code{income} node and its \code{salary-in} and
% \code{extra-in} subnodes (from left to right, as with
% \code{\sankeyfork}). Then each source is linked to its subnode by
% \code{\sankeydubins} (the sources are placed relative to the subnodes).
% Here, only the beginning of the diagram is shown
% (with the \code{debug} option to see the subnodes):
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[ratio=2cm/100,debug,
%     start style=simple,end style=arrow,minimum radius=15mm]
%     \sankeynode{name=income,quantity=100,
%       forked={80/salary-in,20/extra-in}}
%     \sankeynodestart{name=salary,quantity=80,
%       above left={1cm and 3.4cm of salary-in}}
%     \sankeynodestart{name=extra,quantity=20,
%       below left={.8cm and 3.4cm of extra-in}}
%     \sankeydubins{salary}{salary-in}
%     \sankeydubins{extra}{extra-in}
%     \sankeyadvance{income}{2cm}
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
%
%^^A % ------------------------------------------------------------
% \subsection{Step 9: the complete diagram}
%^^A % ------------------------------------------------------------
%
% The complete diagram with its two sources of income, its styles and
% its labels:
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[ratio=2cm/100,
%     start style=simple,end style=arrow,
%     draw/.style={draw=none},
%     color/.style={fill/.style={fill=#1}}]
%     \sankeyset{minimum radius=15mm}
%     \sankeynode{name=income,quantity=100,
%       forked={80/salary-in,20/extra-in}}
%     \sankeynodestart[color=gray!60]{name=salary,quantity=80,
%       above left={1cm and 3.4cm of salary-in}}
%     \sankeynodestart[color=teal!40]{name=extra,quantity=20,
%       below left={.8cm and 3.4cm of extra-in}}
%     \sankeydubins[color=gray!60]{salary}{salary-in}
%     \sankeydubins[color=teal!40]{extra}{extra-in}
%     \sankeyadvance[color=gray!40]{income}{2cm}
%     \sankeyfork{income}{40/housing,25/food,20/other,15/savings}
%     \sankeynodeend[color=red!40]{name=housing-end,quantity=40,
%       above right={1cm and 4cm of housing}}
%     \sankeynodeend[color=orange!50]{name=food-end,quantity=25,
%       above right={.35cm and 4cm of food}}
%     \sankeynodeend[color=blue!30]{name=other-end,quantity=20,
%       below right={.3cm and 4cm of other}}
%     \sankeydubins[color=red!40]{housing}{housing-end}
%     \sankeydubins[color=orange!50]{food}{food-end}
%     \sankeydubins[color=blue!30]{other}{other-end}
%     \sankeyturnright[color=green!40,minimum radius=2mm]{savings}{90}
%     \sankeyadvance[color=green!40]{savings}{5mm}
%     \sankeyend[color=green!40]{savings}
%     \tikzset{every node/.style={font=\small\sffamily}}
%     \node[anchor=south west] at ([yshift=2pt]salary.left)
%     {Salary (\sankeygetnodeqty{salary})};
%     \node[anchor=north west] at ([yshift=-2pt]extra.right)
%     {Extra (\sankeygetnodeqty{extra})};
%     \node[anchor=south] at ($(income-old.left)!.5!(income.left)$)
%     {Income (\sankeygetnodeqty{income})};
%     \foreach \flow/\text in {housing/Housing,food/Food,other/Other}{
%       \node[anchor=west] at ([xshift=12pt]\flow-end.center)
%       {\text\ (\sankeygetnodeqty{\flow-end})};
%     }
%     \node[anchor=north] at ([yshift=-12pt]savings.center)
%     {Savings (\sankeygetnodeqty{savings})};
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
%
% The following sections describe all the options and macros. See also
% the examples (part \ref{examples}, page~\pageref{examples}).
%
% \clearpage
%
%^^A % ------------------------------------------------------------
% \section{Sankey diagram options}
%^^A % ------------------------------------------------------------
%
% The \code{sankey} package uses \code{pgfkeys} to set options via
% \emph{key=value} pairs with default path \code{/sankey} (and
% \code{/sankey/node parameters} for Sankey node parameters).
%
%
% Options can be defined in three ways:
%
% \begin{itemize}
% \item via the optional argument of the
%   \code{sankeydiagram} environment:
%   
% \begin{lstlisting}[style=LaTeXsmall]
% \begin{sankeydiagram}[debug=true]
%   \sankeynode{name=a,quantity=1,angle=0,at={(0,0)}}
% \end{sankeydiagram}
% \end{lstlisting}
% 
% \item \DescribeMacro{\sankeyset} %
% via the \code{\sankeyset} macro:
%   
% \begin{lstlisting}[style=LaTeXsmall]
% \begin{sankeydiagram}
%   \sankeyset{debug=true}
%   \sankeynode{name=a,quantity=1,angle=0,at={(0,0)}}
% \end{sankeydiagram}
% \end{lstlisting}
%   
% \item  temporarily modified for a single macro:
% \begin{lstlisting}[style=LaTeXsmall]
% \begin{sankeydiagram}
%   \sankeynode[debug=true]{name=a,quantity=1,angle=0,at={(0,0)}}
% \end{sankeydiagram}
% \end{lstlisting}
%   
% \end{itemize}
% 
% At the begining of each Sankey diagram, all options are initialized
% with initial values then the \code{every diagram} style is applied.
%
% \begin{sankeyoption}{every diagram}{}{}{empty}
%   This style is installed at beginning of each Sankey diagram.
% \end{sankeyoption}
%
% For instance, to use a ratio of 5mm/10 by default (instead of 1cm/10)
% for all Sankey diagrams, add the following line:
%
% \begin{lstlisting}[style=LaTeXsmall]
% \sankeyset{every diagram/.style={ratio=5mm/10}}
% \end{lstlisting}
%
%^^A % ------------------------------------------------------------
% \subsection{Keys to choose the scale}
%^^A % ------------------------------------------------------------
%
% The scale or ratio of the Sankey diagram is the ratio between the %
% \code{ratio length} and the \code{ratio quantity}.
%
% \begin{sankeyoption}{ratio quantity}{\VAR{number}}{}{10}
%   Quantity (in units of flow) to define ratio. The \VAR{number} can be
%   any math expression.
% \end{sankeyoption}
%
% \begin{sankeyoption}{ratio length}{\VAR{distance}}{}{1cm}
%   Distance (a graphical distance) to define scale.
% \end{sankeyoption}
%
% \begin{sankeyoption}{ratio}{\VAR{distance}/\VAR{number}}{}{1cm/10}
%   Fix the ratio to \VAR{distance}\texttt{/}\VAR{number}.
% \end{sankeyoption}
%
% The initial ratio is 1\,cm/10 units.
%
%
% \textbf{Note:} the \code{sankey} package uses the \code{xfp} package to
% evaluate all math expressions that use quantities (in units of
% flow). You can therefore use quantities of a very large or very small
% order of magnitude. In contrast, for graphic distances, the sankey
% package uses the \code{pgfmath} package (all calculations must not
% exceed $\pm 16383.99999$).
%
%^^A % ------------------------------------------------------------
% \subsection{Keys to define rotate offset}
%^^A % ------------------------------------------------------------
%
% \begin{sankeyoption}{rotate}{\VAR{angle} or \texttt{auto}}{}{auto}
%
%   The \code{rotate} key gives an offset angle applied to all Sankey
%   nodes. This is needed when using the \code{rotate} option within a
%   \code{tikzpicture} or a \code{scope}: this TikZ option is only
%   applied to coordinates and not to TikZ nodes (remember that Sankey
%   nodes are TikZ nodes).
%
%   With the \code{auto} value (the initial value), the offset angle is
%   the rotation of the current TikZ transformation: you don't have to
%   synchronize the \code{rotate} option of the \code{tikzpicture} and
%   that of the \code{sankeydiagram}. With an \VAR{angle}, this angle is
%   used instead (as in previous versions).
%   
% \end{sankeyoption}
%
%^^A % ------------------------------------------------------------
% \subsection{Keys to define drawing parameters}
%^^A % ------------------------------------------------------------
%
% \begin{sankeyoption}{minimum radius}{\VAR{distance}}{}{5mm}
%   The minimum radius used by \code{\sankeyturn} and
%   \code{\sankeydubins}.
% \end{sankeyoption}
%
% \begin{sankeyoption}{prefer}{\texttt{left}, \texttt{right} or \texttt{none}}{}{none}
%   The preferred side used by \code{\sankeydubins} to choose between
%   two shortest paths of the same length (see the \code{prefer} key of
%   the \code{dubins} library, \vref{sec:dubins}).
% \end{sankeyoption}
%
% \begin{sankeyoption}{outin steps}{\VAR{integer}}{}{10}
%   Number of steps used by the \code{\sankeyoutin} macro to simulate flow
%   lanes with constant width.
% \end{sankeyoption}
%
%^^A % ------------------------------------------------------------
% \subsection{Keys to choose drawing styles}
%^^A % ------------------------------------------------------------
%
% \begin{sankeyoption}{fill/.style}{\VAR{style}}{}{{line width=0pt,fill=white}}
%   This TikZ style is used to \emph{fill} all sankey paths.
% \end{sankeyoption}
%
% \begin{sankeyoption}{draw/.style}{\VAR{style}}{}{draw=black,line width=.4pt}
%   This TikZ style is used to \emph{draw} all sankey paths.
% \end{sankeyoption}
%
% \begin{sankeyoption}{start style}{\VAR{style name}}{}{none}
%   There are three predefined \emph{start} styles: \constant{none},
%   \constant{simple}, \constant{arrow}.
% \end{sankeyoption}
%
% \begin{sankeyoption}{end style}{\VAR{style name}}{}{none}
%   There are three predefined \emph{end} styles: \constant{none},
%   \constant{simple}, \constant{arrow}.
% \end{sankeyoption}
%
%^^A % ------------------------------------------------------------
% \subsection{Keys to define new \emph{start} and \emph{end} styles}
%^^A % ------------------------------------------------------------
%
% \begin{sankeyoption}{new start style}{\{\VAR{name}\}\{\VAR{fill
%       path}\}\{\VAR{draw path}\}}{}{}
%   Define the new start style named \VAR{name} with its \VAR{fill
%     path} and its \VAR{draw path}.
% \end{sankeyoption}
%
% \begin{sankeyoption}{new end style}{\{\VAR{name}\}\{\VAR{fill
%       path}\}\{\VAR{draw path}\}}{}{}
%   Define the new end style named \VAR{name} with its \VAR{fill
%     path} and its \VAR{draw path}.
% \end{sankeyoption}
%
% The \VAR{fill path} and the \VAR{draw path} are build in a TikZ scope
% where the origin is the center of the current Sankey node (its name is
% accessible via \code{\name}) and the coordinate system is rotated by
% its orientation.
%
%^^A % ------------------------------------------------------------
% \subsection{The \emph{debug} key}
%^^A % ------------------------------------------------------------
%
% \begin{sankeyoption}{debug}{\VAR{boolean}}{true}{false}
%   To debug a sankey diagram.
% \end{sankeyoption}
%
%^^A % ------------------------------------------------------------
% \section{Sankey nodes and flows}
%^^A % ------------------------------------------------------------
%
%^^A % ------------------------------------------------------------
% \subsection{Create Sankey nodes}
%^^A % ------------------------------------------------------------
%
%^^A % ------------------------------------------------------------
%
% \begin{miniblock}
% \DescribeMacro{\sankeynode} %
% \MACRO\code{\sankeynode}\OPTARG{\VAR{options}}\ARG{\VAR{node parameters}}
%
% The \code{\sankeynode} macro defines a Sankey node. The \VAR{options}
% can be any Sankey diagram keys. To define a Sankey node, you must
% provide a \emph{name}, a \emph{quantity} and an \emph{angle} as
% \VAR{node parameters}.
%
% \begin{sankeyoption}[/sankey/node parameters]{name}{\VAR{name}}{}{}
%   The \VAR{name} of the new Sankey node (and the associated TikZ node).
% \end{sankeyoption}
%
% \begin{sankeyoption}[/sankey/node parameters]{quantity}{\VAR{quantity}}{}{}
%   The quantity (in flow unit) of the new Sankey node. The \VAR{quantity}
%   can be any math expression.
% \end{sankeyoption}
%
% \begin{sankeyoption}[/sankey/node parameters]{angle}{\VAR{angle}}{}{}
%   The orientation of the flow (0 points to the right) of the new Sankey
%   node.
% \end{sankeyoption}
%
% \begin{sankeyoption}[/sankey/node parameters]{at}{(\VAR{coordinate})}{}{(0,0)}
%   The position of the new Sankey node: a TikZ coordinate \emph{with}
%   parentheses, as for the \code{at} key of TikZ nodes. For instance:
%
% \begin{lstlisting}[style=LaTeXsmall]
% \sankeynode{name=b,quantity=10,at=(a)}
% \sankeynode{name=c,quantity=10,at={(2,1)}}
% \sankeynode{name=d,quantity=10,at={($(a)+(1,2)$)}}
% \end{lstlisting}
%
%   For compatibility, a value without parentheses is processed as by
%   the \code{deprecated at} key, with a warning.
% \end{sankeyoption}
%
% \begin{sankeyoption}[/sankey/node parameters]{deprecated at}{\VAR{coordinate}}{}{}
%   The \code{at} key of previous versions: a TikZ coordinate
%   \emph{without} parentheses. \emph{This key is obsolete: use the
%   \code{at} key.} For instance:
%
% \begin{lstlisting}[style=LaTeXsmall]
% \sankeynode{name=c,quantity=10,deprecated at={2,1}}
% \end{lstlisting}
% \end{sankeyoption}
%
% \begin{sankeyoption}[/sankey/node parameters]{above}{\VAR{positioning}}{}{}
%   Places the new Sankey node with the syntax of the \code{positioning}
%   TikZ library (loaded by the \code{sankey} package), for instance
%   \code{above=1cm of a} or \code{above=of a}. The distances are always
%   measured between centers (as with the \code{on grid} option of the
%   \code{positioning} library). As with the \code{positioning} library,
%   the directions are those of the page: they do not follow the
%   \code{rotate} option of the picture.
%
%   The \code{below}, \code{left}, \code{right}, \code{above left},
%   \code{above right}, \code{below left} and \code{below right} keys
%   work the same way. For instance:
%
% \begin{lstlisting}[style=LaTeXsmall]
% \sankeynode{name=b,quantity=10,above right={1cm and 4cm of a}}
% \end{lstlisting}
% \end{sankeyoption}
%
% \begin{sankeyoption}[/sankey/node parameters]{anchor}{\VAR{anchor}}{}{center}
%   Specify the anchor of the Sankey node. Possible values are
%   \constant{center}, \constant{left} or \constant{right}.
% \end{sankeyoption}
%
% \begin{sankeyoption}[/sankey/node parameters]{as}{\VAR{name}}{}{}
%   Copy the \emph{name}, the \emph{quantity}, the \emph{angle} and the
%   \emph{position} of the Sankey node named \VAR{name}.
% \end{sankeyoption}
%
% A Sankey node is also a Tikz node but with only three anchors:
% \code{left}, \code{center} and \code{right}\footnote{In fact, to be
% able to use the TikZ \code{fit} library, the %
% \code{north}, \code{north east} and \code{north west} anchors exist
% and are equal to \code{left}, %
% the \code{east} and \code{west} anchors exist and are equal to
% \code{center} and %
% the \code{south}, \code{south east} and \code{south west} anchors
% exist and are equal to \code{right}.}:
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[debug]
%     \sankeynode{name=a,quantity=10}
%     \sankeynode{name=b,quantity=5,angle=45,at={(2,1)},anchor=left}
%     \sankeynode{name=c,quantity=20,angle=-90,at={(5,0)},anchor=right}
%     \foreach \nodename/\pos in {a/left,b/below left,c/above}{
%       \foreach \ancname in {left,center,right}{
%         \node[node font=\ttfamily\footnotesize,
%         \pos=1mm of \nodename.\ancname,inner sep=0pt,
%         rotate=\sankeygetnodeorient{\nodename},anchor=east]
%         {\ancname\vphantom{g}};
%         \fill[black] (\nodename.\ancname) circle(1pt);
%       }
%     }
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
%^^A % \clearpage
%
%^^A % ------------------------------------------------------------
% \subsubsection{Choose default parameters}
%^^A % ------------------------------------------------------------
%
% \begin{sankeyoption}{every node/.style}{\{\VAR{node parameters}\}}{}{empty}
%   The \VAR{node parameters} defined by the
%   \code{every node} style is installed at the creation of every Sankey node.
% \end{sankeyoption}
%
%^^A % ------------------------------------------------------------
% \subsubsection{Create starting and ending nodes via macros}
%^^A % ------------------------------------------------------------
%
% \begin{miniblock}
% \DescribeMacro{\sankeynodestart} %
% \MACRO\code{\sankeynodestart}\OPTARG{\VAR{options}}\ARG{\VAR{node parameters}}
%
% The \code{\sankeynodestart} creates and fills/draws a starting Sankey
% node:
%
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[start style=arrow,fill/.style={fill=orange!20}]
%     \sankeynodestart{name=a,quantity=10}
%     \sankeynodestart{name=b,quantity=5,angle=45,at={(2,1)},anchor=left}
%     \sankeynodestart{name=c,quantity=20,angle=-90,at={(5,1)},anchor=right}
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%^^A % ------------------------------------------------------------
%
%
% \begin{miniblock}
%   \DescribeMacro{\sankeynodeend} %
%   \MACRO\code{\sankeynodeend}\OPTARG{\VAR{options}}\ARG{\VAR{node
%   parameters}}
%   
%   The \code{\sankeynodeend} creates and fills/draws an ending Sankey
%   node:
%   
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[end style=simple,fill/.style={fill=orange!20}]
%     \sankeynodeend{name=a,quantity=10}
%     \sankeynodeend{name=b,quantity=5,angle=45,at={(2,1)},anchor=left}
%     \sankeynodeend{name=c,quantity=20,angle=-90,at={(5,1)},anchor=right}
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
%^^A % ------------------------------------------------------------
% \subsubsection{Create starting and ending nodes via options}
%^^A % ------------------------------------------------------------
%
% \begin{miniblock}
%   \begin{sankeyoption}[/sankey/node parameters]{start}{\VAR{boolean}}{true}{false}
%     The \code{\sankeynode} macro acts as the
%     \code{\sankeynodestart} macro if you add the
%     \code{start} option to its options.
%   \end{sankeyoption}
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[start style=arrow,fill/.style={fill=orange!20}]
%     \sankeynode{name=a,quantity=10,start}
%     \sankeynode{name=b,quantity=5,angle=45,at={(2,1)},anchor=left,start}
%     \sankeynode{name=c,quantity=20,angle=-90,at={(5,1)},anchor=right,start}
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
% \begin{miniblock}
%   \begin{sankeyoption}[/sankey/node parameters]{end}{\VAR{boolean}}{true}{false}
%     The \code{\sankeynode} macro acts as the \code{\sankeynodeend}
%     macro if you add the \code{end} option to its options.
%   \end{sankeyoption}
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[end style=simple,fill/.style={fill=orange!20}]
%     \sankeynode{name=a,quantity=10,end}
%     \sankeynode{name=b,quantity=5,angle=45,at={(2,1)},anchor=left,end}
%     \sankeynode{name=c,quantity=20,angle=-90,at={(5,1)},anchor=right,end}
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
%
% \begin{miniblock}
%   Although rarely necessary, you can mix these two parameters:
%
%   \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}
%     \sankeyset{
%       end style=arrow,
%       start style=arrow,
%       fill/.style={fill=orange!20}
%     }
%     \sankeynode{name=a,quantity=10,start,end}
%     \sankeynode{name=b,quantity=5,angle=45,at={(2,1)},anchor=left,
%       start,end}
%     \sankeynode{name=c,quantity=20,angle=-90,at={(5,1)},anchor=right,
%       start,end}
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% % 
% {\centering\input{\samplecodename}\par}
% % 
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
%
% \end{miniblock}
%
%^^A % ------------------------------------------------------------
% \subsection{Retrieve information from Sankey nodes}
%^^A % ------------------------------------------------------------
%
% \DescribeMacro{\sankeygetnodeqty} %
% \MACRO\code{\sankeygetnodeqty}\ARG{\VAR{node name}}
%
% The expandable command \code{\sankeygetnodeqty} returns the quantity
% assigned to the Sankey node named \VAR{node name}.
%
% \DescribeMacro{\sankeyqtytolen} %
% \MACRO\code{\sankeyqtytolen}\ARG{\VAR{quantity}}
%
% The expandable \code{\sankeyqtytolen} macro converts \VAR{quantity} to
% graphical length using the current ratio.
%
% \DescribeMacro{\sankeygetnodeorient} %
% \MACRO\code{\sankeygetnodeorient}\ARG{\VAR{node name}}
%
% The expandable command \code{\sankeygetnodeorient} returns the angle
% (orientation) assigned to the Sankey node named \VAR{node name}.
%
%^^A % ------------------------------------------------------------
% \subsection{Move nodes}
%^^A % ------------------------------------------------------------
%
% All the macros of this section move a Sankey node and fill/draw a
% portion of the Sankey flow. Then the previous position of the Sankey
% node is accessible via the \code{-old} suffix (i.e. if you move the
% \code{a} node, its previous position is the \code{a-old} node).
%
% The starred version of each of these macros moves in the opposite
% direction to their non-starred version.
%
% Except for the \code{\sankeyturn} macro, a negative value (distance or
% angle) moves in the opposite direction (the \code{\sankeyturn} macro
% is an exception: a negative angle turns right while a positive value
% turns left).
%
% {\centering
% \begin{tikzpicture}
%   \begin{sankeydiagram}
%     \tikzset{com/.style={node font=\ttfamily\scriptsize,
%     fill=bgcode,fill opacity=1,text opacity=1}}
%     \sankeyset{end style=simple,start style=simple}
%     \sankeynode{name=ac,quantity=5}
%     \sankeynode{name=al,quantity=5,above={2mm of ac.left},anchor=right}
%     \sankeynode{name=ar,quantity=5,below={2mm of ac.right},anchor=left}
%     \sankeyturnleft{al}{60}
%     \sankeyadvance{ac}{1cm}
%     \sankeyturnright{ar}{60}
%     \sankeyturnleft*{al-old}{60}
%     \sankeyadvance*{ac-old}{1cm}
%     \sankeyturnright*{ar-old}{60}
%     \sankeystart{al-old}
%     \sankeystart{ac-old}
%     \sankeystart{ar-old}
%     \sankeyend{al}
%     \sankeyend{ac}
%     \sankeyend{ar}
%     \draw[red,very thick]
%     (al-old-old.left) -- node[com]{n} (al-old-old.right) 
%     (ac-old-old.left) -- node[com]{n} (ac-old-old.right)
%     (ar-old-old.left) -- node[com]{n} (ar-old-old.right);
%     \path
%     (al) ++(2mm,2mm) node[com,anchor=south west,align=left] {
%       \string\sankeyturnleft\{n\}\{angle>0\}\\
%       \string\sankeyturnleftbackward\{n\}\{angle<0\}\\
%       \string\sankeyturnleft*\{n\}\{angle<0\}\\
%       \string\sankeyturnleftbackward*\{n\}\{angle>0\}\\
%       \string\sankeyturn\{n\}\{angle>0\}
%     };
%     \path
%     (al-old) ++(-2mm,2mm) node[com,anchor=south east,align=right] {
%       \string\sankeyturnleftbackward\{n\}\{angle>0\}\\
%       \string\sankeyturnleft\{n\}\{angle<0\}\\
%       \string\sankeyturnleft*\{n\}\{angle>0\}\\
%       \string\sankeyturnleftbackward*\{n\}\{angle<0\}\\
%       \string\sankeyturn*\{n\}\{angle>0\}
%     };
%     \path
%     (ac) ++(2mm,0) node[com,anchor=west,align=left] {
%       \string\sankeyadvance\{n\}\{distance>0\}\\
%       \string\sankeyadvance*\{n\}\{distance<0\}
%     };
%     \path
%     (ac-old) ++(-2mm,0) node[com,anchor=east,align=right] {
%       \string\sankeyadvance\{n\}\{distance<0\}\\
%       \string\sankeyadvance*\{n\}\{distance>0\}
%     };
%     \path
%     (ar) ++(2mm,-2mm) node[com,anchor=north west,align=left] {
%       \string\sankeyturnright\{n\}\{angle>0\}\\
%       \string\sankeyturnrightbackward\{n\}\{angle<0\}\\
%       \string\sankeyturnright*\{n\}\{angle<0\}\\
%       \string\sankeyturnrightbackward*\{n\}\{angle>0\}\\
%       \string\sankeyturn\{n\}\{angle<0\}
%     };
%     \path
%     (ar-old) ++(-2mm,-2mm) node[com,anchor=north east,align=right] {
%       \string\sankeyturnrightbackward\{n\}\{angle>0\}\\
%       \string\sankeyturnright\{n\}\{angle<0\}\\
%       \string\sankeyturnright*\{n\}\{angle>0\}\\
%       \string\sankeyturnrightbackward*\{n\}\{angle<0\}\\
%       \string\sankeyturn*\{n\}\{angle<0\}
%     };
%     \end{sankeydiagram}
%   \end{tikzpicture}
% \par}
%^^A % ------------------------------------------------------------
% \subsubsection{Macro to move straight (forward or backward)}
%^^A % ------------------------------------------------------------
%
%
% \begin{miniblock}
%   \DescribeMacro{\sankeyadvance} %
%   \MACRO\code{\sankeyadvance}\OPTARG{\VAR{options}}\ARG{\VAR{node
%   name}}\ARG{\VAR{distance}}
%   
%   The \code{\sankeyadvance} moves the sankey node straight ahead and
%   fills/draws this portion of the sankey path. A positive
%   \VAR{distance} moves forward while a negative \VAR{distance} moves
%   backward.
%   
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[start style=arrow,fill/.style={fill=orange!20}]
%     \sankeynodestart{name=a,quantity=10}
%     \sankeyadvance{a}{1cm}
%     \sankeynode[debug]{as=a}
%     \sankeynode[debug]{as=a-old}
%     \sankeynodestart{name=b,quantity=5,angle=45,at={(2,1)},anchor=left}
%     \sankeyadvance{b}{1cm}
%     \sankeynodestart{name=c,quantity=10,angle=-90,at={(5,1)},anchor=right}
%     \sankeyadvance{c}{5mm}
%     \fill[cyan] (0,0) circle(2pt) (2,1) circle(2pt) (5,1) circle(2pt);
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
% \begin{miniblock}
%   \MACRO\code{\sankeyadvance*}\OPTARG{\VAR{options}}\ARG{\VAR{node
%   name}}\ARG{\VAR{distance}}
%
%   The
%   \code{\sankeyadvance*} moves the sankey node straight back and fills/draws this portion of the sankey path. A positive \VAR{distance} moves backward while a negative \VAR{distance} moves forward.
%   
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[end style=arrow,fill/.style={fill=orange!20}]
%     \sankeynodeend{name=a,quantity=10}
%     \sankeyadvance*{a}{1cm}
%     \sankeynode[debug]{as=a}
%     \sankeynode[debug]{as=a-old}
%     \sankeynodeend{name=b,quantity=5,angle=45,at={(2,1)},anchor=left}
%     \sankeyadvance*{b}{1cm}
%     \sankeynodeend{name=c,quantity=10,angle=-90,at={(5,1)},anchor=right}
%     \sankeyadvance*{c}{5mm}
%     \fill[cyan] (0,0) circle(2pt) (2,1) circle(2pt) (5,1) circle(2pt);
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
%^^A % ------------------------------------------------------------
% \subsubsection{Macro to turn forward or backward}
%^^A % ------------------------------------------------------------
%
%\begin{miniblock}
%   \DescribeMacro{\sankeyturn} %
%   \MACRO\code{\sankeyturn}\OPTARG{\VAR{options}}\ARG{\VAR{node
%   name}}\ARG{\VAR{angle}}
%   
%   The \code{\sankeyturn} macro moves the
%   sankey node by turning to one side or the other and fills/draws
%   this portion of the sankey path. A \emph{positive} \VAR{angle}
%   turns left while a \emph{negative} \VAR{angle} turns right.
%   
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[start style=arrow,fill/.style={fill=orange!20}]
%     \sankeynodestart{name=a,quantity=10}
%     \sankeyturn{a}{90}
%     \sankeynode[debug]{as=a}
%     \sankeynode[debug]{as=a-old}
%     \sankeynodestart{name=b,quantity=5,angle=45,at={(2,1)},anchor=left}
%     \sankeyturn[minimum radius=1cm]{b}{-45}
%     \sankeynodestart{name=c,quantity=10,angle=-90,at={(5,1)},anchor=right}
%     \sankeyturn{c}{180}
%     \fill[cyan] (0,0) circle(2pt) (2,1) circle(2pt) (5,1) circle(2pt);
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
%
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
% \begin{miniblock}
%   \MACRO\code{\sankeyturn*}\OPTARG{\VAR{options}}\ARG{\VAR{node
%   name}}\ARG{\VAR{angle}}
%   
%   The \code{\sankeyturn*} macro moves the
%   sankey node backward by turning right or left and fills/draws this
%   portion of the sankey path. A \emph{positive} \VAR{angle} turns left
%   while a \emph{negative} \VAR{angle} turns right.
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[end style=simple,fill/.style={fill=orange!20}]
%     \sankeynodeend{name=a,quantity=10}
%     \sankeyturn*{a}{90}
%     \sankeynode[debug]{as=a}
%     \sankeynode[debug]{as=a-old}
%     \sankeynodeend{name=b,quantity=5,angle=45,at={(2,1)},anchor=left}
%     \sankeyturn*[minimum radius=1cm]{b}{-45}
%     \sankeynodeend{name=c,quantity=10,angle=-90,at={(3,1)},anchor=right}
%     \sankeyturn*{c}{180}
%     \fill[cyan] (0,0) circle(2pt) (2,1) circle(2pt) (3,1) circle(2pt);
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
%^^A % ------------------------------------------------------------
% \subsubsection{Macros to turn left (forward or backward)}
%^^A % ------------------------------------------------------------
%
% \begin{miniblock}
%   \DescribeMacro{\sankeyturnleft} %
%   \MACRO\code{\sankeyturnleft}\OPTARG{\VAR{options}}\ARG{\VAR{node
%   name}}\ARG{\VAR{angle}}
%   
%   The \code{\sankeyturnleft} macro moves the sankey node by turning
%   left and fills/draws this portion of the sankey path. A
%   \emph{positive} \VAR{angle} turns forward while a \emph{negative}
%   \VAR{angle} turns backward.
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[start style=arrow,end style=arrow]
%     \sankeyset{fill/.style={fill=orange!20}}
%     \sankeynodestart{name=a,quantity=10}
%     \sankeyturnleft{a}{90}
%     \sankeynode[debug]{as=a}
%     \sankeynode[debug]{as=a-old}
%     \sankeyset{fill/.style={fill=lime!20}}
%     \sankeynodeend{name=b,quantity=5,angle=-135,at={(1,2)},anchor=left}
%     \sankeyturnleft[minimum radius=1cm]{b}{-225}
%     \fill[cyan] (0,0) circle(2pt) (1,2) circle(2pt);
% \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
%
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
% \begin{miniblock}
%   \MACRO\code{\sankeyturnleft*}\OPTARG{\VAR{options}}\ARG{\VAR{node
%   name}}\ARG{\VAR{angle}}
%   
%   The
%   \code{\sankeyturnleft*} macro moves the sankey node backward
%   by turning left and fills/draws this portion of the sankey path.
%   A \emph{positive} \VAR{angle} turns backward while a
%   \emph{negative} \VAR{angle} turns forward.
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[start style=arrow,end style=arrow]
%     \sankeyset{fill/.style={fill=orange!20}}
%     \sankeynodeend{name=a,quantity=10}
%     \sankeyturnleft*{a}{90}
%     \sankeynode[debug]{as=a}
%     \sankeynode[debug]{as=a-old}
%     \sankeyset{fill/.style={fill=lime!20}}
%     \sankeynodestart{name=b,quantity=5,angle=-135,at={(1,2)},anchor=left}
%     \sankeyturnleft*[minimum radius=.75cm]{b}{-225}
%     \fill[cyan] (0,0) circle(2pt) (1,2) circle(2pt);
% \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
%
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
% \begin{miniblock}
%   \DescribeMacro{\sankeyturnleftbackward} %
%   \MACRO\code{\sankeyturnleftbackward}\OPTARG{\VAR{options}}\ARG{\VAR{node
%   name}}\ARG{\VAR{angle}}
%   
%   The \code{\sankeyturnleftbackward} macro moves the sankey node
%   backward by turning left and fills/draws this portion of the sankey
%   path.  A \emph{positive} \VAR{angle} turns backward while a
%   \emph{negative} \VAR{angle} turns forward.
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[start style=arrow,end style=arrow]
%     \sankeyset{fill/.style={fill=orange!20}}
%     \sankeynodeend{name=a,quantity=10}
%     \sankeyturnleftbackward{a}{90}
%     \sankeynode[debug]{as=a}
%     \sankeynode[debug]{as=a-old}
%     \sankeyset{fill/.style={fill=lime!20}}
%     \sankeynodestart{name=b,quantity=5,angle=-135,at={(1,2)},anchor=left}
%     \sankeyturnleftbackward[minimum radius=.75cm]{b}{-225}
%     \fill[cyan] (0,0) circle(2pt) (1,2) circle(2pt);
% \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
%
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
% \begin{miniblock}
%   \MACRO\code{\sankeyturnleftbackward*}\OPTARG{\VAR{options}}\ARG{\VAR{node
%   name}}\ARG{\VAR{angle}}
%   
%   The
%   \code{\sankeyturnleftbackward*} macro moves the sankey node by turning left
%   and fills/draws this portion of the sankey path. A \emph{positive}
%   \VAR{angle} turns forward while a \emph{negative} \VAR{angle} turns backward.
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[start style=arrow,end style=arrow]
%     \sankeyset{fill/.style={fill=orange!20}}
%     \sankeynodestart{name=a,quantity=10}
%     \sankeyturnleftbackward*{a}{90}
%     \sankeynode[debug]{as=a}
%     \sankeynode[debug]{as=a-old}
%     \sankeyset{fill/.style={fill=lime!20}}
%     \sankeynodeend{name=b,quantity=5,angle=-135,at={(1,2)},anchor=left}
%     \sankeyturnleftbackward*[minimum radius=1cm]{b}{-225}
%     \fill[cyan] (0,0) circle(2pt) (1,2) circle(2pt);
% \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
%
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
% 
%^^A % ------------------------------------------------------------
% \subsubsection{Macros to turn right (forward or backward)}
%^^A % ------------------------------------------------------------
%
% \begin{miniblock}
%   \DescribeMacro{\sankeyturnright} %
%   \MACRO\code{\sankeyturnright}\OPTARG{\VAR{options}}\ARG{\VAR{node
%   name}}\ARG{\VAR{angle}}
%   
%   The \code{\sankeyturnright} macro moves the sankey node by turning
%   right and fills/draws this portion of the sankey path. A
%   \emph{positive} \VAR{angle} turns forward while a \emph{negative}
%   \VAR{angle} turns backward.
%   
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[start style=arrow,end style=arrow]
%     \sankeyset{fill/.style={fill=orange!20}}
%     \sankeynodestart{name=a,quantity=10}
%     \sankeyturnright[fill/.style={fill=orange!20}]{a}{90}
%     \sankeynode[debug]{as=a}
%     \sankeynode[debug]{as=a-old}
%     \sankeyset{fill/.style={fill=lime!20}}
%     \sankeynodeend{name=b,quantity=5,angle=45,at={(2,1)},anchor=left}
%     \sankeyturnright[minimum radius=.75cm]{b}{-225}
%     \fill[cyan] (0,0) circle(2pt) (2,1) circle(2pt);
% \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
%
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
% \begin{miniblock}
%   \MACRO\code{\sankeyturnright*}\OPTARG{\VAR{options}}\ARG{\VAR{node
%   name}}\ARG{\VAR{angle}}
%   
%   The \code{\sankeyturnright*} macro
%   moves the sankey node backward by turning right and fills/draws
%   this portion of the sankey path. A \emph{positive} \VAR{angle} turns
%   backward while a \emph{negative} \VAR{angle} turns forward.
%   
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[start style=arrow,end style=arrow]
%     \sankeyset{fill/.style={fill=orange!20}}
%     \sankeynodeend{name=a,quantity=10}
%     \sankeyturnright*[fill/.style={fill=orange!20}]{a}{90}
%     \sankeynode[debug]{as=a}
%     \sankeynode[debug]{as=a-old}
%     \sankeyset{fill/.style={fill=lime!20}}
%     \sankeynodestart{name=b,quantity=5,angle=45,at={(1,1)},anchor=left}
%     \sankeyturnright*[minimum radius=.75cm]{b}{-225}
%     \fill[cyan] (0,0) circle(2pt) (1,1) circle(2pt);
% \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
%
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
% \begin{miniblock}
%   \DescribeMacro{\sankeyturnrightbackward} %
%   \MACRO\code{\sankeyturnrightbackward}\OPTARG{\VAR{options}}\ARG{\VAR{node
%   name}}\ARG{\VAR{angle}}
%   
%   The \code{\sankeyturnrightbackward} macro
%   moves the sankey node backward by turning right and fills/draws
%   this portion of the sankey path. A \emph{positive} \VAR{angle} turns
%   backward while a \emph{negative} \VAR{angle} turns forward.
%   
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[start style=arrow,end style=arrow]
%     \sankeyset{fill/.style={fill=orange!20}}
%     \sankeynodeend{name=a,quantity=10}
%     \sankeyturnrightbackward[fill/.style={fill=orange!20}]{a}{90}
%     \sankeynode[debug]{as=a}
%     \sankeynode[debug]{as=a-old}
%     \sankeyset{fill/.style={fill=lime!20}}
%     \sankeynodestart{name=b,quantity=5,angle=45,at={(1,1)},anchor=left}
%     \sankeyturnrightbackward[minimum radius=.75cm]{b}{-225}
%     \fill[cyan] (0,0) circle(2pt) (1,1) circle(2pt);
% \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
%
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
% \begin{miniblock}
%   \MACRO\code{\sankeyturnrightbackward*}\OPTARG{\VAR{options}}\ARG{\VAR{node
%   name}}\ARG{\VAR{angle}}
%   
%   The
%   \code{\sankeyturnrightbackward*} macro  moves the sankey
%   node forward by turning right and fills/draws this portion
%   of the sankey path. A \emph{positive} \VAR{angle} turns forward
%   while a \emph{negative} \VAR{angle} turns backward.
%   
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[start style=arrow,end style=arrow]
%     \sankeyset{fill/.style={fill=orange!20}}
%     \sankeynodestart{name=a,quantity=10}
%     \sankeyturnrightbackward*[fill/.style={fill=orange!20}]{a}{90}
%     \sankeynode[debug]{as=a}
%     \sankeynode[debug]{as=a-old}
%     \sankeyset{fill/.style={fill=lime!20}}
%     \sankeynodeend{name=b,quantity=5,angle=45,at={(2,1)},anchor=left}
%     \sankeyturnrightbackward*[minimum radius=.75cm]{b}{-225}
%     \fill[cyan] (0,0) circle(2pt) (2,1) circle(2pt);
% \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
%
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
%
%^^A % ------------------------------------------------------------
% \subsection{Links between nodes}
%^^A % ------------------------------------------------------------
%
% The macros described in this section fill/draw a lane between two
% Sankey nodes.
%
% Note: since Sankey nodes are oriented, linking \code{A} node to
% \code{B} node does not produce the same result as linking \code{B}
% node to \code{A} node!
%
% \begin{miniblock}
%   \DescribeMacro{\sankeyoutin} %
%   \MACRO\code{\sankeyoutin}\OPTARG{\VAR{options}}\ARG{\VAR{node
%   A}}\ARG{\VAR{node B}}
%   
%   The \code{\sankeyoutin} macro
%   fills/draws a lane from \VAR{node A} to \VAR{node B} using a
%   Bézier curve with regular steps (10 steps by default) to
%   simulate constant width lane.
%   
%   \textbf{Note:} The constant width and the minimum curvature are
%   \emph{not} guaranteed!
% \end{miniblock}
%
% \begin{miniblock}
%   \DescribeMacro{\sankeydubins} %
%   \MACRO\code{\sankeydubins}\OPTARG{\VAR{options}}\ARG{\VAR{node
%   A}}\ARG{\VAR{node B}}
%   
%   The \code{\sankeydubins} macro fills/draws a lane between
%   \VAR{node A} and \VAR{node B} using a Dubins
%   path\footnote{\url{https://en.wikipedia.org/wiki/Dubins_path}}
%   (see \vref{sec:dubins}).
%
%   \textbf{Note:} The constant width and the minimum curvature are
%   guaranteed.
% \end{miniblock}
%
% \clearpage
%
%^^A % ------------------------------------------------------------
% \subsubsection{Comparison between \ttintitle{outin} and \ttintitle{dubins}
%   paths}
%^^A % ------------------------------------------------------------
%
% The following diagrams compare \texttt{outin} path with
% 10 steps (orange), \texttt{outin} path with 2 steps (red)
% and \texttt{dubins} path (lime) in various positions.
%
% \begin{miniblock}
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[start style=simple,end style=arrow]
%     \sankeyset{fill/.style={fill=orange!20}}
%     \sankeynodestart{name=a,quantity=5}
%     \sankeynodeend{name=b,at={(4,3)},quantity=5}
%     \sankeyoutin{a}{b}
%
%     \sankeyset{fill/.style={fill=red!20}}
%     \sankeynodestart{name=a,at={(2,0)},quantity=5}
%     \sankeynodeend{name=b,at={(6,3)},quantity=5}
%     \sankeyoutin[outin steps=2]{a}{b}
%
%     \sankeyset{fill/.style={fill=lime!40}}
%     \sankeynodestart{name=a,at={(4,0)},quantity=5}
%     \sankeynodeend{name=b,at={(8,3)},quantity=5}
%     \sankeydubins[minimum radius=5mm]{a}{b}
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
% \begin{miniblock}
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[start style=simple,end style=arrow]
%     \sankeyset{fill/.style={fill=orange!20}}
%     \sankeynodestart{name=a,quantity=5}
%     \sankeynodeend{name=b,at={(2,3)},quantity=5}
%     \sankeyoutin{a}{b}
%
%     \sankeyset{fill/.style={fill=red!20}}
%     \sankeynodestart{name=a,at={(2,0)},quantity=5}
%     \sankeynodeend{name=b,at={(4,3)},quantity=5}
%     \sankeyoutin[outin steps=2]{a}{b}
%
%     \sankeyset{fill/.style={fill=lime!40}}
%     \sankeynodestart{name=a,at={(4,0)},quantity=5}
%     \sankeynodeend{name=b,at={(6,3)},quantity=5}
%     \sankeydubins[minimum radius=5mm]{a}{b}
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
% \begin{miniblock}
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[start style=simple,end style=arrow]
%     \sankeyset{fill/.style={fill=orange!20}}
%     \sankeynodestart{name=a,quantity=5}
%     \sankeynodeend{name=b,at={(0,3)},quantity=5}
%     \sankeyoutin{a}{b}
%
%     \sankeyset{fill/.style={fill=red!20}}
%     \sankeynodestart{name=a,at={(2,0)},quantity=5}
%     \sankeynodeend{name=b,at={(2,3)},quantity=5}
%     \sankeyoutin[outin steps=2]{a}{b}
%
%     \sankeyset{fill/.style={fill=lime!40}}
%     \sankeynodestart{name=a,at={(4,0)},quantity=5}
%     \sankeynodeend{name=b,at={(4,3)},quantity=5}
%     \sankeydubins[minimum radius=5mm]{a}{b}
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
%^^A % ------------------------------------------------------------
% \subsubsection{Examples of \ttintitle{dubins} paths}
%^^A % ------------------------------------------------------------
%
% \begin{miniblock}
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}[start style=simple,end style=arrow]
%     \sankeyset{
%       fill/.style={fill=lime!40},
%       draw/.style={draw=green!50!black,line width=2pt},
%     }
%
%     \sankeynodestart{name=a,quantity=5}
%     \sankeynodeend{name=b,at={(0,2)},quantity=5}
%     \sankeydubins[minimum radius=2mm]{a}{b}
%
%     \fill[green!50!black] (2,0) coordinate (c) circle(2pt);
%     \sankeynodestart{name=a,at={([shift={(c)}]90:5mm)},quantity=5}
%     \sankeynodeend{name=b,at={([shift={(c)}]150:5mm)},angle=60,quantity=5}
%     \sankeydubins[minimum radius=2.5mm]{a}{b}
%
%     \sankeynodestart{name=a,at={(3.5,0)},quantity=5}
%     \sankeynodeend{name=b,at={(3.5,.75)},angle=-180,quantity=5}
%     \sankeydubins[minimum radius=5mm]{a}{b}
%
%     \sankeynodestart{name=a,at={(7,1)},quantity=5}
%     \sankeynodeend{name=b,at={(7,1.75)},quantity=5}
%     \sankeydubins[minimum radius=2.5mm]{a}{b}
%
%     \sankeynodestart{name=a,at={(9,0)},quantity=5}
%     \sankeynodeend{name=b,at={(9,2)},angle=180,quantity=5}
%     \sankeydubins[minimum radius=2.5mm]{a}{b}
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
%^^A % ------------------------------------------------------------
% \subsection{Pure filling/drawing macros}
%^^A % ------------------------------------------------------------
%
% \begin{miniblock}
%   \DescribeMacro{\sankeystart} %
%   \MACRO\code{\sankeystart}\OPTARG{\VAR{options}}\ARG{\VAR{name}}
%   
%   The \code{\sankeystart} fills/draws a starting extremity attached to
%   the preexisting Sankey node \VAR{name}:
%   
%   
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}
%     [start style=arrow,fill/.style={fill=cyan!20},draw/.style={draw=blue}]
%     \sankeynode{name=a,quantity=10}
%     \sankeystart{a}
%     \sankeynode{name=b,quantity=5,angle=45,at={(2,1)},anchor=left}
%     \sankeystart{b}
%     \sankeynode{name=c,quantity=20,angle=-90,at={(5,1)},anchor=right}
%     \sankeystart{c}
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%^^A % ------------------------------------------------------------
%
%
% \begin{miniblock}
%   \DescribeMacro{\sankeyend} %
%   \MACRO\code{\sankeyend}\OPTARG{\VAR{options}}\ARG{\VAR{name}}
%
%   The \code{\sankeyend} fills/draws an ending extremity attached to
%   the preexisting Sankey node \VAR{name}:
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}
%     [end style=simple,fill/.style={fill=cyan!20},draw/.style={draw=blue}]
%     \sankeynode{name=a,quantity=10}
%     \sankeyend{a}
%     \sankeynode{name=b,quantity=5,angle=45,at={(2,1)},anchor=left}
%     \sankeyend{b}
%     \sankeynode{name=c,quantity=20,angle=-90,at={(5,1)},anchor=right}
%     \sankeyend{c}
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% % 
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% % 
% {\centering\input{\samplecodename}\par}
% \end{miniblock}
%
%^^A % ------------------------------------------------------------
% \subsection{Forked node}
%^^A % ------------------------------------------------------------
%
%^^A % ------------------------------------------------------------
% \subsubsection{Create and fork a Sankey node}
%^^A % ------------------------------------------------------------
%
% \changes{v3.0}{2021/03/14}{Add keys to fork a Sankey node during its
% creation}
%
% \begin{miniblock}
%   When creating a new Sankey node, the \code{forked} and %
%   \code{fork anchor} keys allow to fork the node directly \emph{and} to
%   anchor it on an anchor of a forked subnode.
%
% \begin{sankeyoption}[/sankey/node parameters]{forked}{\{\VAR{quantity/name pairs}\}}{}{}
%   The \VAR{quantity/name pairs} is a comma separated list of
%   \emph{quantity/name} pairs (one for each subnode, from left to
%   right). The sum of all quantities \emph{must} be equal to the quantity
%   of the new node to fork.
% \end{sankeyoption}
%
% \begin{sankeyoption}[/sankey/node parameters]{fork anchor}{\VAR{node.anchor}}{}{}
%   An anchor belonging to the new node \emph{or} belonging to a subnode
%   (the anchor name must be prefixed by the name of the
%   node). \emph{Note:} when a \code{fork anchor} key is supplied, the
%   \code{anchor} key is ignored (with a \emph{warning} message).
% \end{sankeyoption}
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}
%     \sankeyset{
%       start style=arrow,end style=arrow,
%       fill/.style={fill=yellow!10,line width=0pt,draw=yellow!10}
%     }
%
%     \sankeynode[debug]{
%       name=a,quantity=40,angle=-80,
%       forked={25/b,10/c,5/d},
%       fork anchor=c.right,
%     }
%
%     \sankeyadvance*{b}{1cm}
%     \sankeyturn*[minimum radius=2cm]{c}{-30}
%     \sankeyturn*[minimum radius=2cm]{c}{30}
%     \sankeyturn*[minimum radius=5mm]{d}{-90}
%     \sankeyadvance{a}{1.5cm}
%     \foreach \nodename in {b,c,d}{ \sankeystart{\nodename} }
%     \sankeyend{a}
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% % 
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
%
%^^A % ------------------------------------------------------------
% \subsubsection{Fork a Sankey node}
%^^A % ------------------------------------------------------------
% \begin{miniblock}
%   \DescribeMacro{\sankeyfork} %
%   \MACRO\code{\sankeyfork}\OPTARG{\VAR{options}}\ARG{\VAR{name}}\ARG{\VAR{quantity/name pairs}}
%
%   The \code{\sankeyfork} macro splits the preexisting Sankey node
%   named \VAR{name} in a list of new Sankey subnodes. The
%   \VAR{quantity/name pairs} is a comma separated list of
%   \emph{quantity/name} pairs, one for each subnode from left to
%   right. The sum of all quantities \emph{must} be equal to the
%   quantity of the node to fork.
%
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \begin{sankeydiagram}
%     \sankeynode{name=a,quantity=40,angle=-45}
%     \sankeyfork[debug]{a}{25/b,10/c,5/d}
%     \path (a.left) rectangle (a.right); %^^A create a bounding box
%   \end{sankeydiagram}
% \end{tikzpicture}
% \end{VerbatimOut}
% % 
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
%^^A % ------------------------------------------------------------
% \section{Miscellaneous}
%^^A % ------------------------------------------------------------
%
%^^A % ------------------------------------------------------------
% \subsection{The \ttintitle{debug} layer}
%^^A % ------------------------------------------------------------
%
% The options \code{debug} key uses the \code{sankeydebug} layer to draw
% above the \code{main} TikZ layer. If no layer has been defined before
% loading the \code{sankey} package, it installs (via
% \code{\pgfsetlayers}) four layers: \code{background}, \code{main},
% \code{foreground}, \code{sankeydebug}. Otherwise, it keeps the layers
% already defined and appends the \code{sankeydebug} layer to them. If
% you define your own layers \emph{after} loading the \code{sankey}
% package, add the \code{sankeydebug} layer at the end of your list
% (otherwise, the debug information is drawn on the current layer).
%
% The four following styles define how to display debug information:
%
% \begin{lstlisting}[style=LaTeXsmall]
% \sankeyset{
%   debug color/.style={/utils/exec={\colorlet{debug color}{#1}}},
%   % debug color used by all debug macros
%   debug color=red!75!black,
%   % debug line between left and right anchors
%   debug line/.style={overlay,draw=debug color,|-|},
%   % debug line between center and label
%   debug normal/.style={overlay,draw=debug color},
%   % debug node label
%   debug label/.style={
%     overlay,
%     draw,
%     font=\ttfamily\tiny,
%     text=debug color,text opacity=1,
%     inner sep=.1em,
%     fill=white,fill opacity=1,
%     rounded corners=.1em,
%     node contents={\name},
%   },
% }
% \end{lstlisting}
%
%^^A % ------------------------------------------------------------
% \subsection{How to duplicate a Sankey node}
%^^A % ------------------------------------------------------------
%
% \DescribeMacro{\sankeynodealias} %
% \MACRO\code{\sankeynodealias}\ARG{\VAR{origname}}\ARG{\VAR{clonename}}
%
% The \code{\sankeynodealias} macro clones the Sankey node named
% \VAR{origname} into the Sankey node named \VAR{clonename}.
%
% So, you can clone a Sankey node via two methods:
%
% \begin{lstlisting}[style=LaTeXsmall]
% \sankeynode{name=a,quantity=10}
% \sankeynode{as=a,name=b}
% \end{lstlisting}
%
% \begin{lstlisting}[style=LaTeXsmall]
% \sankeynode{name=a,quantity=10}
% \sankeynodealias{a}{b}
% \end{lstlisting}
%
%^^A % ------------------------------------------------------------
% \subsection{How to define new start and end styles}
%^^A % ------------------------------------------------------------
%
% Here are the definitions of the \code{arrow} styles:
%
% \begin{lstlisting}[style=LaTeXsmall]
% \sankeyset{
%   %% arrow style
%   new start style={arrow}{
%     (\name.left) -- ++(-10pt,0)
%     -- ([xshift=-10pt/6]\name.center)
%     -- ([xshift=-10pt]\name.right)
%     -- (\name.right) -- cycle
%   }{
%     (\name.left) -- ++(-10pt,0)
%     -- ([xshift=-10pt/6]\name.center)
%     -- ([xshift=-10pt]\name.right)
%     -- (\name.right)
%   },
%   new end style={arrow}{
%     (\name.left) -- ([yshift=1mm]\name.left)
%     -- ([xshift=10pt]\name.center)
%     -- ([yshift=-1mm]\name.right) -- (\name.right) -- cycle
%   }{
%     (\name.left) -- ([yshift=1mm]\name.left)
%     -- ([xshift=10pt]\name.center)
%     -- ([yshift=-1mm]\name.right) -- (\name.right)
%   },
% }
% \end{lstlisting}
%
%^^A % ------------------------------------------------------------
% \subsection{History: changes since version 3.0.2}
% \label{sec:history}
%^^A % ------------------------------------------------------------
%
% Version 3.1.0 is compatible with the diagrams of version 3.0.2, with
% the few exceptions noted below. The complete list of changes is at the
% end of this document.
%
% \begin{itemize}
% \item \emph{Placing nodes.} The \code{at} key now expects a TikZ
%   coordinate \emph{with} parentheses, as in TikZ (for instance
%   \code|at={(2,1)}|). The old syntax (without parentheses) still
%   works, with a warning; it is also available as \code{deprecated at}.
%   New keys \code{above}, \code{below}, \code{left}, \code{right},
%   \code{above left}\dots{} place a node relative to another one with
%   the syntax of the \code{positioning} TikZ library (loaded by the
%   package).
% \item \emph{Rotation.} The initial value of the \code{rotate} key is
%   now \code{auto}: the rotation of the current TikZ transformation is
%   read automatically. Giving an explicit angle works as before.
% \item \emph{Layers.} The PGF layers already defined by the user are
%   kept (the \code{sankeydebug} layer is added to them).
% \item \emph{Links.} New \code{prefer} key, to choose between two
%   shortest paths of the same length (\code{\sankeydubins} and
%   \code{dubins} library).
% \item \emph{Fixes.} Forked nodes with non-integer quantities; name of
%   the \code{outin steps} key; length of the straight segment of the
%   \code{rsl} and \code{lsr} Dubins paths (a different path may now
%   be chosen in rare cases).
% \item \emph{The \code{dubins} library} is now documented
%   (section~\ref{sec:dubins}). Changes: new \code{\dubinspathget}
%   macro; \code{\dubinspath} computes the path itself when no method is
%   given; the \code{reverse} key and the method only apply to the
%   current \code{\dubinspath}; explicit errors for unknown methods or
%   stores, missing keys and non-positive radii; null path when start
%   and end are the same.
% \item \emph{Requirements and documentation.} A \LaTeX{} format from
%   2020/10/01 or later is required. New tutorial and two new examples
%   (paper and board cycle, urban water cycle).
% \end{itemize}
%
%^^A % ------------------------------------------------------------
% \section{The \ttintitle{dubins} TikZ library}
% \label{sec:dubins}
%^^A % ------------------------------------------------------------
%
% \changes{v3.1.0}{2026/11/29}{Document the \protect\code{dubins} TikZ library}
%
% The \code{sankey} package uses the \code{dubins} TikZ library to
% compute and draw the Dubins paths used by \code{\sankeydubins}. This
% library is defined in the
% \code{tikzlibrarydubins}\allowbreak\code{.code.tex} file. It may also be used on
% its own (with \LaTeX{} only, since it loads the \code{etoolbox} and
% \code{xfp} packages):
%
% \begin{lstlisting}[style=LaTeXsmall]
% \usetikzlibrary{dubins}
% \end{lstlisting}
%
%^^A % ------------------------------------------------------------
% \subsection{What is a Dubins path?}
%^^A % ------------------------------------------------------------
%
% Given a start point with a start direction, an end point with an end
% direction and a minimum radius of curvature $r$, a Dubins
% path\footnote{\url{https://en.wikipedia.org/wiki/Dubins_path}} is the
% shortest curve joining the two points, tangent to the two directions,
% whose radius of curvature is never less than $r$.
%
% L.~E.~Dubins (1957) proved that such a path is always made of (at most)
% three parts, each one being either an arc of radius $r$ or a straight
% segment. Using \code{L} for a left turn, \code{R} for a right turn and
% \code{S} for a straight segment, there are only six candidates:
% \begin{itemize}
% \item four \emph{CSC} paths: \code{rsr}, \code{lsl}, \code{rsl} and
%   \code{lsr};
% \item two \emph{CCC} paths: \code{rlr} and \code{lrl}.
% \end{itemize}
% Some candidates do not always exist: \code{rsl} and \code{lsr} require
% that the centers of the two circles are at least $2r$ apart,
% \code{rlr} and \code{lrl} require that they are at most $4r$ apart.
% The \code{dubins} library computes the length of each existing
% candidate and keeps the shortest one.
%
%^^A % ------------------------------------------------------------
% \subsection{Macros}
%^^A % ------------------------------------------------------------
%
% The simplest way is to give all the parameters of the path to
% \code{\dubinspath}: it computes then draws the path. You may also use a
% two-step process: first compute the path (\code{\dubinspathcalc}),
% then draw it (\code{\dubinspath}). This is useful to draw the same path
% several times, to draw parallel paths (see
% \vref{sec:dubins-parallel}) or to retrieve the parameters of the path
% (\code{\dubinspathget}).
%
% \begin{miniblock}
%   \DescribeMacro{\dubinspathset} %
%   \MACRO\code{\dubinspathset}\ARG{\VAR{options}}
%
%   The \code{\dubinspathset} macro processes \VAR{options} with
%   \texttt{/tikz/dubins path} as default path. It is useful to define a
%   style that groups all the parameters of a path (see examples below).
% \end{miniblock}
%
% \begin{miniblock}
%   \DescribeMacro{\dubinspathcalc} %
%   \MACRO\code{\dubinspathcalc}\ARG{\VAR{options}}
%
%   The \code{\dubinspathcalc} macro computes the shortest Dubins path
%   defined by the \code{start point}, \code{start angle},
%   \code{end point}, \code{end angle} and \code{minimum radius} keys.
%   It may be used anywhere (with node names as points, it must be used
%   inside the \code{tikzpicture} environment that contains these nodes)
%   but not inside a path.
%
%   The \code{minimum radius} must be positive. If the start and end
%   points and directions are the same, the result is a null path.
%
%   The computation is done within a group: to use its result, you
%   must give a name via the \code{store} key. The result (the chosen
%   method and its parameters) is then stored \emph{globally} under this
%   name and retrieved later via the \code{use store} key.
% \end{miniblock}
%
% \begin{miniblock}
%   \DescribeMacro{\dubinspathget} %
%   \MACRO\code{\dubinspathget}\ARG{\VAR{store name}}\ARG{\VAR{param}}
%
%   The expandable \code{\dubinspathget} macro gives a parameter of the
%   result stored under \VAR{store name}: \code{method}, \code{length}
%   (in points, without unit), \code{first angle}, \code{middle param}
%   or \code{last angle}. For instance:
%
% \begin{lstlisting}[style=LaTeXsmall]
% \dubinspathcalc{start point={0,0},start angle=0,
%   end point={2,1},end angle=90,minimum radius=5mm,store=p}
% Method: \dubinspathget{p}{method},
% length: \dubinspathget{p}{length}\,pt.
% \end{lstlisting}
% \end{miniblock}
%
% \begin{miniblock}
%   \DescribeMacro{\dubinspath} %
%   \MACRO\code{\dubinspath}\ARG{\VAR{options}}
%
%   The \code{\dubinspath} macro is a \emph{path operation}: it must be
%   used inside a path, just after a point. It extends the current path
%   from the current point using the method and the parameters given by
%   \VAR{options} (usually via the \code{use store} key).
%
%   If no method is given (neither \code{method} nor \code{use store}
%   key), \code{\dubinspath} computes the path itself (as
%   \code{\dubinspathcalc} does): the \code{start point},
%   \code{start angle}, \code{end point}, \code{end angle} and
%   \code{minimum radius} keys are then required. The method (and so the
%   \code{use store} key) must be given at each call of \code{\dubinspath}.
%
%   An error is raised if the method is unknown, if the store does not
%   exist or if a required key is missing.
%
%   The current point is \emph{not} replaced by the \code{start point}:
%   the path starts where you are. Only the \code{end point}, the
%   \code{start angle}, the \code{end angle} and the radii are used to
%   locate the arcs and the straight segment.
% \end{miniblock}
%
%^^A % ------------------------------------------------------------
% \subsection{Keys}
%^^A % ------------------------------------------------------------
%
% \begin{sankeyoption}[/tikz/dubins path]{start point}{\VAR{coordinate}}{}{}
%   The start point (any TikZ coordinate without parentheses: \code{A},
%   \code{A.center}, \code{1,2}\dots).
% \end{sankeyoption}
%
% \begin{sankeyoption}[/tikz/dubins path]{start angle}{\VAR{angle}}{}{}
%   The direction (in degrees) of the path at the start point.
% \end{sankeyoption}
%
% \begin{sankeyoption}[/tikz/dubins path]{end point}{\VAR{coordinate}}{}{}
%   The end point.
% \end{sankeyoption}
%
% \begin{sankeyoption}[/tikz/dubins path]{end angle}{\VAR{angle}}{}{}
%   The direction (in degrees) of the path at the end point.
% \end{sankeyoption}
%
% \begin{sankeyoption}[/tikz/dubins path]{minimum radius}{\VAR{distance}}{}{}
%   The minimum radius of curvature (processed by \code{pgfmath}), used
%   for left and right turns.
% \end{sankeyoption}
%
% \begin{sankeyoption}[/tikz/dubins path]{left and right minimum
%   radii}{\VAR{left} \texttt{and} \VAR{right}}{}{}
%   Two different radii for left and right turns (see
%   \vref{sec:dubins-parallel}). The radius used to compute the path and
%   to locate the circles is the mean of these two radii.
% \end{sankeyoption}
%
% \begin{sankeyoption}[/tikz/dubins path]{store}{\VAR{name}}{}{}
%   With \code{\dubinspathcalc}, stores (globally) the result under
%   \VAR{name}.
% \end{sankeyoption}
%
% \begin{sankeyoption}[/tikz/dubins path]{use store}{\VAR{name}}{}{}
%   Retrieves the result stored under \VAR{name}. It is a shortcut for
%   the \code{method}, \code{first angle}, \code{middle param} and
%   \code{last angle} keys.
% \end{sankeyoption}
%
% \begin{sankeyoption}[/tikz/dubins path]{method}{\VAR{method}}{}{}
%   The type of path: \code{rsr}, \code{lsl}, \code{rsl}, \code{lsr},
%   \code{rlr} or \code{lrl}.
% \end{sankeyoption}
%
% \begin{sankeyoption}[/tikz/dubins path]{first angle}{\VAR{angle}}{}{}
%   The angle (in degrees) of the first arc.
% \end{sankeyoption}
%
% \begin{sankeyoption}[/tikz/dubins path]{middle param}{\VAR{number}}{}{}
%   The angle (in degrees) of the middle arc for \emph{CCC} paths, the
%   length of the straight segment for \emph{CSC} paths (not used to
%   draw them).
% \end{sankeyoption}
%
% \begin{sankeyoption}[/tikz/dubins path]{last angle}{\VAR{angle}}{}{}
%   The angle (in degrees) of the last arc.
% \end{sankeyoption}
%
% \begin{sankeyoption}[/tikz/dubins path]{prefer}{\texttt{left}, \texttt{right} or \texttt{none}}{}{none}
%   With \code{\dubinspathcalc} (or \code{\dubinspath} without method),
%   chooses between two shortest paths of the same length (within
%   $0.01$\,pt): the path that starts by a turn on the preferred side is
%   chosen. With \code{none}, the first computed path is chosen (in this
%   order: \code{rsr}, \code{lsl}, \code{rsl}, \code{lsr}, \code{lrl},
%   \code{rlr}).
%
%   For instance, from a point to another point located behind it, with
%   the same direction, the loop may go on the left or on the right with
%   the same length.
% \end{sankeyoption}
%
% \begin{sankeyoption}[/tikz/dubins path]{reverse}{\VAR{boolean}}{}{false}
%   With \code{\dubinspath}, draws the path backward: from the current
%   point (located at, or near, the \code{end point}) to the
%   \code{start point}.
%
%   \textbf{Note:} this key only applies to the current
%   \code{\dubinspath}. The other keys used by \code{\dubinspath}
%   remain active until the end of the current path.
% \end{sankeyoption}
%
%^^A % ------------------------------------------------------------
% \subsection{Parallel paths}
% \label{sec:dubins-parallel}
%^^A % ------------------------------------------------------------
%
% \code{\dubinspath} locates the circles of the last arc from the
% \code{end point} using the mean $r$ of the two radii but draws the
% left turns with the left radius and the right turns with the right
% radius. So, to draw a path parallel to a computed path at a distance
% $d$ on its left, start from a point located at distance $d$ on the
% left of the start point and use $r-d$ as left radius and $r+d$ as
% right radius (and the opposite for a parallel path on its right).
%
% That is how \code{\sankeydubins} draws the two borders of a lane:
% the path of the center of the lane is computed with radius
% $r=\VAR{minimum radius}+w/2$ (where $w$ is the width of the lane),
% then the left border is drawn from the \code{left} anchor of the start
% node with \code{left and right minimum radii=}$r-w/2$ \code{and}
% $r+w/2$ and the right border from the \code{right} anchor with the
% opposite radii.
%
%^^A % ------------------------------------------------------------
% \subsection{Examples}
%^^A % ------------------------------------------------------------
%
% A Dubins path from $(0,0)$ (going up) to $(3,1)$ (going down):
%
% \begin{miniblock}
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \dubinspathset{
%     my path/.style={
%       start point={0,0}, start angle=90,
%       end point={3,1}, end angle=-90,
%       minimum radius=5mm,
%     },
%   }
%   \dubinspathcalc{my path,store=my path}
%   \draw[thick,-latex] (0,0) \dubinspath{my path,use store=my path};
%   \fill[red] (0,0) circle(2pt) (3,1) circle(2pt);
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
% The same path computed and drawn by a single call of
% \code{\dubinspath}:
%
% \begin{miniblock}
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \draw[thick,-latex] (0,0) \dubinspath{
%     start point={0,0}, start angle=90,
%     end point={3,1}, end angle=-90,
%     minimum radius=5mm,
%   };
%   \fill[red] (0,0) circle(2pt) (3,1) circle(2pt);
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
% Same start and end points with various end angles:
%
% \begin{miniblock}
% \begin{VerbatimOut}[gobble=2]{\samplecodename}
% \begin{tikzpicture}
%   \foreach \ang [count=\i from 0] in {0,90,180,-90}{
%     \dubinspathset{
%       p/.style={
%         start point={3*\i,0}, start angle=0,
%         end point={3*\i+1,1}, end angle=\ang,
%         minimum radius=4mm,
%       },
%     }
%     \dubinspathcalc{p,store=p}
%     \draw[thick,-latex] (3*\i,0) \dubinspath{p,use store=p};
%     \fill[red] (3*\i,0) circle(2pt) (3*\i+1,1) circle(2pt);
%   }
% \end{tikzpicture}
% \end{VerbatimOut}
% %
% {\centering\input{\samplecodename}\par}
% %
% \lstinputlisting[style=LaTeXsmall]{\samplecodename}
% \end{miniblock}
%
% ^^A % ------------------------------------------------------------
% \clearpage
%
% \manualparts
%
% \part{Examples}
% \label{examples}
%^^A % ------------------------------------------------------------
% {
%   \setlength{\parskip}{0pt}
%   \localtableofcontents
%   \listoffigures
% }
%
% \tikzset{every picture/.style={}}
%^^A % ------------------------------------------------------------
%
%^^A % ------------------------------------------------------------
% \clearpage
% \section{Simple example}
%^^A % ------------------------------------------------------------
%
% \embedfile[mimetype=text/plain]{sankey-example1.tex}
%
% \begin{figure}
%   \centering
%   {\MakePercentComment\input{sankey-example1.tex}}
%   \caption{Simple example}
%   \label{fig:simple-example}
% \end{figure}
%
% See figure~\vref{fig:simple-example}. The \code{sankey-example1.tex}
% file contains the following code and is an attachment of the current
% PDF document.
%
% \lstinputlisting[style=LaTeXsmall]{sankey-example1.tex}
%
% \iffalse
%<*example1>
\begin{tikzpicture}
  \begin{sankeydiagram}%[debug]
    \colorlet{cold}[rgb]{cyan!75!blue!50!white}
    \colorlet{hot}[rgb]{red!50!orange!75!white}
    \sankeyset{
      ratio=90pt/6,minimum radius=15pt,
      start style=simple,end style=simple,
      draw/.style={
        draw=blue!50!cyan,
        line width=1pt,line cap=round,line join=round,
      },
      cold/.style={
        fill/.style={
          draw=cold,line width=0pt,fill=cold,
        },
      },
      cold to hot/.style={
        fill/.style={
          fill=none,top color=cold,
          bottom color=hot,middle color=yellow,
        },
      },
      hot/.style={
        fill/.style={
          draw=hot,line width=0pt,fill=hot,
        },
      },
    }

    \sankeyset{cold}
    \sankeynodestart{name=p0,at={(100,0)},angle=-90,quantity=6}
    \sankeyadvance{p0}{50pt}
    \sankeyfork{p0}{3/p1,3/p2}
    \sankeyturnleft{p1}{90}
    \sankeyadvance{p1}{20pt}
    \sankeyadvance{p2}{60pt}
    \sankeyfork{p2}{2/p3,1/p4}
    \sankeyturnleft{p3}{90}
    \sankeyadvance{p3}{50pt}
    \sankeyfork{p3}{1/p5,1/p6}
    \sankeyadvance{p5}{70pt}
    \sankeyfork{p1}{1/p7,1/p8,1/p9}
    \sankeyadvance{p7}{50pt}
    \sankeyadvance{p9}{50pt}
    \sankeyadvance{p4}{40pt}
    \sankeyturnleft{p4}{90}
    \sankeyadvance{p4}{65pt}
    \sankeyadvance{p7}{40pt}
    \sankeynode{
      name=p11,below right={15pt and 50pt of p7},quantity=3,
      forked={1/p7a,1/p9a,1/p5a},
    }
    \sankeyoutin{p7}{p7a}
    \sankeyoutin{p9}{p9a}
    \sankeyoutin{p5}{p5a}
    \sankeyadvance{p11}{30pt}
    \sankeyend{p11}
    \sankeyturnright{p8}{90}
    \sankeyturnright{p6}{90}
    \sankeyturnright{p4}{90}
    \sankeyset{hot}
    \sankeyadvance[cold to hot]{p8}{40pt}
    \sankeynode{
      name=p10,below left={60pt and 15pt of p8},angle=-90,quantity=3,
      forked={1/p8a,1/p6a,1/p4a},
    }
    \sankeyoutin[cold to hot]{p4}{p4a}
    \sankeyoutin[cold to hot]{p6}{p6a}
    \sankeyoutin{p8}{p8a}
    \sankeyadvance{p10}{30pt}
    \sankeyend{p10}
  \end{sankeydiagram}
\end{tikzpicture}
%</example1>
% \fi
% 
%^^A % ------------------------------------------------------------
% \clearpage
% \section{Energy diagram}
%^^A % ------------------------------------------------------------
%
% \changes{v3.1.0}{2026/11/29}{Document the coding tips of the examples
%   (data list, styles, labelling macros, loops)}
%
% \embedfile[mimetype=text/plain]{sankey-example-energy.tex}
%
% \begin{figure}
%   \centering
%   {\MakePercentComment\input{sankey-example-energy.tex}}
%   \caption{Energy diagram}
%   \label{fig:very-simple-example}
% \end{figure}
%
% This example comes from
% \href{https://ibphysicsblog.wordpress.com/2015/10/23/sankey-diagrams/}{IB
% Physics Blog} by Kyu Won Shim.
%
% See figure~\vref{fig:very-simple-example}. The \code{sankey-example-energy.tex}
% file contains the following code and is an attachment of the current
% PDF document.
%
% Some coding tips:
% \begin{itemize}
% \item The \code{energy} and \code{lost energy} styles redefine the
%   \code{fill/.style} key in one go. A style is then used as an option of
%   a macro (\code|\sankeyadvance[energy]{Co}{1cm}|) or of a group
%   (\code|\sankeyset{lost energy}|).
% \item The labels are written by macros defined in the example
%   (\code{\energylabel}, \code{\lostenergylabel}, \code{\abovelabel}, etc.).
%   The quantity that they display is read from the node by
%   \code{\sankeygetnodeqty}, so it is not typed twice.
% \item The \code{\turnandstop} macro does a complete branch (turn, stop
%   node, link, label). It is enclosed in a group, so that
%   \code|\sankeyset{lost energy}| only applies to this branch.
% \end{itemize}
%
% \lstinputlisting[style=LaTeXsmall]{sankey-example-energy.tex}
%
% \iffalse
%<*example-energy>
\begin{tikzpicture}
  % font choice
  \renewcommand\rmdefault{txr}\rmfamily\footnotesize
  \sisetup{
    round-mode=places,
    round-precision=1,
    add-decimal-zero,
    round-pad=true,
  }
  \begin{sankeydiagram}
    \colorlet{energy}{blue!30!cyan!80!black}
    \colorlet{lost energy}{red!50!orange!90!black}
    \sankeyset{
      ratio=13em/100,
      minimum radius=1em,
      start style=simple,end style=simple,
      draw/.style={draw=none,line width=0},
      energy/.style={
        fill/.style={
          draw=energy,
          line width=0,
          fill=energy,
        }
      },
      lost energy/.style={
        fill/.style={
          draw=lost energy,
          line width=0,
          fill=lost energy,
        }
      }
    }

    \newcommand\abovelabel[2]{ % valname, label
      \node[anchor=south east,align=center,inner xsep=0] at (#1.left) {#2};
    }
    
    \newcommand\energylabel[1]{ % valname
      \node[anchor=north east,text=energy,inner xsep=0] at (#1.right)
      {\num{\sankeygetnodeqty{#1}}};
    }

    \newcommand\lostenergylabel[2]{ % valname, label
      \node[anchor=north,text=lost energy] at ([yshift=-2.5mm]#1.center)
      (value)
      {\num{\sankeygetnodeqty{#1}}};
      \node[anchor=north,inner sep=0,align=center] at (value.south) {#2};
    }
    
    \newcommand\lostenergylabelbottom[2]{ % valname, label
      \draw[draw=lost energy,dashed,thick]
      ([yshift=-3mm]#1.center) coordinate (#1) -- ([yshift=-3mm]#1.center);
      \lostenergylabel{#1}{#2}
    }
    
    \sankeynode{name=Co,quantity=100.0}
    \path (Co.right) ++(0,-7mm) coordinate (c);
    
    \newcommand\turnandstop[2]{ % valname, label
      \begingroup
      \sankeyset{lost energy}
      \sankeyturnright{#1}{90}
      \sankeynode{as=#1,name=#1-stop,at={(#1 |- c)}}
      \sankeyoutin{#1}{#1-stop}
      \sankeynode{as=#1-stop,name=#1}
      \sankeyend{#1}
      \lostenergylabel{#1}{#2}
      \endgroup
    }    

    \newcommand\turnandstopbottom[2]{ % valname, label
      \begingroup
      \sankeyset{lost energy}
      \sankeyturnright{#1}{90}
      \sankeynode{as=#1,name=#1-stop,at={(#1 |- c)}}
      \sankeyoutin{#1}{#1-stop}
      \sankeynode{as=#1-stop,name=#1}
      \sankeyend{#1}
      \lostenergylabelbottom{#1}{#2}
      \endgroup
    }    

    \def\hshift{6.25em}
    
    \sankeyadvance[energy]{Co}{1.2*\hshift}
    \abovelabel{Co}{\textbf{Coal}\\(Primary energy)}
    \energylabel{Co}
    \sankeyfork{Co}{35/El1,65/Pg}
    \turnandstop{Pg}{Power generation}

    \sankeyadvance[energy]{El1}{1.8*\hshift}
    \abovelabel{El1}{\textbf{Electricity}\\(Secondary energy)}
    \energylabel{El1}
    \sankeyfork{El1}{33.5/El2,1.5/Tr}
    \turnandstopbottom{Tr}{Transmission}
    
    \sankeyadvance[energy]{El2}{.65*\hshift}
    \energylabel{El2}
    \sankeyfork{El2}{31.5/El3,2.0/Di}
    \turnandstop{Di}{Distribution}
    
    \sankeyadvance[energy]{El3}{.65*\hshift}
    \energylabel{El3}
    \sankeyfork{El3}{31.0/El4,0.5/Wi}
    \turnandstopbottom{Wi}{Wiring}
    
    \sankeyadvance[energy]{El4}{.65*\hshift}
    \abovelabel{El4}{\textbf{Electricity}\\(Final energy)}
    \energylabel{El4}
    \sankeyfork{El4}{3.0/Lr1,28.0/Lb}
    \turnandstop{Lb}{Lightbulb}
    
    \sankeyadvance[energy]{Lr1}{1.1*\hshift}
    \abovelabel{Lr1}{\textbf{Light radiation}\\(Useful energy)}
    \energylabel{Lr1}
    \sankeyfork{Lr1}{2.0/Lr2,1.0/Ls}
    \turnandstopbottom{Ls}{Lampshade}
    
    \sankeyadvance[energy]{Lr2}{.6*\hshift}
    \energylabel{Lr2}
    \sankeyfork{Lr2}{1.0/Il,1.0/Id}
    \turnandstop{Id}{Idle}

    \sankeyadvance[energy]{Il}{.6*\hshift}
    \abovelabel{Il}{\textbf{Illumination}\\(Energy services)}
    \energylabel{Il}
    \sankeyend[energy]{Il}
  \end{sankeydiagram}
\end{tikzpicture}
%</example-energy>
% \fi
%^^A % ------------------------------------------------------------
% \clearpage
% \section{Example from question on TeX.se}
%^^A % ------------------------------------------------------------
%
% \changes{v3.0}{2021/03/14}{Fix bad names in second example}
%
% \embedfile[mimetype=text/plain]{sankey-example2.tex}
%
% \begin{figure}
%   \centering
%   {\MakePercentComment\input{sankey-example2}}
%   \caption{Example from TeX.se question}
%   \label{fig:texse-example}
% \end{figure}
%
% This example came from
% \href{https://tex.stackexchange.com/q/40159/14500}{this question} on
% \href{https://tex.stackexchange.com/}{TeX.StackExchange}.
%
% See figure~\vref{fig:texse-example}. The \code{sankey-example2.tex}
% file contains the following code and is an attachment of the current
% PDF document.
% 
% \lstinputlisting[style=LaTeXsmall]{sankey-example2}
%
% \iffalse
%<*example2>
\begin{tikzpicture}
  \renewcommand*\sfdefault{txss}

  \begin{sankeydiagram}%[debug]
    \sankeyset{
      ratio=4cm/524.3,
      minimum radius=3mm,
      start style=arrow,
      end style=arrow,
      fill/.style={
        line width=0pt,
        fill=cyan!50!blue!50!black,
        draw=cyan!50!blue!50!black,
      },
      draw/.style={draw=none},
      every node/.style={angle=-90},
    }

    \sankeynodestart{name=B,at={(-.5,0)},quantity=7.2}
    \coordinate[below=1mm of B.center] (B label);
    \sankeyadvance{B}{5mm}
    \sankeynodestart{name=GI,at={(1,0)},quantity=137.3}
    \coordinate[below=1mm of GI.center] (GI label);
    \sankeyadvance{GI}{5mm}
    \sankeynodestart{name=I,at={(4,0)},quantity=397.8}
    \coordinate[below=1mm of I.center] (I label);
    \sankeynode{
      name=EI,at={(2.86,-3)},quantity=542.3,
      forked={397.8/Ia,137.3/GIa,7.2/Ba}
    }
    \sankeydubins[minimum radius=1.2cm]{I}{Ia}
    \sankeyoutin{GI}{GIa}
    \sankeyoutin{B}{Ba}
    \sankeyadvance{EI}{5mm}
    \coordinate (EI label) at (EI);
    \sankeyadvance{EI}{5mm}
    \sankeyfork{EI}{63.1/EB,479.2/P}

    \sankeyturnleft{EB}{90}
    \sankeyadvance{EB}{4cm}
    \coordinate (EB label) at ($(EB)!.5!(EB-old)$);
    \sankeyend{EB}

    \sankeyadvance{P}{10mm}
    \coordinate (P label) at (P);
    \sankeyadvance{P}{5mm}

    \sankeyfork{P}{33.5/NV,445.7/P-NV}

    {
      \colorlet{NV color}{cyan!80!lime!50!gray}
      \sankeyset{fill/.append style={fill=NV color,draw=NV color}}
      \sankeyturnleft{NV}{90}
      \sankeynode{as=NV,name=NV2,at={(NV -| EB)}}
      \sankeyoutin{NV}{NV2}
      \coordinate (NV label) at (NV -| EB label);
      \sankeyend{NV2}
    }

    \sankeyadvance{P-NV}{10mm}
    \sankeyfork{P-NV}{118.1/U,327.6/P-NV-U}

    {
      \sankeyset{
        fill/.style={fill=orange!70!gray!50,draw=orange!70!gray!50}
      }
      \sankeyturnleft{U}{90}
      \sankeynode{as=U,name=U2,at={(U -| EB)}}
      \sankeyoutin{U}{U2}
      \coordinate (U label) at (U -| EB label);
      \sankeyend{U2}
    }

    \sankeyadvance{P-NV-U}{10mm}
    \sankeyfork{P-NV-U}{327.2/P-NV-U-SD,0.4/SD}

    {
      \sankeyturnright{SD}{90}
      \sankeyadvance{SD}{15mm}
      \coordinate (SD label) at (SD);
      \sankeyadvance{SD}{15mm}
      \sankeyend{SD}
    }

    \sankeyadvance{P-NV-U-SD}{8mm}
    \sankeyfork{P-NV-U-SD}{18.8/VE,308.4/E}

    {
      \sankeyset{fill/.append style={orange!70!gray!30}}
      \sankeyturnleft{VE}{90}
      \sankeynode{as=VE,name=VE2,at={(VE -| EB)}}
      \sankeyoutin{VE}{VE2}
      \coordinate (VE label) at (VE -| EB label);
      \sankeyend{VE2}
    }

    \sankeyadvance{E}{8mm}
    \coordinate (E label) at (E);
    \sankeyadvance{E}{20mm}
    \sankeyfork{E}{135.1/H+GHD,87.2/V,86.1/In}

    \sankeyturnright{In}{90}
    \sankeyadvance{In}{10mm}
    \sankeyturnleft{In}{90}
    \sankeyadvance{In}{5mm}
    \coordinate (In label)  at (In);
    \sankeyadvance{In}{10mm}
    \sankeyend{In}

    \sankeynode{as=V,name=V2,at={(V|-In label)}}
    \sankeyoutin{V}{V2}
    \coordinate (V label) at (V2);
    \sankeyadvance{V2}{10mm}
    \sankeyend{V2}

    \sankeyturnleft{H+GHD}{90}
    \sankeyadvance{H+GHD}{5mm}
    \sankeyfork{H+GHD}{47.0/GHD,88.1/H}

    \sankeyturnright{H}{90}
    \sankeynode{as=H,name=H2,at={(H|-In label)}}
    \sankeyoutin{H}{H2}
    \coordinate (H label) at (H2);
    \sankeyadvance{H2}{10mm}
    \sankeyend{H2}

    \sankeyadvance{GHD}{30mm}
    \sankeyturnright{GHD}{90}
    \sankeynode{as=GHD,name=GHD2,at={(GHD|-In label)}}
    \sankeyoutin{GHD}{GHD2}
    \coordinate (GHD label) at (GHD2);
    \sankeyadvance{GHD2}{10mm}
    \sankeyend{GHD2}
  \end{sankeydiagram}

  % labels
  \tikzset{
    label/.style={
      fill=white,fill opacity=.8,text opacity=1,
      inner sep=1mm,
      text=cyan!50!blue!50!black,
      inner xsep=2mm,
      font=\sffamily\bfseries\footnotesize,
      align=center,
    },
  }
  \node[label,anchor=north] (B label) at (B label) {7.2};
  \node[label,left=1mm of B label] {Bestands-\\entnahme};
  \node[label,anchor=north] at (GI label) {137.3};
  \node[label,above=5mm of GI label] {Gewinnung\\im Inland};
  \node[label,anchor=north] at (I label) {397.8};
  \node[label,above=5mm of I label] {Import};

  \node[label] at (EI label) {542.3\\Energieaufkommen im Inland};

  \node[label,anchor=center] (EB label) at (EB label) {63.1};
  \node[label,above=1mm of EB label] {Export und\\Bunkerung};

  \node[label] at (P label) {479.2\\Primärenergieverbrauch};

  \node[label,anchor=center] (NV label) at (NV label) {33.5};
  \node[label,above=0mm of NV label] {Nichtenergetischer Verbrauch};

  \node[label,anchor=center] (U label) at (U label) {118.1};
  \node[label,below=3mm of U label] {Umwandlungsverluste};

  \node[label,anchor=center] (SD label) at (SD label) {0.4};
  \node[label,above=0mm of SD label] {Statistische\\Differenzen};

  \node[label,anchor=center] (VE label) at (VE label) {18.8};
  \node[label,below=0mm of VE label] {Verbrauch in den\\Energiesktoren};

  \node[label,anchor=north] (E label) at (E label)
  {308.4\\Endenergieverbrauch};

  \node[label,anchor=north] (In label) at (In label) {86.1};
  \node[label,anchor=north,below=1cm of In label] {Industrie};

  \node[label,anchor=north] (V label) at (V label) {87.2};
  \node[label,anchor=north,below=1cm of V label] {Verkehr};

  \node[label,anchor=north] (H label) at (H label) {88.1};
  \node[label,anchor=north,below=1cm of H label] {Haushalte};

  \node[label,anchor=north] (GHD label) at (GHD label) {47.0};
  \node[label,anchor=north,below=1cm of GHD label]
  {Gewerbe, Handel\\Diensleistungen};
\end{tikzpicture}
%</example2>
% \fi
%
%^^A % ------------------------------------------------------------
% \clearpage
% \section{Reproduction of an example from Google Charts documentation}
%^^A % ------------------------------------------------------------
%
% \changes{v3.0}{2021/03/14}{Add the reproduction of an example from
% Google Charts documentation}
%
% \embedfile[mimetype=text/plain]{sankey-example3.tex}
%
% This example is a reproduction of an example of Google
% Charts Documentation\footnote{\url{https://developers.google.com/chart/interactive/docs/gallery/sankey}}.
%
% See figure \vref{fig:google-example}. The \code{sankey-example3.tex}
% file contains the following code and is an attachment of the current
% PDF document.
%
% \begin{figure}
%   \centering
%   {\MakePercentComment\input{sankey-example3}}
%   \caption{Reproduction of an example from Google Charts
%   documentation}
%   \label{fig:google-example}
% \end{figure}
%
% \lstinputlisting[style=LaTeXsmall]{sankey-example3}
%
% \iffalse
%<*example3>
\begin{tikzpicture}
  \begin{sankeydiagram}%[debug]
    \sffamily
    \sankeyset{
      ratio=1cm/10,
      outin steps=2,
      draw/.style={draw=none,line width=0pt},
      color/.style={fill/.style={fill=#1,fill opacity=.75}},
      shade/.style 2 args={fill/.style={left color=#1,
          right color=#2,fill opacity=.5}},
      % colors
      @define HTML color/.code args={#1/#2}{\definecolor{#1}{HTML}{#2}},
      @define HTML color/.list={
        cyan/a6cee3,lime/b2df8a,red/fb9a99,orange/fdbf6f,
        violet/cab2d6,yellow/ffff99,blue/1f78b4,green/33a02c
      },
      % colors of countries
      @let country color/.code args={#1/#2}{\colorlet{#1}[rgb]{#2}},
      @let country color/.list={
        CA/red,US/orange,MX/orange,BR/cyan,FR/lime,GB/red,
        SP/lime,PT/cyan,ML/blue,SN/violet,MA/yellow,
        AO/violet,ZA/yellow,IN/green,JP/green,CN/blue
      },
    }
    \def\vdist{5mm}
    \def\hwidth{.5em}
    \def\hdist{4.1cm}
    
    \sankeynode{name=CA,quantity=7}
    \sankeynode{name=US,quantity=8,above={\vdist of CA.left},anchor=right}
    \sankeynode{name=MX,quantity=8,above={\vdist of US.left},anchor=right}
    \sankeynode{name=BR,quantity=8,above={\vdist of MX.left},anchor=right}

    \foreach \country in {CA,US,MX,BR}{
      \sankeyadvance[color=\country]{\country}{\hwidth}
    }

    \sankeyfork{CA}{1/CA-to-PT,1/CA-to-GB,5/CA-to-FR}
    \sankeyfork{US}{1/US-to-PT,1/US-to-SP,5/US-to-GB,1/US-to-FR}
    \sankeyfork{MX}{1/MX-to-PT,5/MX-to-SP,1/MX-to-GB,1/MX-to-FR}
    \sankeyfork{BR}{5/BR-to-PT,1/BR-to-SP,1/BR-to-GB,1/BR-to-FR}

    \sankeynode{name=FR,quantity=11,
      right={\hdist of CA.right},anchor=right}
    \sankeynode{name=GB,quantity=11,
      above={\vdist of FR.left},anchor=right}
    \sankeynode{name=SP,quantity=7,
      above={\vdist of GB.left},anchor=right}
    \sankeynode{name=PT,quantity=8,
      above={\vdist of SP.left},anchor=right}

    \sankeyfork{FR}
    {1/FR-from-BR,1/FR-from-MX,1/FR-from-US,5/FR-from-CA,3/FR-from-00}
    \sankeyfork{GB}
    {1/GB-from-BR,1/GB-from-MX,5/GB-from-US,1/GB-from-CA,3/GB-from-00}
    \sankeyfork{SP}{1/SP-from-BR,5/SP-from-MX,1/SP-from-US}
    \sankeyfork{PT}{5/PT-from-BR,1/PT-from-MX,1/PT-from-US,1/PT-from-CA}

    \foreach \country in {FR,GB,SP,PT}{
      \sankeyadvance[color=\country]{\country}{\hwidth}
    }

    \sankeyfork{FR}{1/FR-to-ZA,1/FR-to-AO,3/FR-to-MA,3/FR-to-SN,3/FR-to-ML}
    \sankeyfork{GB}{7/GB-to-ZA,1/GB-to-AO,2/GB-to-MA,1/GB-to-SN}
    \sankeyfork{SP}{1/SP-to-ZA,3/SP-to-MA,1/SP-to-SN,2/SP-to-00}
    \sankeyfork{PT}{3/PT-to-ZA,2/PT-to-AO,1/PT-to-MA,1/PT-to-SN,1/PT-to-00}

    \sankeynode{name=ML,quantity=9,
      right={\hdist of FR.right},anchor=right}
    \sankeynode{name=SN,quantity=9,
      above={\vdist of ML.left},anchor=right}
    \sankeynode{name=MA,quantity=9,
      above={\vdist of SN.left},anchor=right}
    \sankeynode{name=AO,quantity=9,
      above={\vdist of MA.left},anchor=right}
    \sankeynode{name=ZA,quantity=12,
      above={\vdist of AO.left},anchor=right}

    \sankeyfork{ML}{3/ML-from-FR,6/Mail-from-00}
    \sankeyfork{SN}
    {1/SN-from-PT,1/SN-from-SP,1/SN-from-GB,3/SN-from-FR,3/SN-from-00}
    \sankeyfork{MA}{1/MA-from-PT,3/MA-from-SP,2/MA-from-GB,3/MA-from-FR}
    \sankeyfork{AO}{2/AO-from-PT,1/AO-from-GB,1/AO-from-FR,5/AO-from-00}
    \sankeyfork{ZA}{3/ZA-from-PT,1/ZA-from-SP,7/ZA-from-GB,1/ZA-from-FR}
    
    \foreach \country in {ML,SN,MA,AO,ZA}{
      \sankeyadvance[color=\country]{\country}{\hwidth}
    }

    \sankeyfork{ML}{5/ML-to-CN,3/ML-to-JP,1/ML-to-IN}
    \sankeyfork{SN}{5/SN-to-CN,3/SN-to-JP,1/SN-to-IN}
    \sankeyfork{MA}{5/MA-to-CN,3/MA-to-JP,1/MA-to-IN}
    \sankeyfork{AO}{5/AO-to-CN,3/AO-to-JP,1/AO-to-IN}
    \sankeyfork{ZA}{5/ZA-to-CN,3/ZA-to-JP,1/ZA-to-IN,3/ZA-to-00}

    \sankeynode{name=IN,quantity=5,
      right={\hdist of ML.right},anchor=right}
    \sankeynode{name=JP,quantity=15,
      above={\vdist of IN.left},anchor=right}
    \sankeynode{name=CN,quantity=25,
      above={\vdist of JP.left},anchor=right}
    
    \sankeyfork{IN}
    {1/IN-from-ZA,1/IN-from-AO,1/IN-from-MA,1/IN-from-SN,1/IN-from-ML}
    \sankeyfork{JP}
    {3/JP-from-ZA,3/JP-from-AO,3/JP-from-MA,3/JP-from-SN,3/JP-from-ML}
    \sankeyfork{CN}
    {5/CN-from-ZA,5/CN-from-AO,5/CN-from-MA,5/CN-from-SN,5/CN-from-ML}

    \foreach \country in {IN,JP,CN}{
      \sankeyadvance[color=\country]{\country}{\hwidth}
    }
    
    \foreach \startcountry/\countries in {
      CA/{PT,GB,FR},    US/{PT,SP,GB,FR},    MX/{PT,SP,GB,FR},
      BR/{PT,SP,GB,FR}, FR/{ML,SN,MA,AO,ZA}, GB/{SN,MA,AO,ZA},
      SP/{SN,MA,ZA},    PT/{SN,MA,AO,ZA},    ML/{IN,JP,CN},
      SN/{IN,JP,CN},    MA/{IN,JP,CN},       AO/{IN,JP,CN},
      ZA/{IN,JP,CN}}
    {
      \foreach \endcountry in \countries {
        \sankeyoutin[shade={\startcountry}{\endcountry}]
        {\startcountry-to-\endcountry}{\endcountry-from-\startcountry}
      }
    }

    \foreach \country/\countryname in {CA/Canada, US/USA, MX/Mexico,
      BR/Brazil, FR/France, GB/England, SP/Spain, PT/Portugal}
    {
      \node[anchor=west,inner sep=.1em,font=\small]
      at (\country) {\countryname\vphantom{Ag}};
    }

    \foreach \country/\countryname in {
      ML/Mali, SN/Senegal, MA/Morocco, AO/Angola,
      ZA/South Africa, IN/India, JP/Japan, CN/China}
    {
      \node[anchor=east,inner sep=.1em,font=\small]
      at (\country-old) {\countryname\vphantom{Ag}};
    }
  \end{sankeydiagram}
\end{tikzpicture}
%</example3>
% \fi
%
%^^A % ------------------------------------------------------------
% \subsection{Variation}
%^^A % ------------------------------------------------------------
%
% Here is a variation of the previous example using the \code{rotate}
% key. Note that the positioning keys (\code{above}, \code{right}\dots)
% use the directions of the page, as the \code{positioning} TikZ
% library does: since the picture is rotated by $-90$ degrees,
% \code{right} and \code{below} replace the \code{above} and
% \code{right} keys of the previous example.
%
% See figure \vref{fig:google-example-variation}. The
% \code{sankey-example3-variation.tex} file contains the following code
% and is an attachment of the current PDF document.
%
% \begin{figure}
%   \centering
%   {\MakePercentComment\input{sankey-example3-variation}}
%   \caption{Reproduction of an example from Google Charts documentation
%   -- variation using the \protect\texttt{rotate} key.}
%   \label{fig:google-example-variation}
% \end{figure}
%
% \lstinputlisting[style=LaTeXsmall]{sankey-example3-variation}
%
% \iffalse
%<*example3-variation>
\begin{tikzpicture}[rotate=-90]
  \begin{sankeydiagram}[rotate=-90]
    \sffamily
    \sankeyset{
      ratio=1.7cm/10,
      outin steps=2,
      start style=arrow,
      end style=simple,
      draw/.style={draw=white,line width=.4pt},
      color/.style={fill/.style={fill=#1,fill opacity=.75}},
      shade/.style 2 args={fill/.style={
          fill=none,line width=0,
          top color=#1,bottom color=#2,
          middle color=#1!50!#2!50!white,
          fill opacity=.75}},
      % colors
      @define HTML color/.code args={#1/#2}{\definecolor{#1}{HTML}{#2}},
      @define HTML color/.list={
        cyan/a6cee3,lime/b2df8a,red/fb9a99,orange/fdbf6f,
        violet/cab2d6,yellow/ffff99,blue/1f78b4,green/33a02c
      },
      % colors of countries
      @let country color/.code args={#1/#2}{\colorlet{#1}[rgb]{#2}},
      @let country color/.list={
        CA/red,US/orange,MX/lime,BR/violet,FR/yellow,GB/blue,
        SP/green,PT/cyan,ML/cyan,SN/red,MA/orange,
        AO/violet,ZA/lime,IN/blue,JP/yellow,CN/green
      },
    }
    \def\vdist{5mm}
    \def\hwidth{1em}
    \def\hdist{6cm}

    \sankeynode{name=CA,quantity=7}
    \sankeynode{name=US,quantity=8,right={\vdist of CA.left},anchor=right}
    \sankeynode{name=MX,quantity=8,right={\vdist of US.left},anchor=right}
    \sankeynode{name=BR,quantity=8,right={\vdist of MX.left},anchor=right}

    \foreach \country in {CA,US,MX,BR}{
      \sankeystart[color=\country]{\country}
      \sankeyadvance[color=\country]{\country}{\hwidth}
    }

    \sankeyfork{CA}{1/CA-to-PT,1/CA-to-GB,5/CA-to-FR}
    \sankeyfork{US}{1/US-to-PT,1/US-to-SP,5/US-to-GB,1/US-to-FR}
    \sankeyfork{MX}{1/MX-to-PT,5/MX-to-SP,1/MX-to-GB,1/MX-to-FR}
    \sankeyfork{BR}{5/BR-to-PT,1/BR-to-SP,1/BR-to-GB,1/BR-to-FR}

    \sankeynode{name=FR,quantity=11,
      below={\hdist of CA.right},anchor=right}
    \sankeynode{name=GB,quantity=11,
      right={\vdist of FR.left},anchor=right}
    \sankeynode{name=SP,quantity=7,
      right={\vdist of GB.left},anchor=right}
    \sankeynode{name=PT,quantity=8,
      right={\vdist of SP.left},anchor=right}

    \sankeyfork{FR}
    {1/FR-from-BR,1/FR-from-MX,1/FR-from-US,5/FR-from-CA,3/FR-from-00}
    \sankeyfork{GB}
    {1/GB-from-BR,1/GB-from-MX,5/GB-from-US,1/GB-from-CA,3/GB-from-00}
    \sankeyfork{SP}{1/SP-from-BR,5/SP-from-MX,1/SP-from-US}
    \sankeyfork{PT}{5/PT-from-BR,1/PT-from-MX,1/PT-from-US,1/PT-from-CA}

    \foreach \country in {FR,GB,SP,PT}{
      \sankeyadvance[color=\country]{\country}{\hwidth}
    }

    \sankeyfork{FR}{1/FR-to-ZA,1/FR-to-AO,3/FR-to-MA,3/FR-to-SN,3/FR-to-ML}
    \sankeyfork{GB}{7/GB-to-ZA,1/GB-to-AO,2/GB-to-MA,1/GB-to-SN}
    \sankeyfork{SP}{1/SP-to-ZA,3/SP-to-MA,1/SP-to-SN,2/SP-to-00}
    \sankeyfork{PT}{3/PT-to-ZA,2/PT-to-AO,1/PT-to-MA,1/PT-to-SN,1/PT-to-00}

    \sankeynode{name=ML,quantity=9,
      below={\hdist of FR.right},anchor=right}
    \sankeynode{name=SN,quantity=9,
      right={\vdist of ML.left},anchor=right}
    \sankeynode{name=MA,quantity=9,
      right={\vdist of SN.left},anchor=right}
    \sankeynode{name=AO,quantity=9,
      right={\vdist of MA.left},anchor=right}
    \sankeynode{name=ZA,quantity=12,
      right={\vdist of AO.left},anchor=right}

    \sankeyfork{ML}{3/ML-from-FR,6/Mail-from-00}
    \sankeyfork{SN}
    {1/SN-from-PT,1/SN-from-SP,1/SN-from-GB,3/SN-from-FR,3/SN-from-00}
    \sankeyfork{MA}{1/MA-from-PT,3/MA-from-SP,2/MA-from-GB,3/MA-from-FR}
    \sankeyfork{AO}{2/AO-from-PT,1/AO-from-GB,1/AO-from-FR,5/AO-from-00}
    \sankeyfork{ZA}{3/ZA-from-PT,1/ZA-from-SP,7/ZA-from-GB,1/ZA-from-FR}

    \foreach \country in {ML,SN,MA,AO,ZA}{
      \sankeyadvance[color=\country]{\country}{\hwidth}
    }

    \sankeyfork{ML}{5/ML-to-CN,3/ML-to-JP,1/ML-to-IN}
    \sankeyfork{SN}{5/SN-to-CN,3/SN-to-JP,1/SN-to-IN}
    \sankeyfork{MA}{5/MA-to-CN,3/MA-to-JP,1/MA-to-IN}
    \sankeyfork{AO}{5/AO-to-CN,3/AO-to-JP,1/AO-to-IN}
    \sankeyfork{ZA}{5/ZA-to-CN,3/ZA-to-JP,1/ZA-to-IN,3/ZA-to-00}

    \sankeynode{name=IN,quantity=5,
      below={\hdist of ML.right},anchor=right}
    \sankeynode{name=JP,quantity=15,
      right={\vdist of IN.left},anchor=right}
    \sankeynode{name=CN,quantity=25,
      right={\vdist of JP.left},anchor=right}

    \sankeyfork{IN}
    {1/IN-from-ZA,1/IN-from-AO,1/IN-from-MA,1/IN-from-SN,1/IN-from-ML}
    \sankeyfork{JP}
    {3/JP-from-ZA,3/JP-from-AO,3/JP-from-MA,3/JP-from-SN,3/JP-from-ML}
    \sankeyfork{CN}
    {5/CN-from-ZA,5/CN-from-AO,5/CN-from-MA,5/CN-from-SN,5/CN-from-ML}

    \foreach \country in {IN,JP,CN}{
      \sankeyadvance[color=\country]{\country}{\hwidth}
      \sankeyend[color=\country]{\country}
    }

    \foreach \startcountry/\countries in {
      CA/{PT,GB,FR},    US/{PT,SP,GB,FR},    MX/{PT,SP,GB,FR},
      BR/{PT,SP,GB,FR}, FR/{ML,SN,MA,AO,ZA}, GB/{SN,MA,AO,ZA},
      SP/{SN,MA,ZA},    PT/{SN,MA,AO,ZA},    ML/{IN,JP,CN},
      SN/{IN,JP,CN},    MA/{IN,JP,CN},       AO/{IN,JP,CN},
      ZA/{IN,JP,CN}}
    {
      \foreach \endcountry in \countries {
        \sankeyoutin[shade={\startcountry}{\endcountry}]
        {\startcountry-to-\endcountry}{\endcountry-from-\startcountry}
      }
    }

    
    \foreach \country/\countryname in {CA/Canada, US/USA, MX/Mexico,
      BR/Brazil, FR/France, GB/England, SP/Spain, PT/Portugal}
    {
      \node[anchor=south,inner sep=.1em,font=\small]
      at (\country) {\countryname\vphantom{Ag}};
    }

    \foreach \country/\countryname in {
      ML/Mali, SN/Senegal, MA/Morocco, AO/Angola,
      ZA/South Africa, IN/India, JP/Japan, CN/China}
    {
      \node[anchor=south,inner sep=.1em,font=\small]
      at (\country) {\countryname\vphantom{Ag}};
    }
  \end{sankeydiagram}
\end{tikzpicture}
%</example3-variation>
% \fi
%
%^^A % ------------------------------------------------------------
% \clearpage
% \section{Very nice example -- Nadieh Bremer creation}
%^^A % ------------------------------------------------------------
%
% \embedfile[mimetype=text/plain]{sankey-example4.tex}
%
% \begin{figure}
%   \centering
%   {\MakePercentComment\input{sankey-example4}}
%   \caption{Very nice example -- Nadieh Bremer's creation}
%   (from
%   \href{https://www.visualcinnamon.com/portfolio/adyen-report-2019/}{Adyen's
%     Shareholder Report})
%   \label{fig:nice-example}
% \end{figure}
%
% Graphic designer Nadieh Bremer created this very nice Sankey
% diagram\footnote{\url{https://www.visualcinnamon.com/portfolio/adyen-report-2019/}}
% for Adyen's second half 2018 report to shareholders. It is coded here
% with her kind permission.
%
% You can change the data values between lines 27 and 52.
%
% Some coding tips make this diagram simpler to write and to change:
% \begin{itemize}
% \item Each value is written only once, in the \code{def data/.list}
%   key. For each item, \code{def data/.code args} stores the label
%   (\code{\LabSet}) and the quantity (\code{\QtySet}) in macros named
%   after the node. The quantity is computed by \code{\fpeval}, so an item
%   can be an expression that uses the other quantities, read with
%   \code{\Qty}: the intermediate totals are never typed. The labels are
%   read with \code{\Lab}.
% \item The \code{cost node} style gathers all that the labels have in
%   common (font, alignment, contents). Each label is then a single
%   \code{\node}, for instance \code|\node[cost node=R,right label hashed=R];|.
%   The \code{right label hashed} and \code{left label hashed} styles put
%   a label at the middle of a hashed band, between the node and its
%   previous position (the \code{-old} alias).
% \item The macros defined in the example (\code{\turnandstop} and
%   \code{\hashband}) and the \code{\foreach} loops repeat the same
%   operations for several nodes.
% \end{itemize}
% Pitfalls: no comma after the last item of the \code{def data/.list},
% and a label that contains a comma must be enclosed in braces.
%
% See figure~\vref{fig:nice-example}. The \code{sankey-example4.tex}
% file contains the following code and is an attachment of the current
% PDF document.
%
% \lstinputlisting[numbers=left,style=LaTeXsmall]{sankey-example4}
%
% \iffalse
%<*example4>
\begin{tikzpicture}
  \renewcommand*\sfdefault{txss}
  \sffamily
  \sisetup{
    detect-all=true,
    group-separator={,},
    group-minimum-digits=4,
  }
  % storage of labels
  \newcommand\LabSet[2]{% node name, label
    \expandafter\edef\csname#1@Lab\endcsname{#2}}
  \newcommand\Lab[1]{% node name
    \csname#1@Lab\endcsname}
  % storage of quantities
  \newcommand\QtySet[2]{% node name, quantity
    \expandafter\edef\csname#1@Qty\endcsname{\fpeval{#2}}}
  \newcommand\Qty[1]{% node name
    \csname#1@Qty\endcsname}
  % all nodes with their name, label and quantity
  \sankeyset{
    def data/.code args={#1/#2/#3}{% node name/label/values
      \LabSet{#1}{#2}
      \QtySet{#1}{#3}
      \typeout{#1: \Qty{#1}€ (\Lab{#1})}
    },
    def data/.list={
      {Pf/Processing\\fees/71713},
      {Sog/Sales of\\good/4547},
      {Sf/Settlement\\fees/842075},
      {Os/Other\\services/37532},
      {R/Revenues/\Qty{Pf}+\Qty{Sog}+\Qty{Sf}+\Qty{Os}},
      {Coi/Cost of Inventory/5151},
      {Ciffi/Cost insecure from financial institutions/758234},
      {Nr/Net revenue/\Qty{R}-\Qty{Coi}-\Qty{Ciffi}},
      {Aadotaifa/Amortization and\\depreciation of tangible and\\
        intangible fixed assets/4688},
      {Ssapc/Social securities and\\pension costs/7860},
      {Was/Wages and salaries/35627},
      {Ooe/Other operating expenses/37346},
      {Nr2/-/\Qty{Nr}-\Qty{Aadotaifa}-\Qty{Ssapc}-\Qty{Was}-\Qty{Ooe}},
      {Oi/Other income/47},
      {Ibiiieait/Income before interest income,\\interest expense and
        income taxes/\Qty{Nr2}+\Qty{Oi}},
      {Fe/Finance expense/561},
      {Ofr/Other financial results/2533},
      {Ibiiieait2/-/\Qty{Ibiiieait}-\Qty{Fe}-\Qty{Ofr}},
      {Fi/Finance income/204},
      {Ibit/Income before income taxes/\Qty{Ibiiieait2}+\Qty{Fi}},
      {It/Income taxes/21134},
      {Niftp/Net income for the period/\Qty{Ibit}-\Qty{It}},
      {Octa/Other currency\\translation adjustments/785},
      {Tci/Total comprehensive income/\Qty{Niftp}+\Qty{Octa}}
    },
  }

  \definecolor{mygreen}{RGB}{9,192,82}
  \tikzset{
    cost node/.style={
      overlay,
      align=flush center,
      node font=\footnotesize\sffamily\bfseries,
      inner sep=0,
      node contents={%
        {\mdseries€\,\num{\Qty{#1}}}\\
        \Lab{#1}\vphantom{g}%
      },
    },
    white hash/.style={
      draw=none,fill=none,
      pattern={Lines[angle=60,line width=2pt,distance=4pt]},
      pattern color=white,
    },
    line sep/.style={draw=white,line width=1pt},
    left label/.style={left=#1,align=flush right,anchor=north east},
    right label/.style={right=#1,align=flush left},
    right label hashed/.style={
      right=1mm of $(#1.left)!.5!(#1-old.left)$,align=flush left,
    },
    left label hashed/.style={
      left=1mm of $(#1.right)!.5!(#1-old.right)$,align=flush right,
    },
  }

  \newcommand\turnandstop[1]{
    \sankeyturn[green to greenwhite]{#1}{-90}
    \sankeynode{as=#1,name=#1-e,at={(#1 -| Coi)}}
    \sankeyoutin[greenwhite to white]{#1}{#1-e}
    \node[cost node=#1,left label={1mm of #1-e.right}];
  }

  \begin{sankeydiagram}%[debug]
    \sankeyset{
      ratio=28em/1000000,
      minimum radius=2cm,
      start style=none,
      every node/.style={angle=-90},
      % default fill and draw styles
      fill/.style={
        line width=0pt,
        fill=mygreen,
      },
      draw/.style={draw=none},
      % specific fill and draw styles
      green to greenwhite/.style={
        fill/.style={
          line width=0pt,
          right color=mygreen,
          left color=mygreen!20!white,
        }
      },
      greenwhite to white/.style={
        fill/.style={
          line width=0pt,
          right color=mygreen!20!white,
          left color=mygreen!5!white,
        }
      },
      dashed/.style={draw/.style={draw=mygreen,dashed}},
    }

    \coordinate (top) at (0,2em);

    \sankeynodestart{name=Pf,quantity=\Qty{Pf}}
    \node[cost node=Pf,above=.5em of Pf.center];

    \sankeynodestart{name=Sog,quantity=\Qty{Sog},
      right={4em of Pf.left},anchor=right}
    \node[cost node=Sog,above=.5em of Sog.center];

    \sankeynodestart{name=Sf,quantity=\Qty{Sf},
      right={2em of Sog.left},anchor=right}
    \node[cost node=Sf,above=.5em of Sf.center];

    \sankeynodestart{name=Os,quantity=\Qty{Os},
      right={2em of Sf.left},anchor=right}
    \node[cost node=Os,above=.5em of Os.center];

    \sankeynode{
      name=R,quantity=\Qty{R},below={10em of Sf},
      forked={\Qty{Os}/Os-a,\Qty{Sf}/Sf-a,\Qty{Sog}/Sog-a,\Qty{Pf}/Pf-a},
    }

    \foreach \nodename in {Pf,Sog,Sf,Os}{
      \sankeyoutin[fill/.style={top color=white,bottom color=mygreen}]
      {\nodename}{\nodename-a}
    }

    \sankeyadvance{R}{1em}
    \node[cost node=R,right label hashed=R];

    \sankeyfork{R}{\Qty{Ciffi}/Ciffi,\Qty{Nr}/Nr,\Qty{Coi}/Coi}

    \sankeyturnleft[minimum radius=1.cm]{Ciffi}{90}
    \node[cost node=Ciffi,at={([shift={(1mm,0)}]Ciffi.center)},rotate=-90,
    anchor=south,align=flush left,node font=\scriptsize\sffamily\bfseries];

    \sankeyturnright[green to greenwhite]{Coi}{90}
    \sankeyadvance[greenwhite to white]{Coi}{1em}
    \node[cost node=Coi,left={1mm of [yshift=.75ex]Coi.left},
    align=flush right,anchor=north east,overlay];

    \sankeyadvance{Nr}{9em}
    \sankeyadvance{Nr}{1em}
    \node[cost node=Nr,left label hashed=Nr,
    node font=\large\sffamily\bfseries];

    \sankeyfork{Nr}{\Qty{Nr2}/Nr2,\Qty{Ooe}/Ooe,
      \Qty{Was}/Was,\Qty{Ssapc}/Ssapc,\Qty{Aadotaifa}/Aadotaifa}

    \turnandstop{Aadotaifa}

    \sankeyadvance{Ssapc}{5em}
    \turnandstop{Ssapc}

    \sankeyadvance{Was}{9em}
    \turnandstop{Was}

    \sankeyadvance{Ooe}{12em}
    \turnandstop{Ooe}

    \sankeyadvance{Nr2}{15em}
    \sankeynode{name=Ibiiieait,quantity=\Qty{Ibiiieait},
      anchor=right,at={(Nr2.right)},
      forked={\Qty{Oi}/Oi,\Qty{Nr2}/Nr2-e}}

    \sankeyturnleftbackward[minimum radius=1cm,dashed]{Oi}{90}
    \node[cost node=Oi,right label=1mm of Oi.left];

    \sankeyadvance{Ibiiieait}{1em}
    \node[cost node=Ibiiieait,right label hashed=Ibiiieait];

    \sankeyfork{Ibiiieait}
    {\Qty{Ibiiieait2}/Ibiiieait2,\Qty{Ofr}/Ofr,\Qty{Fe}/Fe}

    \turnandstop{Fe}

    \sankeyadvance{Ofr}{3em}
    \turnandstop{Ofr}

    \sankeyadvance{Ibiiieait2}{6em}
    \sankeynode{name=Ibit,quantity={\Qty{Ibiiieait2}+\Qty{Fi}},
      anchor=right,at={(Ibiiieait2.right)},
      forked={\Qty{Fi}/Fi,\Qty{Ibiiieait2}/Ibiiieait2-e}}

    \sankeyturnleftbackward[minimum radius=1cm,dashed]{Fi}{90}
    \node[cost node=Fi,right label=1mm of Fi.left];

    \sankeyadvance{Ibit}{1em}
    \node[cost node=Ibit,right label hashed=Ibit];

    \sankeyfork{Ibit}{\Qty{Niftp}/Niftp,\Qty{It}/It}

    \turnandstop{It}

    \sankeyadvance{Niftp}{6em}

    \sankeyadvance{Niftp}{1em}
    \node[cost node=Niftp,right label hashed=Niftp];

    \sankeynode{name=Tci,quantity=\Qty{Niftp}+\Qty{Octa},
      anchor=right,below={6em of Niftp.right},
      forked={\Qty{Octa}/Octa,\Qty{Niftp}/Niftp-e}}
    \sankeyoutin{Niftp}{Niftp-e}

    \sankeyturnleftbackward[minimum radius=1cm]{Octa}{90}
    \node[cost node=Octa,right label=1mm of Octa.left];

    \sankeyadvance{Tci}{1em}
    \node[cost node=Tci,right label hashed=Tci];

    \newcommand\hashband[1]{
      \draw[line sep] (#1-old.right) -- (#1-old.left);
      \draw[line sep] (#1.right) -- (#1.left);
      \path[white hash] (#1-old.right) rectangle (#1.left);
    }

    \foreach \nodename in {R,Nr,Nr,Ibiiieait,Ibit,Niftp,Tci}{
      \hashband{\nodename}
    }

  \end{sankeydiagram}
\end{tikzpicture}
%</example4>
% \fi
%
%^^A % ------------------------------------------------------------
% \clearpage
% \section{Cycles -- paper and board}
%^^A % ------------------------------------------------------------
%
% \changes{v3.1.0}{2026/11/29}{Add two examples with cycles (paper and
%   board, urban water)}
%
% \embedfile[mimetype=text/plain]{sankey-example-paper.tex}
%
% \begin{figure}
%   \centering
%   {\MakePercentComment\input{sankey-example-paper.tex}}
%   \caption{Paper and board cycle in Europe (percentages of the
%     production; illustrative orders of magnitude)}
%   \label{fig:paper-example}
% \end{figure}
%
% A Sankey diagram may contain cycles. This example shows the paper and
% board industry in Europe in three stages: the paper mills, the use of
% the products, and the collection and sorting of used paper. The
% quantities are percentages of the production. They are orders of
% magnitude given for illustration only, not reference data.
%
% Each value is written only once, in the \code{def data} list (as in
% \code{sankey-example4.tex}). The other values, including the total of
% each stage, are computed from them with \code{\Qty}. A stage is drawn
% by the \code{\stage} macro of the example: a forked node for the
% inputs, a band of fixed length, then a \code{\sankeyfork} for the
% outputs. The three stages are placed on a circle and linked by
% \code{\sankeydubins}. The \code{flow} style, with a color as its
% argument, redefines \code{fill/.style} in one go (\code|flow=virgin|).
% The \code{\foreach} loops of \code{\stage} draw all the inputs, then all
% the outputs, from the lists of the call. The flows that return to the stage which they
% come from (broke, reuse, re-sorted paper) are loops: each one leaves
% its stage with a left turn and returns with a left turn, so it does not
% cross it. A flow changes color only when it goes through a stage, splits
% or merges.
%
% The labels are placed by two macros defined in the example. The
% \code{\flowlabel} macro computes again the Dubins path of the center of
% a band, without drawing it, and puts the label at a given position
% along it (with the \code{markings} decoration), outside the band. The
% \code{\iolabel} macro puts the label of an input or of an output in the
% extension of the node. The \code{minimum radius} key is shared with
% \code{\flowlabel} by the \code{\minr} macro. Pitfalls: no comma after
% the last item of the \code{def data} list, and a label that contains a
% comma must be enclosed in braces.
%
% See figure~\vref{fig:paper-example}. The
% \code{sankey-example-paper.tex} file contains the following code and
% is an attachment of the current PDF document.
%
% \lstinputlisting[style=LaTeXsmall]{sankey-example-paper.tex}
%
% \iffalse
%<*example-paper>
\begin{tikzpicture}
  \sisetup{detect-all}
  % storage of labels and quantities (as in sankey-example4.tex)
  \newcommand\LabSet[2]{% flow name, label
    \expandafter\def\csname#1@Lab\endcsname{#2}}
  \newcommand\Lab[1]{\csname#1@Lab\endcsname}
  \newcommand\QtySet[2]{% flow name, quantity
    \expandafter\edef\csname#1@Qty\endcsname{\fpeval{#2}}}
  \newcommand\Qty[1]{\csname#1@Qty\endcsname}
  % data: percentages of the paper and board production
  % (orders of magnitude for Europe)
  \sankeyset{
    def data/.code args={#1/#2/#3}{\LabSet{#1}{#2}\QtySet{#1}{#3}},
    def data/.list={
      {virgin/virgin fibres/45},
      {recovered/recovered\\fibres/58},
      {broke/broke/7},
      {loss/losses/3},
      {product/products/\Qty{virgin}+\Qty{recovered}-\Qty{loss}},
      {reuse/reuse/5},
      {stock/{stock (books,\\archives)}/5},
      {notcoll/{not collected\\(incineration, landfill)}/30},
      {coll/used paper\\collected/\Qty{product}-\Qty{stock}-\Qty{notcoll}},
      {resort/re-sorted/3},
      {reject/net exports\\and sorting\\rejects/\Qty{coll}-\Qty{recovered}},
      {mills/paper mills/\Qty{broke}+\Qty{recovered}+\Qty{virgin}},
      {use/use/\Qty{reuse}+\Qty{product}},
      {sort/collection\\and sorting/\Qty{resort}+\Qty{coll}}
    },
  }
  \begin{sankeydiagram}
    \def\minr{3mm}
    \colorlet{stage}{black!25}
    \colorlet{virgin}{green!50!black!45}
    \colorlet{fibre}{brown!45}
    \colorlet{loop}{orange!70}
    \colorlet{stock}{blue!30}
    \colorlet{loss}{red!45}
    \sankeyset{
      ratio=1cm/60,minimum radius=\minr,
      start style=simple,end style=arrow,
      draw/.style={draw=black!60,line width=.3pt},
      flow/.style={fill/.style={fill=#1,draw=#1,line width=0pt}},
    }
    \tikzset{
      txt/.style={font=\scriptsize\sffamily,align=center,inner sep=1pt},
      stage name/.style={txt,font=\footnotesize\sffamily\bfseries},
      lab/.style={txt,node contents={\Lab{#1}\\\qty{\Qty{#1}}{\percent}}},
    }
    \def\R{3.3cm}
    \def\L{1.8cm}
    \def\gap{4mm}
    % pairs (quantity/name) of a list of triplets (quantity/name/color)
    \newcommand\pairs[2]{% triplets, macro to define
      \def#2{}
      \foreach \q/\n/\c in {#1}{\xdef#2{#2\ifx#2\empty\else,\fi\q/\n}}}
    % length before an input or after an output: none for the internal
    % loops (color loop), which are then as short as possible
    \newcommand\gapof[1]{\ifnum\pdfstrcmp{#1}{loop}=0 0mm\else\gap\fi}
    % a stage: node name, data name, angle, position, input triplets,
    % output triplets
    \newcommand\stage[6]{
      \pairs{#5}\ins
      \pairs{#6}\outs
      \sankeynode{name=#1,quantity=\Qty{#2},angle=#3,at={(#4)},
        forked/.expand once=\ins}
      \foreach \q/\n/\c in {#5}{\sankeyadvance*[flow=\c]{\n}{\gapof{\c}}}
      \sankeyadvance[flow=stage]{#1}{\L}
      \pgfmathsetmacro\rot{cos(#3)<0 ? #3-180 : #3}
      \node[stage name,rotate=\rot] at ($(#1-old.center)!.5!(#1.center)$)
        {\Lab{#2}};
      \edef\tmp{\noexpand\sankeyfork{#1}{\outs}}\tmp
      \foreach \q/\n/\c in {#6}{\sankeyadvance[flow=\c]{\n}{\gapof{\c}}}
    }
    \stage{P}{mills}{0}{-90:\R}
      {\Qty{broke}/Pbrokein/loop,\Qty{recovered}/Precin/fibre,
        \Qty{virgin}/Pvirgin/virgin}
      {\Qty{broke}/Pbroke/loop,\Qty{product}/Pprod/fibre,
        \Qty{loss}/Ploss/loss}
    \stage{U}{use}{120}{30:\R}
      {\Qty{reuse}/Ureusein/loop,\Qty{product}/Uprodin/fibre}
      {\Qty{reuse}/Ureuse/loop,\Qty{coll}/Ucoll/fibre,
        \Qty{stock}+\Qty{notcoll}/Uout/loss}
    \stage{C}{sort}{240}{150:\R}
      {\Qty{resort}/Crejin/loop,\Qty{coll}/Ccollin/fibre}
      {\Qty{resort}/Crej/loop,\Qty{recovered}/Crec/fibre,
        \Qty{reject}/Cout/loss}
    % links between stages
    \sankeydubins[flow=fibre]{Pprod}{Uprodin}
    \sankeydubins[flow=fibre]{Ucoll}{Ccollin}
    \sankeydubins[flow=fibre]{Crec}{Precin}
    % internal loops
    \sankeyset{flow=loop}
    \foreach \o/\i in {Pbroke/Pbrokein,Ureuse/Ureusein,Crej/Crejin}{
      \sankeyturnleft{\o}{90}
      \sankeyturnleft*{\i}{90}
      \sankeydubins{\o}{\i}
    }
    % input
    \sankeyset{flow=virgin}
    \sankeyturnright*{Pvirgin}{90}
    \sankeyadvance*{Pvirgin}{1cm}
    \sankeystart{Pvirgin}
    % outputs
    \sankeyset{flow=loss}
    \foreach \n in {Ploss,Cout}{
      \sankeyturnright{\n}{90}
      \sankeyadvance{\n}{1cm}
      \sankeyend{\n}
    }
    \sankeyturnright{Uout}{60}
    \sankeyfork{Uout}{\Qty{stock}/Ustock,\Qty{notcoll}/Unot}
    \sankeyturnright{Unot}{30}
    \sankeyadvance{Unot}{1cm}
    \sankeyend{Unot}
    \sankeyturnleft[flow=stock]{Ustock}{30}
    \sankeyadvance[flow=stock]{Ustock}{1cm}
    \sankeyend[flow=stock]{Ustock}
    % labels
    % label of a flow (outside the band, at the middle of a Dubins
    % link): position, from, to, data name, anchor
    \newcommand\flowlabel[5][.5]{
      \path[decorate,decoration={markings,mark=at position #1 with
        {\node at (0,{-.5*\sankeyqtytolen{\Qty{#4}}pt-1mm})
          [lab=#4,anchor=#5];}}]
        (#2.center) \dubinspath{
          start point=#2.center,start angle=\sankeygetnodeorient{#2},
          end point=#3.center,end angle=\sankeygetnodeorient{#3},
          minimum radius=\minr+.5*\sankeyqtytolen{\Qty{#4}}pt};
    }
    \flowlabel{Pprod}{Uprodin}{product}{150}
    \flowlabel{Ucoll}{Ccollin}{coll}{270}
    \flowlabel{Crec}{Precin}{recovered}{30}
    \flowlabel{Pbroke}{Pbrokein}{broke}{270}
    \flowlabel{Ureuse}{Ureusein}{reuse}{30}
    \flowlabel{Crej}{Crejin}{resort}{150}
    % label of an input (#2=180) or an output (#2=0): distance,
    % node name, data name
    \newcommand\iolabel[4][2.5mm]{
      \pgfmathtruncatemacro\a{\sankeygetnodeorient{#3}+(#2)}
      \pgfmathtruncatemacro\b{\a+180}
      \node at ([shift={(\a:#1)}]#3.center) [lab=#4,anchor=\b];
    }
    \iolabel{180}{Pvirgin}{virgin}
    \iolabel{0}{Ploss}{loss}
    \iolabel{0}{Cout}{reject}
    \iolabel{0}{Unot}{notcoll}
    \iolabel{0}{Ustock}{stock}
  \end{sankeydiagram}
\end{tikzpicture}
%</example-paper>
% \fi
%
%^^A % ------------------------------------------------------------
% \clearpage
% \section{Cycles -- urban water}
%^^A % ------------------------------------------------------------
%
% \embedfile[mimetype=text/plain]{sankey-example-water.tex}
%
% \begin{figure}
%   \centering
%   \makebox[\linewidth]{\MakePercentComment\input{sankey-example-water.tex}}
%   \caption{Urban water cycle (flows in \unit{\cubic\metre\per\day} for
%     a city of about \num{400000} inhabitants; illustrative orders of
%     magnitude)}
%   \label{fig:water-example}
% \end{figure}
%
% This second example uses the same techniques for the water cycle of a
% city of about \num{400000} inhabitants, in four stages: the river, the
% drinking water treatment, the network and its users, and the
% wastewater treatment. Two loops return to their own stage (the filter
% backwash and the sludge recirculation). The river enters and leaves in
% a straight line. The flows (in \unit{\cubic\metre\per\day}) are orders
% of magnitude given for illustration only. For instance, the leaks of
% the network are \qty{20}{\percent} of the drinking water, which is
% close to the French average.
%
% The coding tips are those of the previous example. The macros are the
% same, except that the
% \code{\stage} macro uses the name of the node as the name of the data
% and that \code{\flowlabel} can put a label inside the loop instead of
% outside (the \code{\side} macro is \code{1} instead of \code{-1}), as
% for the treated water. The \code{\iolabel} macro has an optional
% argument to change the distance of the label. The figure is a little
% wider than the text: it is centered in a box of the width of the text
% and overflows into the margins.
%
% See figure~\vref{fig:water-example}. The
% \code{sankey-example-water.tex} file contains the following code and
% is an attachment of the current PDF document.
%
% \lstinputlisting[style=LaTeXsmall]{sankey-example-water.tex}
%
% \iffalse
%<*example-water>
\begin{tikzpicture}
  \sisetup{detect-all}
  \sisetup{group-separator={\,},group-minimum-digits=4,per-mode=symbol}
  % storage of labels and quantities (as in sankey-example4.tex)
  \newcommand\LabSet[2]{% flow name, label
    \expandafter\def\csname#1@Lab\endcsname{#2}}
  \newcommand\Lab[1]{\csname#1@Lab\endcsname}
  \newcommand\QtySet[2]{% flow name, quantity
    \expandafter\edef\csname#1@Qty\endcsname{\fpeval{#2}}}
  \newcommand\Qty[1]{\csname#1@Qty\endcsname}
  % data: daily flows (m3/d) of a city of about 400,000 inhabitants
  % (orders of magnitude)
  \sankeyset{
    def data/.code args={#1/#2/#3}{\LabSet{#1}{#2}\QtySet{#1}{#3}},
    def data/.list={
      {withdrawal/withdrawal/100000},
      {backwash/filter backwash/3000},
      {drinking/drinking water/\Qty{withdrawal}},
      {leaks/network leaks/20000},
      {use/{consumption,\\evaporation}/10000},
      {waste/wastewater/\Qty{drinking}-\Qty{leaks}-\Qty{use}},
      {rain/rainwater\\(combined sewer)/25000},
      {sludgerec/sludge recirculation/60000},
      {sludge/excess\\sludge/1000},
      {treated/treated water/\Qty{waste}+\Qty{rain}-\Qty{sludge}},
      {upstream/upstream\\flow/300000},
      {downstream/downstream\\flow/
        \Qty{treated}+\Qty{upstream}-\Qty{withdrawal}},
      {T/drinking water\\treatment/
        \Qty{backwash}+\Qty{withdrawal}},
      {U/network\\and users/\Qty{drinking}},
      {S/wastewater\\treatment/\Qty{sludgerec}+\Qty{waste}+\Qty{rain}},
      {M/river/\Qty{treated}+\Qty{upstream}}
    },
  }
  \begin{sankeydiagram}
    \def\minr{3mm}
    \colorlet{stage}{black!25}
    \colorlet{raw}{cyan!35}
    \colorlet{drinking}{blue!35}
    \colorlet{waste}{brown!45}
    \colorlet{treated}{teal!35}
    \colorlet{loop}{orange!70}
    \colorlet{loss}{red!45}
    \sankeyset{
      ratio=1cm/100000,minimum radius=\minr,
      start style=simple,end style=arrow,
      draw/.style={draw=black!60,line width=.3pt},
      flow/.style={fill/.style={fill=#1,draw=#1,line width=0pt}},
    }
    \tikzset{
      txt/.style={font=\scriptsize\sffamily,align=center,inner sep=1pt},
      stage name/.style={txt,font=\scriptsize\sffamily\bfseries},
      lab/.style={txt,
        node contents={\Lab{#1}\\\qty{\Qty{#1}}{\cubic\metre\per\day}}},
    }
    \def\R{5cm}
    \def\L{2cm}
    \def\gap{6mm}
    % pairs (quantity/name) of a list of triplets (quantity/name/color)
    \newcommand\pairs[2]{% triplets, macro to define
      \def#2{}
      \foreach \q/\n/\c in {#1}{\xdef#2{#2\ifx#2\empty\else,\fi\q/\n}}}
    % length before an input or after an output: none for the internal
    % loops (color loop), which are then as short as possible
    \newcommand\gapof[1]{\ifnum\pdfstrcmp{#1}{loop}=0 0mm\else\gap\fi}
    % a stage: node (and data) name, angle, position, input triplets,
    % output triplets
    \newcommand\stage[5]{
      \pairs{#4}\ins
      \pairs{#5}\outs
      \sankeynode{name=#1,quantity=\Qty{#1},angle=#2,at={(#3)},
        forked/.expand once=\ins}
      \foreach \q/\n/\c in {#4}{\sankeyadvance*[flow=\c]{\n}{\gapof{\c}}}
      \sankeyadvance[flow=stage]{#1}{\L}
      \pgfmathsetmacro\rot{or(cos(#2)<-0.01,sin(#2)<-0.99) ? #2-180 : #2}
      \node[stage name,rotate=\rot] at ($(#1-old.center)!.5!(#1.center)$)
        {\Lab{#1}};
      \edef\tmp{\noexpand\sankeyfork{#1}{\outs}}\tmp
      \foreach \q/\n/\c in {#5}{\sankeyadvance[flow=\c]{\n}{\gapof{\c}}}
    }
    \stage{T}{0}{-90:\R}
      {\Qty{backwash}/Tloopin/loop,\Qty{withdrawal}/Tin/raw}
      {\Qty{backwash}/Tloop/loop,\Qty{drinking}/Tout/drinking}
    \stage{U}{90}{0:\R}
      {\Qty{drinking}/Uin/drinking}
      {\Qty{waste}/Uout/waste,\Qty{use}+\Qty{leaks}/Uloss/loss}
    \stage{S}{180}{90:\R}
      {\Qty{sludgerec}/Sloopin/loop,\Qty{waste}/Sin/waste,
        \Qty{rain}/Srain/raw}
      {\Qty{sludgerec}/Sloop/loop,\Qty{treated}/Sout/treated,
        \Qty{sludge}/Ssludge/loss}
    \stage{M}{270}{180:\R}
      {\Qty{treated}/Min/treated,\Qty{upstream}/Mup/raw}
      {\Qty{withdrawal}/Mout/raw,\Qty{downstream}/Mdown/raw}
    % links between stages
    \sankeydubins[flow=drinking]{Tout}{Uin}
    \sankeydubins[flow=waste]{Uout}{Sin}
    \sankeydubins[flow=treated]{Sout}{Min}
    \sankeydubins[flow=raw]{Mout}{Tin}
    % internal loops
    \sankeyset{flow=loop}
    \foreach \o/\i in {Tloop/Tloopin,Sloop/Sloopin}{
      \sankeyturnleft{\o}{90}
      \sankeyturnleft*{\i}{90}
      \sankeydubins{\o}{\i}
    }
    % inputs
    \sankeyset{flow=raw}
    \sankeyturnright*{Srain}{90}
    \sankeyadvance*{Srain}{1cm}
    \sankeystart{Srain}
    \sankeyadvance*{Mup}{2cm}
    \sankeystart{Mup}
    % outputs
    \sankeyset{flow=loss}
    \sankeyturnright{Uloss}{60}
    \sankeyfork{Uloss}{\Qty{use}/Uuse,\Qty{leaks}/Uleak}
    \sankeyturnright{Uleak}{30}
    \sankeyadvance{Uleak}{1cm}
    \sankeyend{Uleak}
    \sankeyturnleft{Uuse}{30}
    \sankeyadvance{Uuse}{1cm}
    \sankeyend{Uuse}
    \sankeyturnright{Ssludge}{90}
    \sankeyadvance{Ssludge}{1cm}
    \sankeyend{Ssludge}
    \sankeyset{flow=raw}
    \sankeyadvance{Mdown}{2cm}
    \sankeyend{Mdown}
    % labels
    % label of a flow (outside the band, or inside if \side is 1, at
    % the middle of a Dubins link): position, from, to, data name, anchor
    \def\side{-1}
    \newcommand\flowlabel[5][.5]{
      \path[decorate,decoration={markings,mark=at position #1 with
        {\node at (0,{\side*(.5*\sankeyqtytolen{\Qty{#4}}pt+1mm)})
          [lab=#4,anchor=#5];}}]
        (#2.center) \dubinspath{
          start point=#2.center,start angle=\sankeygetnodeorient{#2},
          end point=#3.center,end angle=\sankeygetnodeorient{#3},
          minimum radius=\minr+.5*\sankeyqtytolen{\Qty{#4}}pt};
    }
    \flowlabel{Tout}{Uin}{drinking}{135}
    \flowlabel{Uout}{Sin}{waste}{225}
    {\def\side{1}\flowlabel[.85]{Sout}{Min}{treated}{180}}
    \flowlabel{Mout}{Tin}{withdrawal}{45}
    \flowlabel{Tloop}{Tloopin}{backwash}{270}
    \flowlabel{Sloop}{Sloopin}{sludgerec}{90}
    % label of an input (#2=180) or an output (#2=0): distance,
    % node name, data name
    \newcommand\iolabel[4][2.5mm]{
      \pgfmathtruncatemacro\a{\sankeygetnodeorient{#3}+(#2)}
      \pgfmathtruncatemacro\b{\a+180}
      \node at ([shift={(\a:#1)}]#3.center) [lab=#4,anchor=\b];
    }
    \iolabel{180}{Srain}{rain}
    \iolabel{0}{Uleak}{leaks}
    \iolabel{0}{Uuse}{use}
    \iolabel{0}{Ssludge}{sludge}
    \iolabel{180}{Mup}{upstream}
    \iolabel[6mm]{0}{Mdown}{downstream}
  \end{sankeydiagram}
\end{tikzpicture}
%</example-water>
% \fi
%
% \clearpage
%
% \StopEventually{}
%^^A % ------------------------------------------------------------
%
% \manualparts
%
% \part{Installation \& Implementation}
% \label{implementation}
%^^A % ------------------------------------------------------------
%
% {
%   \setlength{\parskip}{0pt}
%   \localtableofcontents
% }
%
% An AI assistant was used to help develop and debug the code and the
% documentation of this package.
%
% \changes{v3.0.1}{2022/02/04}{Fix options used by the new version of \protect\code{siunitx} package}
%
%^^A % ------------------------------------------------------------
% \section{Compiling \ttintitle{sankey}}
%^^A % ------------------------------------------------------------
%
% \changes{v3.0.1}{2022/02/04}{Add instructions for compiling and installing the
% package}
%
% To produce the \code{sankey} package:
%
% \begin{lstlisting}[style=bashsmall]
% pdflatex sankey.ins # or 'latex sankey.ins'
% \end{lstlisting}
%
% To finish the installation you have to move the
% \code{tikzlibrarydubins.code.tex} and
% \code{sankey.sty} files into a directory searched by \LaTeX.
% 
% To compile the \code{sankey} documentation (the
% \code{sankey.pdf} file):
%
% \begin{lstlisting}[style=bashsmall]
% pdflatex sankey.dtx
% makeindex -s gind.ist -o sankey.ind sankey.idx
% pdflatex sankey.dtx
% makeindex -s gind.ist -o sankey.ind sankey.idx
% pdflatex sankey.dtx
% pdflatex sankey.dtx
% \end{lstlisting}
%
%
%^^A % ------------------------------------------------------------
% \section{The \ttintitle{sankey.sty} file}
%^^A % ------------------------------------------------------------
%
% This section documents the implementation of the \code{sankey}
% package.
%
% \paragraph{Plan of the file.} After the declarations of the required
% packages and of the PGF layers, the code is organized as follows.
% \begin{enumerate}
% \item \emph{Fields}: setter and getter macros storing the quantity and
%   the orientation of each Sankey node and the start and end paths.
% \item The \code{sankey node} TikZ shape.
% \item \emph{Keys}: the options of a diagram (path \code{/sankey}) and
%   the parameters of a node (path \code{/sankey/node parameters}).
% \item \emph{Internal macros}: small helpers, then the macros which
%   create a Sankey node and its start and end lanes.
% \item \emph{User macros}, defined with the \code{snk@} prefix, and the
%   \code{sankeydiagram} environment which gives them their public names.
% \item The predefined start and end styles.
% \end{enumerate}
%
% \paragraph{Naming conventions.} Every internal macro, field or TikZ
% name starts with \code{snk@} (or \code{@snk@} for the macros created
% by the fields). The macros of the user interface are first defined
% \emph{globally} with the \code{snk@} prefix (for instance
% \code{\snk@sankeynode}). The \code{sankeydiagram} environment copies
% them \emph{locally} (with \code{\NewCommandCopy}) under their public
% names (\code{\sankeynode}, \dots). Thus the public macros exist only
% inside a diagram and cannot clash with other packages outside it. The
% only exceptions are \code{\sankeyset} and the getters
% \code{\sankeygetnodeqty} and \code{\sankeygetnodeorient}, which are
% always available.
%
% \paragraph{Implicit parameters.} The macros do not pass all their data
% through arguments. While a node is being created (and by the macros
% which move a node), the following macros play the role of local
% variables, set by the keys of the node parameters:
% \begin{itemize}
% \item \code{\name}, \code{\qty}, \code{\orient} and \code{\pos}: the
%   name, the quantity, the orientation (in degrees) and the position of
%   the node;
% \item \code{\snk@anchor}: the anchor of the node placed at \code{\pos};
% \item \code{\snk@listofforks} and \code{\snk@forkanchor}: the forks of
%   the node and the anchor used to place them.
% \end{itemize}
% The diagram options are stored in \code{\snk@currot} (offset angle,
% see \code{\snk@getrotate}), \code{\snk@minradius}, \code{\snk@prefer},
% \code{\snk@stepoutin}, \code{\snk@startstyle}, \code{\snk@endstyle} and
% in the ratio macros \code{\snk@totalqty} and \code{\snk@totallen}.
% Every user macro opens a group (\code{\begingroup}) before applying its
% options, so that these values, set by its optional argument, are
% restored on exit. On the contrary, the quantity and the orientation of
% a Sankey node are stored \emph{globally} (with \code{\xdef}), because
% the node must outlive the group of the macro which created it.
%
% \paragraph{What \ttintitle{sankeynode} does.} The main macro
% \code{\snk@sankeynode} proceeds in the following steps:
% \begin{enumerate}
% \item it applies its optional argument (diagram options), then the
%   node parameters (the \code{@initial parameters} style, the
%   \code{every node} style and the user parameters);
% \item \code{\snk@makenode} stores the quantity and the orientation of
%   the node and creates the TikZ node;
% \item \code{\snk@makeforkednode} creates the sub-nodes of a forked
%   node (if any) and shifts the whole fork if requested;
% \item if the \code{start} (or \code{end}) parameter is true, it fills
%   and draws the start (or end) of flow;
% \item finally, \code{\snk@show@debug} draws the debug information if
%   the \code{debug} key is true.
% \end{enumerate}
% The other macros (moves, turns, \code{\sankeyfork}, \dots) are built
% on this one: they compute a new position and call \code{\sankeynode}
% to create the new node.
%
% \changes{v1.0}{2016/03/06}{First version}
% \changes{v2.0}{2021/01/27}{First public version (on \CTAN)}
% \changes{v3.0}{2021/03/14}{Better naming rule}
% \changes{v3.0}{2021/03/14}{Use \protect\code{.ins} and \protect\code{.dtx} files}
%
% \iffalse
%<*sankey>
% \fi
%
% \changes{v3.1.0}{2026/11/29}{Require a \LaTeX{} format from 2020/10/01 or later}
%
% Version information:
%
%    \begin{macrocode}
\NeedsTeXFormat{LaTeX2e}[2020/10/01]
\ProvidesPackage{sankey}[2026/11/29 v3.1.0 to draw Sankey diagrams]
%    \end{macrocode}
%
% All required packages and TikZ libraries:
%    \begin{macrocode}
\RequirePackage{xparse}
\RequirePackage{etoolbox}
\RequirePackage{xfp}
\RequirePackage{tikz}
\usetikzlibrary{
  calc,
  decorations.markings,
  positioning,
  dubins
}
%    \end{macrocode}
% 
% Declarations of PGF layers (to debug Sankey diagrams).
% \changes{v3.1.0}{2026/11/29}{The layers defined by the user are kept (the \protect\code{sankeydebug} layer is added to them)}
% If the layer list is the default one (only the \code{main} layer), the
% package installs the \code{background}, \code{main},
% \code{foreground} and \code{sankeydebug} layers (as previous versions
% did). Otherwise, the layers already defined by the user are kept and
% the \code{sankeydebug} layer is appended to them.
%
%    \begin{macrocode}
\pgfdeclarelayer{background}
\pgfdeclarelayer{foreground}
\pgfdeclarelayer{sankeydebug}
\def\snk@defaultlayers{main}
\ifdefined\pgf@layerlist
  \ifx\pgf@layerlist\snk@defaultlayers
    \pgfsetlayers{background,main,foreground,sankeydebug}
  \else
    \edef\snk@tmp{\noexpand\in@{,sankeydebug,}{,\pgf@layerlist,}}\snk@tmp
    \ifin@\else
      \edef\snk@tmp{\noexpand\pgfsetlayers{\pgf@layerlist,sankeydebug}}%
      \snk@tmp
    \fi
  \fi
\else
  \pgfsetlayers{background,main,foreground,sankeydebug}
\fi
%    \end{macrocode}
%
%
%^^A % ------------------------------------------------------------
% \subsection{Fields}
%^^A % ------------------------------------------------------------
%
% \begin{macro}{\snk@newfield}
%
% The \code{\snk@newfield} macro defines
% setter and getter macros for \emph{key}/\emph{value} pairs.
% It requires five parameters: the \emph{def} macro used to
% store a new value, the \emph{setter} macro name, the \emph{getter} macro name,
% the \emph{cs name} used by the new field (including a \texttt{\#1}
% parameter -- the \emph{key}) and the \emph{error message} (used by the getter
% macro if the key is not defined).
%
% The \emph{setter} macro requires
% two parameters: the key and the value.
% The \emph{getter} macro requires
% one parameter: the key.
%
% Each value is stored in a macro whose name is built from the \emph{cs
% name} (for instance \code{@snk@node@qty@<name>} for the quantity of the
% node \code{<name>}). A trick is used here: the \emph{cs name} is given
% with a \emph{single} \texttt{\#1}. When it is inserted in the body of
% the setter and getter (where the parameter is written \texttt{\#\#1}),
% this \texttt{\#1} is not doubled and thus becomes, after the
% definition, the first parameter of the setter or getter, that is the
% \emph{key}. The choice of the \emph{def} macro sets the scope of the
% field: \code{\xdef} for the \emph{global} and \emph{expanded} fields
% (the data of the Sankey nodes) and \code{\def} for the \emph{local}
% ones (the start and end paths).
%
%    \begin{macrocode}
\def\snk@newfield#1#2#3#4#5{
  % setter
  \def#2##1##2{\expandafter#1\csname #4\endcsname{##2}}
  % getter
  \def#3##1{%
    \ifcsdef{#4}{%
      \csname#4\endcsname%
    }{%
      \PackageError{sankey}{#5}{unknown key with \string#3}%
    }%
  }
}
%    \end{macrocode}
% \end{macro}
%
%^^A % ------------------------------------------------------------
% \subsubsection{Definition of \emph{global} and \emph{expanded} fields (using
% \ttintitle{\protect\string\xdef})}
%^^A % ------------------------------------------------------------
%
% \begin{macro}{\snk@setnodeqty}
% \begin{macro}{\sankeygetnodeqty}
% The setter and getter macros to store and retrieve
% the \emph{quantity} field associated with
% each Sankey node (the key is the name of the Sankey node).
%    \begin{macrocode}
\snk@newfield\xdef\snk@setnodeqty\sankeygetnodeqty%
{@snk@node@qty@#1}{Unknown sankey node '#1'}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% 
% \begin{macro}{\snk@setnodeorient}
% \begin{macro}{\sankeygetnodeorient}
% The setter and getter macros to store and retrieve
% the \emph{angle} (or orientation) field
% associated with each Sankey node (the key is the name of the Sankey node).
%    \begin{macrocode}
\snk@newfield\xdef\snk@setnodeorient\sankeygetnodeorient%
{@snk@node@orient@#1}{Unknown sankey node '#1'}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%^^A % ------------------------------------------------------------
% \subsubsection{Definitions of \emph{local} fields (using \ttintitle{\protect\string\def})}
%^^A % ------------------------------------------------------------
%
% \begin{macro}{\snk@setstartfill}
% \begin{macro}{\snk@getstartfill}
% \begin{macro}{\snk@setstartdraw}
% \begin{macro}{\snk@getstartdraw}
% The setter and getter macros to store and retrieve the starting fill/draw
% paths (the key is the style name).
%    \begin{macrocode}
\snk@newfield\def\snk@setstartfill\snk@getstartfill%
{@snk@start@fill@#1}{Unknown sankey start fill path #1}

\snk@newfield\def\snk@setstartdraw\snk@getstartdraw%
{@snk@start@draw@#1}{Unknown sankey start draw path #1}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% 
% \begin{macro}{\snk@setendfill}
% \begin{macro}{\snk@getendfill}
% \begin{macro}{\snk@setenddraw}
% \begin{macro}{\snk@getenddraw}
% The setter and getter macros to store and retrieve the ending fill/draw
% paths (the key is the style name).
%    \begin{macrocode}
\snk@newfield\def\snk@setendfill\snk@getendfill%
{@snk@end@fill@#1}{Unknown sankey end fill path #1}

\snk@newfield\def\snk@setenddraw\snk@getenddraw%
{@snk@end@draw@#1}{Unknown sankey end draw path #1}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%^^A % ------------------------------------------------------------
% \subsubsection{Check if a sankey node is defined}
%^^A % ------------------------------------------------------------
%
% \begin{macro}{\snk@ifnodedefined}
%
% The \code{\snk@ifnodedefined} macro checks if a Sankey
% node is defined by checking if its name is associated to
% a \emph{quantity}.
%    \begin{macrocode}
\newcommand\snk@ifnodedefined[3]{%
  \ifcsdef{@snk@node@qty@#1}{#2}{#3}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\snk@errorifnotdefined}
% The \code{\snk@errorifnotdefined} macro generates
% an error message if the Sankey node is not defined.
%    \begin{macrocode}
\newcommand\snk@errorifnotdefined[1]{%
  \snk@ifnodedefined{#1}{}%
  {\PackageError{sankey}{Unknown sankey node '#1'}{}}%
}
%    \end{macrocode}
% \end{macro}
%
%^^A % ------------------------------------------------------------
% \subsection{The \ttintitle{sankey node} shape}
%^^A % ------------------------------------------------------------
%
%
% A \code{sankey node} is defined as a TikZ node
% with a particular \emph{shape}: its width is null and its
% height matches the associated \emph{quantity}.
% This shape requires only three anchors: \code{center}, \code{left}
% and \code{right}.
% These three anchors are sufficient to use the
% \code{sankey} package. But the \code{fit} library needs
% anchors defined by a rectangular node.
%
% The shape inherits its geometry from the \code{rectangle} shape. The
% width of the node is null and its height is the length of the
% quantity, so the \code{\northeast} and \code{\southwest} corners of the
% rectangle are the two ends of the node. The \code{left} anchor is the
% \code{\northeast} corner and the \code{right} anchor is the
% \code{\southwest} corner: seen from the direction of the flow (the node
% is oriented along its \emph{angle}, the flow goes through the node
% from left to right when the angle is $0$), the \code{left} anchor is on
% the left-hand side of the flow. The other anchors are inherited from
% \code{rectangle} only for the \code{fit} library.
%
%    \begin{macrocode}
\pgfdeclareshape{sankey node}{
  \inheritsavedanchors[from=rectangle]
  \inheritanchor[from=rectangle]{center}
  \inheritanchorborder[from=rectangle]
  \anchor{left}{\pgf@process{\northeast}}
  \anchor{right}{\pgf@process{\southwest}}
  % compatibility with 'fit' library
  \inheritanchor[from=rectangle]{west}
  \inheritanchor[from=rectangle]{east}
  \inheritanchor[from=rectangle]{north}
  \inheritanchor[from=rectangle]{south}
  \inheritanchor[from=rectangle]{north west}
  \inheritanchor[from=rectangle]{south east}
  \inheritanchor[from=rectangle]{north east}
  \inheritanchor[from=rectangle]{south west}
}
%    \end{macrocode}
%
%^^A % ------------------------------------------------------------
% \subsection{Keys}
%^^A % ------------------------------------------------------------
%
% \begin{macro}{\sankeyset}
% The \code{sankey} package uses \code{pgfkeys} to set options via
% \emph{key=value} pairs using the \texttt{/sankey} path
% (for Sankey diagram options) and using the
% \texttt{/sankey/node parameters} path (for Sankey node parameters).
%
% The \code{\sankeyset} macro processes
% its parameter as a list of comma separated pairs of the form
% \emph{key=value} with \texttt{/sankey} as default path.
%
%    \begin{macrocode}
\pgfkeys{/sankey/.is family}
\NewDocumentCommand\sankeyset{m}{\pgfkeys{sankey,#1}}
%    \end{macrocode}
% \end{macro}
%
%^^A % ------------------------------------------------------------
% \subsubsection{Keys to define the scale}
%^^A % ------------------------------------------------------------
% \begin{macro}{\snk@totalqty}
% \begin{macro}{\snk@totallen}
% 
% The \code{ratio quantity}, \code{ratio length} and
% \code{ratio} keys define the ratio between
% \emph{flow quantity} and \emph{graphic length} (the scale).
% The \code{\snk@totalqty} and \code{\snk@totallen} macros store the values.
% All \emph{quantities} are processed by \code{\fpeval} and
% all \emph{lengths} are processed by \code{pgfmath}.
%    \begin{macrocode}
\sankeyset{
  ratio quantity/.code={\edef\snk@totalqty{\fpeval{#1}}},
  ratio quantity/.value required,
  ratio length/.code={
    \pgfmathsetmacro\snk@totallen{#1}
    \edef\snk@totallen{\snk@totallen pt}
  },
  ratio length/.value required,
  ratio/.style args={#1/#2}{
    ratio length=#1,
    ratio quantity=#2,
  },
  ratio/.value required,
}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%^^A % ------------------------------------------------------------
% \subsubsection{Rotate offset}
%^^A % ------------------------------------------------------------
%
% \begin{macro}{\snk@rotate}
% \changes{v3.1.0}{2026/11/29}{New \protect\code{auto} value (initial value) for the \protect\code{rotate} key}
%
% The \code{rotate} key stores an offset angle applied to all Sankey
% nodes (or \code{auto}). This is needed when using the \code{rotate}
% option within a \code{tikzpicture} or a \code{scope}. This TikZ
% option is only applied to coordinates and not to TikZ nodes (remember
% that Sankey nodes are TikZ nodes).
%
%    \begin{macrocode}
\sankeyset{
  rotate/.code={%
    \ifstrequal{#1}{auto}%
    {\def\snk@rotate{auto}}%
    {\edef\snk@rotate{\fpeval{#1}}}%
  },
  rotate/.value required,
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\snk@getrotate}
% \begin{macro}{\snk@currot}
% The \code{\snk@getrotate} macro stores in \code{\snk@currot} the
% offset angle to use: the value of the \code{rotate} key or, with the
% \code{auto} value, the rotation of the current TikZ transformation
% (computed from the entries $a$ and $b$ of the transformation matrix).
%
%    \begin{macrocode}
\def\snk@getrotate{%
  \ifdefstring{\snk@rotate}{auto}{%
    \pgfgettransformentries\snk@ta\snk@tb\snk@tc\snk@td\snk@tx\snk@ty
    \pgfmathsetmacro\snk@currot{atan2(\snk@tb,\snk@ta)}%
  }{%
    \let\snk@currot\snk@rotate
  }%
}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%^^A % ------------------------------------------------------------
% \subsubsection{Minimum radius}
%^^A % ------------------------------------------------------------
%
% \begin{macro}{\snk@minradius}
%
% The \code{minimum radius} key processes the minimum radius
% of curvature by \code{pgfmath} then stores it in
% the \code{\snk@minradius} macro.
%    \begin{macrocode}
\sankeyset{
  minimum radius/.code={
    \pgfmathsetmacro\snk@minradius{#1}
    \edef\snk@minradius{\snk@minradius pt}
  },
  minimum radius/.value required,
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\snk@prefer}
% \changes{v3.1.0}{2026/11/29}{New \protect\code{prefer} key (used by \protect\code{sankeydubins})}
% The \code{prefer} key stores in \code{\snk@prefer} the preferred side
% used by \code{\sankeydubins} to choose between two Dubins paths of the
% same length (see the \code{prefer} key of the \code{dubins} library).
%
%    \begin{macrocode}
\sankeyset{
  prefer/.is choice,
  prefer/left/.code={\def\snk@prefer{left}},
  prefer/right/.code={\def\snk@prefer{right}},
  prefer/none/.code={\def\snk@prefer{none}},
}
%    \end{macrocode}
% \end{macro}
%
%^^A % ------------------------------------------------------------
% \subsubsection{Outin step}
%^^A % ------------------------------------------------------------
%
% \begin{macro}{\snk@stepoutin}
% \changes{v3.1.0}{2026/11/29}{Fix the name of the \protect\code{outin steps} key in \protect\code{.value required}}
% The \code{outin steps} key stores its value (the number of steps used
% by \code{\sankeyoutin} to approximate the lane) in
% the \code{\snk@stepoutin} macro.
%
%    \begin{macrocode}
\sankeyset{
  outin steps/.estore in=\snk@stepoutin,
  outin steps/.value required,
}
%    \end{macrocode}
% \end{macro}
%
%^^A % ------------------------------------------------------------
% \subsubsection{Sankey debug}
%^^A % ------------------------------------------------------------
%
%
% The \code{debug} key drives the \code{sankey debug} toggle (an
% \code{etoolbox} toggle, tested by \code{\snk@show@debug}). The toggle
% is set locally (like every \code{etoolbox} toggle set without its
% global variant): it is false at the beginning of each diagram (see
% the \code{@initial options} style), and the key can be used in the
% optional argument of a macro to change it for this macro only.
%
%    \begin{macrocode}
\newtoggle{sankey debug}
\sankeyset{
  debug/.is choice,
  debug/true/.code={\toggletrue{sankey debug}},
  debug/false/.code={\togglefalse{sankey debug}},
  debug/.default=true,
}
%    \end{macrocode}
%
%^^A % ------------------------------------------------------------
% \subsubsection{Start and end styles}
%^^A % ------------------------------------------------------------
%
% \begin{macro}{\snk@startstyle}
% \begin{macro}{\snk@endstyle}
% The \code{start style} and \code{end style} keys are choices.
%
% The \code{new start style} and \code{new end style} keys
% add new option to these choices.
% They use the \code{startfill}, \code{startdraw} fields
% or the \code{endfill} and \code{enddraw}
% fields (using the style \emph{name} as key) to store the fill and draw
% paths then create a new option to install the new
% start (\code{\snk@startstyle}) or end (\code{\snk@endstyle}) style.
%
%    \begin{macrocode}
\sankeyset{
  start style/.is choice,
  end style/.is choice,
  % to define new start and end styles
  new start style/.code n args={3}{% name, fill path, draw path
    \snk@setstartfill{#1}{#2}
    \snk@setstartdraw{#1}{#3}
    \sankeyset{start style/#1/.code={\def\snk@startstyle{#1}}}
  },
  new end style/.code n args={3}{% name, fill path, draw path
    \snk@setendfill{#1}{#2}
    \snk@setenddraw{#1}{#3}
    \sankeyset{end style/#1/.code={\def\snk@endstyle{#1}}}
  },
}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%^^A % ------------------------------------------------------------
% \subsubsection{Initial parameters}
%^^A % ------------------------------------------------------------
%
% The \code{@initial options} style defines default values for
% options of Sankey diagram.  The \code{every diagram} style (initially
% empty) allows the user to choose its own default values.
%
% The \code{@initial options} and the \code{every diagram} styles are
% applied (in this order) at the beginning of each Sankey diagram, then
% the options given to the \code{sankeydiagram} environment. Thus a
% later one overrides the earlier ones. The \code{@} in the name marks
% the style as internal: the user is not expected to change it (use
% \code{every diagram} instead).
%
% The styles \code{fill} and \code{draw} are the TikZ styles used by all
% the macros to fill and draw the lanes. The \code{debug color} key
% defines a color named \code{debug color} (with \code{/utils/exec}), and
% the three \code{debug} styles use it to draw the debug information.
%
%    \begin{macrocode}
\sankeyset{
  debug color/.style={/utils/exec={\colorlet{debug color}{#1}}},
  @initial options/.style={
    ratio=1cm/10,
    minimum radius=5mm,%
    prefer=none,
    outin steps=10,
    debug=false,
    start style=none,
    end style=none,
    rotate=auto,
    % default fill/draw styles,
    fill/.style={line width=0pt,fill=white},
    draw/.style={draw=black,line width=.4pt},
    % debug color used by all debug macros
    debug color=red!75!black,
    % debug line between left and right anchors
    debug line/.style={overlay,draw=debug color,|-|},
    % debug line between center and label
    debug normal/.style={overlay,draw=debug color},
    % debug node label
    debug label/.style={
      overlay,
      draw,
      font=\ttfamily\tiny,
      text=debug color,text opacity=1,
      inner sep=.1em,
      fill=white,fill opacity=1,
      rounded corners=.1em,
      node contents={\name},
    },
    every node/.style={},
  },
  every diagram/.style={},
}

%    \end{macrocode}
%
%^^A % ------------------------------------------------------------
% \subsubsection{Sankey node parameters}
%^^A % ------------------------------------------------------------
%
% The \code{/sankey/node parameters} family defines all parameters during
% creation of Sankey node.
%
%    \begin{macrocode}
\sankeyset{node parameters/.is family}
%    \end{macrocode}
% \begin{macro}{\name}
% \begin{macro}{\qty}
% \begin{macro}{\orient}
% \begin{macro}{\pos}
%
% The \code{name}, \code{quantity}, \code{angle} and \code{at} keys use the
% \code{\name}, \code{\qty}, \code{\orient} and \code{\pos} macros
% to store the \emph{name}, the \emph{quantity}, the \emph{orientation} (or
% \emph{angle}) and the \emph{position} of a Sankey node during its
% creation.
%
% The \emph{quantity} is processed via \code{\fpeval}. The
% \emph{orientation} is normalized.
%
%    \begin{macrocode}
\sankeyset{node parameters,
  name/.estore in=\name,
  name/.value required,
  quantity/.code={\edef\qty{\fpeval{#1}}},
  quantity/.value required,
  angle/.code={\edef\orient{\snk@normalize@angle{#1}}},
  angle/.value required,
  at/.code={\snk@at{#1}},
  at/.value required,
}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\snk@at}
% \changes{v3.1.0}{2026/11/29}{The \protect\code{at} key works as in TikZ (coordinate with parentheses)}
% \changes{v3.1.0}{2026/11/29}{The old \protect\code{at} key is kept as \protect\code{deprecated at}}
% The \code{at} key works as in TikZ: its value is a TikZ coordinate
% \emph{with} parentheses. For compatibility, a value without
% parentheses is processed as by the \code{deprecated at} key (the
% \code{at} key of previous versions) with a warning.
%
%    \begin{macrocode}
\def\snk@at#1{%
  \pgfutil@ifnextchar({\snk@at@tikz}{\snk@at@old}#1\snk@at@stop
}
\def\snk@at@tikz#1\snk@at@stop{%
  \tikz@scan@one@point\pgfutil@firstofone#1\relax
  \edef\pos{\the\pgf@x,\the\pgf@y}%
}
\def\snk@at@old#1\snk@at@stop{%
  \PackageWarning{sankey}{The value of the 'at' key must be a TikZ
    coordinate with parentheses: use 'at={(#1)}' (or the 'deprecated
    at' key)}%
  \snk@getpos\pos{#1}%
}
\sankeyset{node parameters,
  deprecated at/.code={\snk@getpos\pos{#1}},
  deprecated at/.value required,
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\snk@positioning}
% \changes{v3.1.0}{2026/11/29}{New keys to place a Sankey node with the syntax of the \protect\code{positioning} TikZ library}
% The \code{above}, \code{below}, \code{left}, \code{right},
% \code{above left}, \code{above right}, \code{below left} and
% \code{below right} keys use the \code{positioning} TikZ library to
% compute the position of the new Sankey node. The
% \code{\snk@positioning} macro creates a temporary TikZ coordinate
% with the given positioning option and the \code{on grid} option
% (distances between centers), then uses its position.
%
%    \begin{macrocode}
\def\snk@positioning#1{%
  \path coordinate[on grid,#1] (snk@positioning);
  \snk@getpos\pos{snk@positioning}%
}
\sankeyset{node parameters,
  above/.code={\snk@positioning{above=#1}},
  below/.code={\snk@positioning{below=#1}},
  left/.code={\snk@positioning{left=#1}},
  right/.code={\snk@positioning{right=#1}},
  above left/.code={\snk@positioning{above left=#1}},
  above right/.code={\snk@positioning{above right=#1}},
  below left/.code={\snk@positioning{below left=#1}},
  below right/.code={\snk@positioning{below right=#1}},
}
%    \end{macrocode}
% \end{macro}
%
% The \code{as} key is just a shortcut to define the four current node
% parameters by copying them from an existing Sankey node.
%
%    \begin{macrocode}
\sankeyset{node parameters,
  as/.style={
    name=#1,
    quantity=\sankeygetnodeqty{#1},
    angle=\sankeygetnodeorient{#1},
    at={(#1.center)},
  },
  as/.value required,
}
%    \end{macrocode}
%
% \begin{macro}{\snk@anchor}
%
% The \code{anchor} key stores in the \code{\snk@anchor} macro
% the anchor name to use to create the new current Sankey node
%
%    \begin{macrocode}
\sankeyset{node parameters,
  anchor/.is choice,
  anchor/left/.code={\def\snk@anchor{left}},
  anchor/right/.code={\def\snk@anchor{right}},
  anchor/center/.code={\def\snk@anchor{center}},
  anchor/.value required,
}
%    \end{macrocode}
% \end{macro}
%
% The \code{start} and \code{end} keys drive the
% \code{sankey node start} and \code{sankey node end}
% toggles.
%
%    \begin{macrocode}
\newtoggle{sankey node start}
\newtoggle{sankey node end}
\sankeyset{node parameters,
  start/.is choice,
  start/true/.code={\toggletrue{sankey node start}},
  start/false/.code={\togglefalse{sankey node start}},
  start/.default=true,
  % 
  end/.is choice,
  end/true/.code={\toggletrue{sankey node end}},
  end/false/.code={\togglefalse{sankey node end}},
  end/.default=true,
}
%    \end{macrocode}
% \begin{macro}{\snk@listofforks}
% \begin{macro}{\snk@forkanchor}
%
% The \code{forked} and \code{fork anchor} keys store their value in the
% \code{\snk@listofforks} and \code{\snk@forkanchor} macros.
%
%    \begin{macrocode}
\sankeyset{node parameters,
  forked/.estore in=\snk@listofforks,
  forked/.value required,
  fork anchor/.estore in=\snk@forkanchor,
  fork anchor/.value required,
}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% The \code{@initial parameters} style initialises all Sankey node
% parameters at the start of the creation of a new Sankey node. Since the
% parameters are plain macros (not groups of keys), there is nothing to
% reset between two nodes except these values: this is why every node
% starts from this style. The \code{name} and \code{quantity} parameters
% have no default value: the user must give them. The \code{start} and
% \code{end} toggles are false by default (the \code{\sankeynodestart}
% and \code{\sankeynodeend} macros set them).
%
%    \begin{macrocode}
\sankeyset{node parameters,
  @initial parameters/.style={
    start=false,
    end=false,
    forked=,
    fork anchor=,
    anchor=center,
    at={(0,0)},
    angle=0,
  },
}
%    \end{macrocode}
% 
%
%^^A % ------------------------------------------------------------
% \subsubsection{Internal Tikz style}
%^^A % ------------------------------------------------------------
%
% To apply this style with TikZ, use absolute key name
% (\texttt{/sankey/@sankey node}). This style is used to create the TikZ
% node associated to a Sankey node.
%
% The style takes three arguments: the \emph{name}, the \emph{position}
% and the \emph{anchor} of the node. It selects the \code{sankey node}
% shape without any padding (\code{inner sep=0}), with a null width and
% a height given by the quantity of the node (converted to a length by
% \code{\sankeyqtytolen}), and it is invisible. The rotation is the
% orientation of the node plus the offset angle \code{\snk@currot} (a
% TikZ node is not rotated by a \code{rotate} option of the picture, see
% the \code{rotate} key). The \code{anchor} option places the given
% anchor of the node at the given position.
%
%    \begin{macrocode}
\sankeyset{
  % sankey node TikZ style
  @sankey node/.style n args={3}{% name, pos, anchor
    shape=sankey node,
    inner sep=0,
    minimum height={\sankeyqtytolen{\sankeygetnodeqty{#1}}},
    minimum width=0,
    draw=none,
    line width=0pt,
    fill=none,
    node contents={},
    rotate=\sankeygetnodeorient{#1}+\snk@currot,
    at={(#2)},
    name=#1,
    anchor=#3,
  },
}
%    \end{macrocode}
% 
%^^A % ------------------------------------------------------------
% \subsection{Internal macros}
%^^A % ------------------------------------------------------------
%
% \begin{macro}{\snk@getpos}
%
% The \code{\snk@getpos} macro extracts the position of a TikZ
% node\footnote{Thanks to Andrew Stacey \url{https://tex.stackexchange.com/a/33765/14500}}.
%
%    \begin{macrocode}
\def\snk@getpos#1#2{%
  \tikz@scan@one@point\pgfutil@firstofone(#2)\relax%
  \edef#1{\the\pgf@x,\the\pgf@y}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\snk@modulo}
% 
% The \code{\snk@modulo} macro evaluates \#1 modulo \#2 using \code{\fpeval}.
% 
%    \begin{macrocode}
\def\snk@modulo#1#2{\fpeval{#1-(floor((#1)/(#2),0)*#2)}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\snk@normalize@angle}
%
% The \code{\snk@normalize@angle} macro normalizes \#1 (an angle) between
% $-180$ and $180$ (using \code{\fpeval}).
%
%    \begin{macrocode}
\def\snk@normalize@angle#1{%
  \fpeval{\snk@modulo{(#1)+180}{360}-180}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\snk@show@debug}
%
% The \code{\snk@show@debug} macro draws debug information
% of the Sankey node named \#1 but only if the \code{sankey debug}
% toggle is true. Everything is drawn on the \code{sankeydebug}
% layer (or on the current layer if the \code{sankeydebug} layer has been
% removed from the layer list by the user). It uses the \code{/sankey/debug line},
% \code{/sankey/debug normal} and \code{/sankey/debug label} TikZ styles.
% The macro works in a group and sets \code{\name}, \code{\qty} and
% \code{\orient} itself, because it can be called from macros which have
% not set them (the debug label uses \code{\name}).
%
%    \begin{macrocode}
\def\snk@show@debug#1{% node name
  \iftoggle{sankey debug}{
    \begingroup
    \edef\name{#1}
    \edef\qty{\sankeygetnodeqty{\name}}
    \edef\orient{\sankeygetnodeorient{\name}}
    \snk@getrotate
    \def\snk@debugdraw{%
      \path[/sankey/debug line] (\name.left) -- (\name.right);
      \pgfmathsetmacro{\snk@len}{\sankeyqtytolen{\qty}/3}
      \path[/sankey/debug normal] (\name.center)
      -- ($(\name.center)!\snk@len pt!90:(\name.right)$)
      node[/sankey/debug label,rotate=\orient+90+\snk@currot,anchor=north];
    }
    \edef\snk@tmp{\noexpand\in@{,sankeydebug,}{,\pgf@layerlist,}}\snk@tmp
    \ifin@
      \begin{pgfonlayer}{sankeydebug}
        \snk@debugdraw
      \end{pgfonlayer}
    \else
      \snk@debugdraw
    \fi
    \endgroup
  }{}
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\snk@makeforkednode}
% \begin{macro}{\snk@tot}
% \begin{macro}{\snk@subnodeqty}
% \begin{macro}{\snk@subnodename}
% \begin{macro}{\snk@added@values}
%
% The \code{\snk@makeforkednode} forks a Sankey node.
% \changes{v3.1.0}{2026/11/29}{Fix the comparison of non-integer quantities in forked nodes}
%
% The list \code{\snk@listofforks} has the form
% \code{qty1/name1,qty2/name2,...}. If it is empty, the macro does
% nothing (but warns if a \code{fork anchor} is given without
% \code{forked}). Otherwise it proceeds in four steps.
% \begin{enumerate}
% \item For each \code{qty/name} pair, the \code{@add forked node} key
%   creates a coordinate named \code{name} on the segment from the
%   \code{left} anchor to the \code{right} anchor of the forked node. Its
%   position is proportional to the quantities: the center of the new
%   sub-node is at the fraction $(\mathit{tot} + \mathit{qty}/2)/\mathit{total}$ of the
%   segment, where $\mathit{total}$ is the quantity of the forked node and \code{\snk@tot} the sum of the quantities already
%   placed. The sub-node (with the same orientation as the forked node)
%   is created by \code{\sankeynode}, with \code{debug=false}, then
%   \code{\snk@tot} is updated. The \texttt{\#\#1/\#\#2} are doubled
%   because the key is defined inside a macro.
% \item The sum \code{\snk@tot} of the quantities is compared with the
%   quantity of the forked node: a warning is emitted if they differ.
% \item The \code{fork anchor} (by default the anchor used to place the
%   forked node) is the point of the forked node which must lie at the
%   position \code{\pos}. The vector \code{\snk@c} is the difference
%   between this anchor and \code{\pos}.
% \item The forked node and all its sub-nodes are created again, with
%   the \code{as} key (to copy the quantity and the orientation) and
%   shifted by \code{-\snk@c}. The nodes created in the first step were
%   only used to compute the geometry; the nodes of the same names which
%   replace them are the final ones.
% \end{enumerate}
% This macro is called by \code{\snk@sankeynode} with the
% parameters of the node, and it calls \code{\snk@sankeynode} itself:
% there is no infinite recursion because the \code{@initial parameters}
% style sets \code{forked} to empty for each new node.
%
%    \begin{macrocode}
\def\snk@makeforkednode{
  \begingroup
  \ifdefempty{\snk@listofforks}{
    \ifdefempty{\snk@forkanchor}{}{
      \PackageWarning{sankey}%
      {Can't use 'fork anchor' key without 'forked' key}
    }
  }{
    \def\snk@tot{0}
    \def\snk@added@values{}
    \sankeyset{
      @add forked node/.code args={##1/##2}{
        \coordinate (##2) at ($(\name.left)%
        !\fpeval{(\snk@tot+.5*(##1))/\qty}%
        !(\name.right)$);
        \edef\snk@orient{\orient}
        \sankeynode[debug=false]
        {name=##2,quantity=##1,at=(##2),angle=\snk@orient}
        \edef\snk@tot{\fpeval{\snk@tot+##1}}
        \edef\snk@added@values{\snk@added@values+##1}
      },
      @add forked node/.list/.expand once=\snk@listofforks,
    }
    \ifnumequal{\fpeval{\qty == \snk@tot}}{1}{}{
      \PackageWarning{sankey}%
      {^^J*** Warning: bad sankey fork: %
        \qty\space!=\space\snk@added@values(=\snk@tot)%
        ^^J\snk@listofforks}
    }
    \ifdefempty{\snk@forkanchor}{
      \edef\snk@forkanchor{\name.\snk@anchor}
    }{}
    \snk@getpos\snk@c{$(\snk@forkanchor) - (\pos)$}
    \sankeynode{as=\name,at={($(\name) - (\snk@c)$)}}
    \foreach \snk@subnodeqty/\snk@subnodename in \snk@listofforks {
      \sankeynode{as=\snk@subnodename,at={($(\snk@subnodename) - (\snk@c)$)}}
    }
  }
  \endgroup
}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \begin{macro}{\snk@makenode}
%
% The \code{\snk@makenode} macro creates a new Sankey node named
% \code{\name} with \code{\qty} quantity, oriented at
% \code{\orient} degrees (but modified by the offset angle given by
% \code{\snk@getrotate}), anchored by its \code{\snk@anchor} (or its \emph{center}
% by default) at \code{\pos} position. The quantity and the orientation
% (normalized) are stored in the global fields of the node before the TikZ
% node is created, because the \code{@sankey node} style reads them.
% The macro takes no argument.
%
%    \begin{macrocode}
\def\snk@makenode{
  \begingroup
  \snk@setnodeqty{\name}{\qty}
  \edef\orient{\snk@normalize@angle{\orient}}
  \snk@setnodeorient{\name}{\orient}
  \ifundef{\snk@anchor}{\def\snk@anchor{center}}{}
  \snk@getrotate
  \node[/sankey/@sankey node={\name}{\pos}{\snk@anchor}];
  \endgroup
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\snk@filldrawstart}
%
% The \code{\snk@filldrawstart} macro fills
% (with the \code{/sankey/fill} TikZ style) then draws
% (with the \code{/sankey/draw} TikZ style)
% a start of flow using paths from style \code{\snk@startstyle} on
% the Sankey node named \code{\name}.
%
%    \begin{macrocode}
\def\snk@filldrawstart{
  \begin{scope}[shift={(\name)},rotate=\orient]
    \path[/sankey/fill] \snk@getstartfill{\snk@startstyle};
    \path[/sankey/draw] \snk@getstartdraw{\snk@startstyle};
  \end{scope}
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\snk@filldrawend}
%
% The \code{\snk@filldrawend} macro fills
% (with the \code{/sankey/fill} TikZ style) then draws
% (with the \code{/sankey/draw} TikZ style)
% an end of flow using paths from style \code{\snk@endstyle} on
% the Sankey node named \code{\name}.
%
%    \begin{macrocode}
\def\snk@filldrawend{
  \begin{scope}[shift={(\name)},rotate=\sankeygetnodeorient{\name}]
    \path[/sankey/fill] \snk@getendfill{\snk@endstyle};
    \path[/sankey/draw] \snk@getenddraw{\snk@endstyle};
  \end{scope}
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\snk@checkquantities}
% \begin{macro}{\snk@qtyi}
% \begin{macro}{\snk@qtyii}
% The \code{\snk@checkquantities} compares quantities
% from Sankey nodes \code{#1} and \code{#2} and emits
% an error message if they differ (\code{#3}  is the name
% of the macro which requested the verification).
%
%    \begin{macrocode}
\def\snk@checkquantities#1#2#3{
  \begingroup
  \edef\snk@qtyi{\sankeygetnodeqty{#1}}
  \edef\snk@qtyii{\sankeygetnodeqty{#2}}
  \ifdefstrequal{\snk@qtyi}{\snk@qtyii}{}{
    \PackageError{sankey}%
    {^^J*** \string#3: quantities differ between %
      #1 (\snk@qtyi) and #2 (\snk@qtyii)%
      ^^J}%
    {The quantities of the two Sankey nodes must be equal.}
  }
  \endgroup
}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%^^A % ------------------------------------------------------------
% \subsection{User macros}
%^^A % ------------------------------------------------------------
%
% The user macros are globally defined as internal (with \code{snk@}
% prefix) and locally defined in the \code{sankeydiagram} environment as
% user macros (without the \code{snk@} prefix).
% 
% \begin{macro}{\snk@sankeydubins}
%   
%   The \code{\snk@sankeydubins} macro links two Sankey nodes via a
%   Dubins path. First, it computes the Dubins path between centers
%   (left and right radii are the same) and stores the result under the
%   name \code{sankey} (the \code{store=sankey} key). Then it uses the stored result to fill and draw the
%   lane (left border and right borders use Dubins paths with asymmetric
%   radii).
%   
%    \begin{macrocode}
\NewDocumentCommand\snk@sankeydubins{O{}mm}{% options, sn, en
  \snk@errorifnotdefined{#2}
  \snk@errorifnotdefined{#3}
  \snk@checkquantities{#2}{#3}{\sankeydubins}
  \begingroup
  \sankeyset{#1}
  \pgfmathsetmacro\qty{\sankeygetnodeqty{#2}}
  \dubinspathset{
    sankey/.style={
      start point=#2.center,start angle=\sankeygetnodeorient{#2},
      end point=#3.center,end angle=\sankeygetnodeorient{#3},
      minimum radius=\snk@minradius + .5 * \sankeyqtytolen{\qty} pt,
    },
  }
  \edef\snk@tmp{\noexpand\dubinspathset{prefer=\snk@prefer}}\snk@tmp
  \dubinspathcalc{sankey,store=sankey}
  \dubinspathset{
    left border/.style={
      sankey, use store=sankey,
      left and right minimum radii={\snk@minradius}
      and {\snk@minradius + \sankeyqtytolen{\qty} pt},
    },
    right border/.style={
      sankey, use store=sankey,
      left and right minimum radii=
      {\snk@minradius + \sankeyqtytolen{\qty} pt}
      and {\snk@minradius},
    },
  }
  % fill the region
  \path[/sankey/fill] (#2.left)  \dubinspath{left border}
  -- (#3.left) -- (#3.right) \dubinspath{right border,reverse}
  -- (#2.right) -- cycle;
  % draw left and right borders
  \path[/sankey/draw] (#2.left) \dubinspath{left border}
  (#2.right) \dubinspath{right border};
  \endgroup
}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\snk@sankeyoutin}
%
%   The \code{\snk@sankeyoutin} macro links two Sankey nodes via a
%   Bézier curve.  First, to simulate constant width, it creates
%   \code{\snk@stepoutin} intermediate Sankey nodes along the Bézier
%   curve. Then, the lane is filled and drawn linking all the
%   intermediate Sankey node via smaller Bézier curves.
%
%   The work is done in four stages.
%   \begin{enumerate}
%   \item A decoration of type \code{markings} is applied to an invisible
%     Bézier curve from the center of the first node to the center of the
%     second one (leaving and entering with the orientations of the
%     nodes). At each of the \code{\snk@stepoutin}$-1$ regularly spaced
%     marks, three coordinates are created in the local frame of the
%     mark (tangent to the curve): the point on the curve, named
%     \code{snk@outinmidpt-}\emph{N} (\emph{N} is the sequence number of
%     the mark), and the points at the half-width of the lane on each
%     side, named with the suffixes \code{-l} and \code{-r}.
%   \item For each mark, an intermediate Sankey node is created at the
%     point of the curve. Its orientation is deduced from the direction
%     of the segment between the \code{-r} and \code{-l} points, so that
%     it is perpendicular to the curve. These nodes are created with
%     \code{debug=false} to hide the debug information.
%   \item The nodes numbered $0$ and \code{\snk@stepoutin} are the two end
%     nodes, copied at the positions and orientations of the given nodes
%     (these are the only ones that are not on the curve).
%   \item The lane is filled and drawn in two passes (fill, then draw),
%     each one made of two loops: one follows the \code{left} anchors from
%     node $0$ to node \code{\snk@stepoutin}, the other follows the
%     \code{right} anchors in the opposite direction. Two successive
%     anchors are joined by a Bézier curve (\code{to}) leaving and entering
%     in the direction of the nodes. With \code{looseness=1} the curve
%     keeps the default shape of \code{to}, so that the segments are
%     smooth. The \code{remember} option of \code{\foreach} gives the
%     previous node of each iteration.
%   \end{enumerate}
%
%    \begin{macrocode}
\NewDocumentCommand\snk@sankeyoutin{O{}mm}{% options, sn, en
  \snk@errorifnotdefined{#2}
  \snk@errorifnotdefined{#3}
  \snk@checkquantities{#2}{#3}{\sankeyoutin}
  \begingroup
  \sankeyset{#1}
  \edef\qty{\sankeygetnodeqty{#2}}
  \pgfmathsetmacro\snk@len{\sankeyqtytolen{\qty}/2}
  \edef\snk@step{\fpeval{1/\snk@stepoutin}}
  \edef\snk@laststep{\inteval{\snk@stepoutin-1}}
  \path[overlay,decorate,decoration={
      markings,
      mark=between positions \snk@step and {\fpeval{1-.5*\snk@step}}
      step \snk@step with {
        \edef\snk@outinmidptname{%
          snk@outinmidpt-%
          \pgfkeysvalueof{/pgf/decoration/mark info/sequence number}%
        }
        \path
        (0,0) coordinate(\snk@outinmidptname)
        (0,-\snk@len pt) coordinate (\snk@outinmidptname-r)
        (0,\snk@len pt) coordinate (\snk@outinmidptname-l)
        ;
      }
    }]
  (#2.center)
  to[out=\sankeygetnodeorient{#2},in=\sankeygetnodeorient{#3}+180]
  (#3.center);
  \foreach \snk@ptnum in {1,...,\snk@laststep}{
    \edef\snk@outinmidptname{snk@outinmidpt-\snk@ptnum}
    \dbp@anglebetween\snk@outinmidptangle%
    {\snk@outinmidptname-r}{\snk@outinmidptname-l}
    \sankeynode[debug=false]{%
      name=\snk@outinmidptname,
      quantity=\qty,
      angle=\snk@outinmidptangle-90,%
      at=(\snk@outinmidptname)%
    }
  }
  \sankeynode[debug=false]{%
    name={snk@outinmidpt-0},
    quantity=\sankeygetnodeqty{#2},
    angle=\sankeygetnodeorient{#2},%
    at={(#2)}%
  }
  \sankeynode[debug=false]{%
    name={snk@outinmidpt-\snk@stepoutin},
    quantity={\sankeygetnodeqty{#3}},
    angle={\sankeygetnodeorient{#3}},%
    at={(#3)}%
  }
  \path[/sankey/fill,looseness=1]
  (snk@outinmidpt-0.left)
  \foreach \snk@curpt
  [remember=\snk@curpt as \snk@prevpt (initially 0)]
  in {1,...,\snk@stepoutin}{
    to[out=\sankeygetnodeorient{snk@outinmidpt-\snk@prevpt},
      in=\sankeygetnodeorient{snk@outinmidpt-\snk@curpt}+180]
    (snk@outinmidpt-\snk@curpt.left)
  }
  --
  (snk@outinmidpt-\snk@stepoutin.right)
  \foreach \snk@curpt
  [remember=\snk@curpt as \snk@prevpt (initially \snk@stepoutin)]
  in {\snk@laststep,...,0}{
    to[out=\sankeygetnodeorient{snk@outinmidpt-\snk@prevpt}+180,
      in=\sankeygetnodeorient{snk@outinmidpt-\snk@curpt}]
    (snk@outinmidpt-\snk@curpt.right)
  }
  -- cycle;
  \path[/sankey/draw,looseness=1]
  (snk@outinmidpt-0.left)
  \foreach \snk@curpt
  [remember=\snk@curpt as \snk@prevpt (initially 0)]
  in {1,...,\snk@stepoutin}{
    to[out=\sankeygetnodeorient{snk@outinmidpt-\snk@prevpt},
      in=\sankeygetnodeorient{snk@outinmidpt-\snk@curpt}+180]
    (snk@outinmidpt-\snk@curpt.left)
  }
  (snk@outinmidpt-\snk@stepoutin.right)
  \foreach \snk@curpt
  [remember=\snk@curpt as \snk@prevpt (initially \snk@stepoutin)]
  in {\snk@laststep,...,0}{
    to[out=\sankeygetnodeorient{snk@outinmidpt-\snk@prevpt}+180,
      in=\sankeygetnodeorient{snk@outinmidpt-\snk@curpt}]
    (snk@outinmidpt-\snk@curpt.right)
  };
  \endgroup
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\snk@sankeynodealias}
%   
%   The \code{\snk@sankeynodealias} macro clones the Sankey node named
%   \code{#1} into a Sankey node named \code{#2}. The TikZ node gets a
%   second name via the \code{alias} key, applied with
%   \code{late options} (which runs the options on an existing node
%   without creating it again), and the quantity and orientation of the
%   original node are copied to the alias.
%
%    \begin{macrocode}
\NewDocumentCommand\snk@sankeynodealias{mm}{%name, alias
  \snk@errorifnotdefined{#1}
  \path[late options={name=#1,alias=#2}];
  \snk@setnodeqty{#2}{\sankeygetnodeqty{#1}}
  \snk@setnodeorient{#2}{\sankeygetnodeorient{#1}}
}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\snk@sankeynode}
%   
%   The \code{\snk@sankeynode} macro creates a new Sankey node. The
%   optional argument \code{#1} contains diagram options, applied
%   locally; the mandatory argument \code{#2} contains the node
%   parameters (the name of the node is given by its \code{name} key).
%   See the introduction of this section for the steps.
%
%    \begin{macrocode}
\NewDocumentCommand\snk@sankeynode{O{}m}{% options, node parameters
  \begingroup
  \sankeyset{#1}
  \sankeyset{node parameters,@initial parameters,/sankey/every node,#2}
  \snk@makenode
  \snk@makeforkednode
  \iftoggle{sankey node start}{\snk@filldrawstart}{}
  \iftoggle{sankey node end}{\snk@filldrawend}{}
  \snk@show@debug{\name}
  \endgroup
}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\snk@sankeystart}
%   
%   The \code{\snk@sankeystart} macro fills and draws a starting lane
%   attached to the Sankey node named \code{#2}.
%
%    \begin{macrocode}
\NewDocumentCommand\snk@sankeystart{O{}m}{% options, name
  \snk@errorifnotdefined{#2}
  \begingroup
  \sankeyset{#1}
  \edef\name{#2}
  \edef\orient{\sankeygetnodeorient{#2}}
  \edef\qty{\sankeygetnodeqty{#2}}
  \snk@filldrawstart
  \endgroup
}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\snk@sankeynodestart}
%   
%   The \code{\snk@sankeynodestart} macro creates the new Sankey
%   node named \code{#2} then fills and draws a starting lane
%   attached to this new Sankey node.
%   
%    \begin{macrocode}
\NewDocumentCommand\snk@sankeynodestart{O{}m}{% option, node parameters
  \sankeynode[#1]{start,#2}
}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\snk@sankeyend}
%   
%   The \code{\snk@sankeyend} macro fills and draws an ending lane
%   attached to the Sankey node named \code{#2}.
%   
%    \begin{macrocode}
\NewDocumentCommand\snk@sankeyend{O{}m}{%options, name
  \snk@errorifnotdefined{#2}
  \begingroup
  \sankeyset{#1}
  \edef\name{#2}
  \edef\orient{\sankeygetnodeorient{#2}}
  \edef\qty{\sankeygetnodeqty{#2}}
  \snk@filldrawend
  \endgroup
}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\snk@sankeynodeend}
%   
%   The \code{\snk@sankeynodeend} macro creates the new Sankey
%   node named \code{#2} then fills and draws an ending lane
%   attached to this new Sankey node.
%   
%    \begin{macrocode}
\NewDocumentCommand\snk@sankeynodeend{O{}m}{% options, node parameters
  \sankeynode[#1]{end,#2}
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\snk@init@move}
%
%   \changes{v3.0.2}{2025/01/10}{Factorization of the node move initialization code}
%
%   The \code{\snk@init@move} macro applies the options and clones the
%   current node (as \code{<name>-old}) before its moving. It also sets
%   \code{\name}, \code{\snk@oldname} and \code{\qty}.
%
%    \begin{macrocode}
\def\snk@init@move#1#2{% params: options, name
  \sankeyset{#1}
  \edef\name{#2}
  \edef\snk@oldname{#2-old}
  \sankeynodealias{\name}{\snk@oldname}
  \edef\qty{\sankeygetnodeqty{\name}}
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\snk@sankeyadvance}
%
%   The \code{\snk@sankeyadvance} macro moves toward (or backward if
%   \emph{starred} calls -- \code{#1}) the Sankey node named \code{#3}.
%   \code{#4} is a distance. The previous position is kept
%   by a Sankey node named \code{#3-old}.
%   
%    \begin{macrocode}
\NewDocumentCommand\snk@sankeyadvance{sO{}mm}{%
  % params: *(reverse), options, name, distance
  \snk@errorifnotdefined{#3}
  \begingroup
  \snk@init@move{#2}{#3}
  \IfBooleanTF{#1}{
    % move backward
    \sankeynode{
      at={($(\snk@oldname.center)!#4!90:(\snk@oldname.left)$)},
      angle=\sankeygetnodeorient{\snk@oldname},
      quantity=\sankeygetnodeqty{\snk@oldname},
      name=\name,
    }
    \path[/sankey/fill]
    (\name.left) -- (\snk@oldname.left)
    -- (\snk@oldname.right) -- (\name.right) -- cycle;
    \path[/sankey/draw]
    (\name.left) -- (\snk@oldname.left)
    (\snk@oldname.right) -- (\name.right);
  }{
    % move forward
    \sankeynode{
      at={($(\snk@oldname.center)!#4!-90:(\snk@oldname.left)$)},
      angle=\sankeygetnodeorient{\snk@oldname},
      quantity=\sankeygetnodeqty{\snk@oldname},
      name=\name,
    }
    \path[/sankey/fill]
    (\snk@oldname.left) -- (\name.left)
    -- (\name.right) -- (\snk@oldname.right) -- cycle;
    \path[/sankey/draw]
    (\snk@oldname.left) -- (\name.left)
    (\name.right) -- (\snk@oldname.right);
  }
  \snk@show@debug{\name}
  \endgroup
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\snk@turn}
%
%   \MACRO\code{\snk@turn}\ARG{\VAR{side}}\ARG{\VAR{direction}}\ARG{\VAR{options}}\ARG{\VAR{name}}\ARG{\VAR{angle}}
%
%   This macro moves the Sankey node named \VAR{name} by turning left
%   (\VAR{side} is $1$) or right (\VAR{side} is $-1$), forward
%   (\VAR{direction} is $1$) or backward (\VAR{direction} is $-1$). A
%   negative \VAR{angle} reverses the direction. The center of the turn
%   is located at distance \code{minimum radius} from the \code{left}
%   (or \code{right}) anchor of the node. The lane between the previous
%   position $X$ and the new position $Y$ (swapped when moving backward)
%   is filled/drawn by two arcs: the arc on the inner side of the turn
%   has the minimum radius, the other one has the minimum radius plus
%   the width of the lane. The previous position is kept by a Sankey
%   node named \code{#4-old}.
%
%   Geometry: the center \code{\snk@c} of the turn lies on the line
%   through the \code{left} and \code{right} anchors of the node, at the
%   distance \code{\snk@minradius} outside the lane (beyond the
%   \code{left} anchor for a left turn, beyond the \code{right} anchor for
%   a right turn). The new position \code{\pos} is the center of the node
%   rotated around \code{\snk@c} by the angle \code{\snk@rot}. The
%   \code{\snk@base} angle ($\mp 90$ degrees) converts the orientation of a
%   node into the polar angle, seen from \code{\snk@c}, of its anchors:
%   the arcs start at the anchor of the node \code{\snk@X} and end at the
%   anchor of the node \code{\snk@Y}. The radius \code{\snk@rl} of the
%   \code{left} border and the radius \code{\snk@rr} of the \code{right}
%   border are the minimum radius for the inner side of the turn and the
%   minimum radius plus the width of the lane for the outer side.
%
%    \begin{macrocode}
\def\snk@turn#1#2#3#4#5{%
  % side, direction, options, name, angle
  \snk@errorifnotdefined{#4}%
  \begingroup
  \edef\snk@angle{\fpeval{#5}}%
  \edef\snk@anglesign{\fpeval{sign(\snk@angle)}}%
  \ifnumless{\snk@anglesign}{0}{%
    \edef\snk@angle{\fpeval{-(\snk@angle)}}%
    \edef\snk@dir{\inteval{-1*(#2)}}%
  }{%
    \edef\snk@dir{#2}%
  }%
  \snk@init@move{#3}{#4}%
  \edef\snk@oldorient{\sankeygetnodeorient{\name}}%
  \edef\snk@rot{\fpeval{(#1)*(\snk@dir)*\snk@angle}}%
  \edef\orient{\fpeval{\snk@oldorient+\snk@rot}}%
  % center of the turn and new position
  \ifnumgreater{#1}{0}{%
    \snk@getpos\snk@c{$(\name.left)!-\snk@minradius!(\name.right)$}%
  }{%
    \snk@getpos\snk@c{$(\name.right)!-\snk@minradius!(\name.left)$}%
  }%
  \snk@getpos\pos{$(\snk@c)!1!\snk@rot:(\name.center)$}%
  \snk@makenode%
  % X: from, Y: to
  \ifnumgreater{\snk@dir}{0}{%
    \edef\snk@X{\snk@oldname}\edef\snk@Y{\name}%
    \let\snk@oX\snk@oldorient\let\snk@oY\orient
  }{%
    \edef\snk@X{\name}\edef\snk@Y{\snk@oldname}%
    \let\snk@oX\orient\let\snk@oY\snk@oldorient
  }%
  % radii of the left and right borders and angle offset of the arcs
  \pgfmathsetmacro\snk@rmin{\snk@minradius}%
  \pgfmathsetmacro\snk@rmax{\snk@minradius+\sankeyqtytolen{\qty}}%
  \ifnumgreater{#1}{0}{%
    \let\snk@rl\snk@rmin\let\snk@rr\snk@rmax
  }{%
    \let\snk@rl\snk@rmax\let\snk@rr\snk@rmin
  }%
  \edef\snk@base{\inteval{-90*(#1)}}%
  % fill the region
  \path[/sankey/fill]
  (\snk@X.left) arc(\snk@oX+\snk@base:\snk@oY+\snk@base:\snk@rl pt)
  -- (\snk@Y.left) -- (\snk@Y.right)
  arc(\snk@oY+\snk@base:\snk@oX+\snk@base:\snk@rr pt)
  -- (\snk@X.right) -- cycle;
  % draw left and right borders
  \path[/sankey/draw]
  (\snk@X.left) arc(\snk@oX+\snk@base:\snk@oY+\snk@base:\snk@rl pt)
  (\snk@Y.right) arc(\snk@oY+\snk@base:\snk@oX+\snk@base:\snk@rr pt);
  \snk@show@debug{\name}%
  \endgroup
}
%    \end{macrocode}
% \end{macro}
%
% The next four macros (\code{\snk@sankeyturnright},
% \code{\snk@sankeyturnrightbackward}, \code{\snk@sankeyturnleft} and
% \code{\snk@sankeyturnleftbackward}) are thin wrappers around
% \code{\snk@turn}: they only choose the \emph{side} and the
% \emph{direction}. The starred versions use the opposite of the angle.
% Because \code{\snk@turn} reverses the direction for a negative angle,
% a negative angle with a forward macro moves the node backward (and
% conversely), still turning on the same side.
%
% \begin{macro}{\snk@sankeyturnright}
%
%   \changes{v3.0}{2021/03/14}{New macro}
%   
%   The \code{sankeyturnright} macro moves forward the Sankey node named
%   \code{#3} by turning right. The angle is \code{#4} (the starred
%   version uses the opposite of \code{#4}). If the angle is
%   \emph{negative}, the macro calls the \code{\sankeyturnrightbackward}
%   macro to move backward else the macro fills/draws the lane between
%   the previous position and the new position. The previous position is
%   kept by a Sankey node named \code{#3-old}.
%
%    \begin{macrocode}
\NewDocumentCommand\snk@sankeyturnright{sO{}mm}{%
  % *(reverse), options, name, angle
  \IfBooleanTF{#1}
  {\snk@turn{-1}{1}{#2}{#3}{-(#4)}}
  {\snk@turn{-1}{1}{#2}{#3}{#4}}%
}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\snk@sankeyturnrightbackward}
%   
%   \changes{v3.0}{2021/03/14}{New macro}
%   
%   The \code{\snk@sankeyturnrightbackward} macro moves backward the
%   Sankey node named \code{#3} by turning right. The angle is \code{#4}
%   (the starred version uses the opposite of \code{#4}). If the angle
%   is \emph{negative}, the macro calls the \code{\sankeyturnright}
%   macro to move forward else the macro fills/draws the lane between
%   the previous position and the new position. The previous position is
%   kept by a Sankey node named \code{#3-old}.
%
%    \begin{macrocode}
\NewDocumentCommand\snk@sankeyturnrightbackward{sO{}mm}{%
  % *(reverse), options, name, angle
  \IfBooleanTF{#1}
  {\snk@turn{-1}{-1}{#2}{#3}{-(#4)}}
  {\snk@turn{-1}{-1}{#2}{#3}{#4}}%
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\snk@sankeyturnleft}
%   
%   \changes{v3.0}{2021/03/14}{New macro}
%   
%   The \code{\snk@sankeyturnleft} macro moves forward the Sankey node
%   named \code{#3} by turning left. The angle is \code{#4} (the starred
%   version uses the opposite of \code{#4}). If the angle is
%   \emph{negative}, the macro calls the \code{\sankeyturnleftbackward}
%   macro to move backward else the macro fills/draws the lane between
%   the previous position and the new position. The previous position is
%   kept by a Sankey node named \code{#3-old}.
%
%    \begin{macrocode}
\NewDocumentCommand\snk@sankeyturnleft{sO{}mm}{%
  % *(reverse), options, name, angle
  \IfBooleanTF{#1}
  {\snk@turn{1}{1}{#2}{#3}{-(#4)}}
  {\snk@turn{1}{1}{#2}{#3}{#4}}%
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\snk@sankeyturnleftbackward}
%
%   \changes{v3.0}{2021/03/14}{New macro}
% 
%   The \code{\snk@sankeyturnleftbackward} macro moves backward the
%   Sankey node named \code{#3} by turning left. The angle is \code{#4}
%   (the starred version uses the opposite of \code{#4}). If the angle
%   is \emph{negative}, the macro calls the \code{\sankeyturnleft} macro
%   to move forward else the macro fills/draws the lane between the
%   previous position and the new position. The previous position is
%   kept by a Sankey node named \code{#3-old}.
%
%    \begin{macrocode}
\NewDocumentCommand\snk@sankeyturnleftbackward{sO{}mm}{%
  % *(reverse), options, name, angle
  \IfBooleanTF{#1}
  {\snk@turn{1}{-1}{#2}{#3}{-(#4)}}
  {\snk@turn{1}{-1}{#2}{#3}{#4}}%
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\snk@sankeyturn}
%   
%   \changes{v3.0}{2021/03/14}{Simplification by using new \emph{turn} macros}
%   
%   The \code{\snk@sankeyturn} macro moves toward (or backward if
%   \emph{starred} calls -- \code{#1}) the Sankey node named \code{#3}
%   by turning left (angle \code{#4} is positive) or right (angle
%   \code{#4} is negative).  The previous position is kept by a Sankey
%   node named \code{#3-old}.
%
%    \begin{macrocode}
\NewDocumentCommand\snk@sankeyturn{sO{}mm}{%
  % *(reverse), options, name, angle
  \snk@errorifnotdefined{#3}
  \begingroup
  \edef\snk@anglesign{\fpeval{sign(#4)}}
  \IfBooleanTF{#1}{
    \ifnumgreater{\snk@anglesign}{-1}
    {\sankeyturnleftbackward[#2]{#3}{#4}}
    {\sankeyturnrightbackward[#2]{#3}{-1*#4}}
  }{
    \ifnumgreater{\snk@anglesign}{-1}
    {\sankeyturnleft[#2]{#3}{#4}}
    {\sankeyturnright[#2]{#3}{-1*#4}}
  }
  \endgroup
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\snk@sankeyfork}
%   
%   The \code{\snk@sankeyfork} macro forks the Sankey node named
%   \code{#2} to the list of subnodes given by \code{#3}.
%   The subnodes are cloned to take into account
%   the \code{debug} option.
%   
%    \begin{macrocode}
\NewDocumentCommand\snk@sankeyfork{O{}mm}{%options, name, list of forks
  \snk@errorifnotdefined{#2}
  \begingroup
  \sankeyset{#1}
  \sankeynode[debug=false]{as={#2},forked={#3}}
  \foreach \qty/\snk@subnodename in {#3}{\sankeynode{as={\snk@subnodename}}}
  \endgroup
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\snk@sankeyqtytolen}
%   
%   The \code{\snk@sankeyqtytolen} macro converts quantity to length
%   using \code{\fpeval} and the ratio determined by
%   \code{\snk@totalqty} and \code{\snk@totallen}.
%
%    \begin{macrocode}
\NewExpandableDocumentCommand\snk@sankeyqtytolen{m}{%
  \fpeval{(#1)/\snk@totalqty*\snk@totallen}%
}
%    \end{macrocode}
% \end{macro}
%
%^^A % ------------------------------------------------------------
% \subsection{The \protect\ttintitle{sankeydiagram} environment}
%^^A % ------------------------------------------------------------
%
%
% \begin{environment}{sankeydiagram}
%
%   \changes{v3.0.2}{2025/01/10}{Simplification of the environment by copying internal macros}
%
%   The \code{sankeydiagram} environment allows the creation of Sankey
%   diagrams.
%   
%   \DescribeMacro{\sankeyadvance}%
%   \DescribeMacro{\sankeydubins}%
%   \DescribeMacro{\sankeyend}%
%   \DescribeMacro{\sankeyfork}%
%   \DescribeMacro{\sankeynodealias}%
%   \DescribeMacro{\sankeynodeend}%
%   \DescribeMacro{\sankeynodestart}%
%   \DescribeMacro{\sankeynode}%
%   \DescribeMacro{\sankeyoutin}%
%   \DescribeMacro{\sankeyqtytolen}%
%   \DescribeMacro{\sankeystart}%
%   \DescribeMacro{\sankeyturnleftbackward}%
%   \DescribeMacro{\sankeyturnleft}%
%   \DescribeMacro{\sankeyturnrightbackward}%
%   \DescribeMacro{\sankeyturnright}%
%   \DescribeMacro{\sankeyturn}%
%   It defines locally all the macros used by a Sankey diagram.
%   The public names are copies (\code{\NewCommandCopy}) of the internal
%   macros, defined inside the environment so that they do not exist
%   outside of it. A copy is a full duplicate (same arguments and same
%   body), so no wrapper macro or additional expansion is needed.
%
%   Then it applies the \code{@initial options} and \code{every diagram}
%   styles (in this order) and applies all the keys provided in its
%   optional argument.
%
%    \begin{macrocode}
\NewDocumentEnvironment{sankeydiagram}{O{}}{
  \NewCommandCopy{\sankeyadvance}{\snk@sankeyadvance}
  \NewCommandCopy{\sankeydubins}{\snk@sankeydubins}
  \NewCommandCopy{\sankeyend}{\snk@sankeyend}
  \NewCommandCopy{\sankeyfork}{\snk@sankeyfork}
  \NewCommandCopy{\sankeynodealias}{\snk@sankeynodealias}
  \NewCommandCopy{\sankeynodeend}{\snk@sankeynodeend}
  \NewCommandCopy{\sankeynodestart}{\snk@sankeynodestart}
  \NewCommandCopy{\sankeynode}{\snk@sankeynode}
  \NewCommandCopy{\sankeyoutin}{\snk@sankeyoutin}
  \NewCommandCopy{\sankeyqtytolen}{\snk@sankeyqtytolen}
  \NewCommandCopy{\sankeystart}{\snk@sankeystart}
  \NewCommandCopy{\sankeyturnleftbackward}{\snk@sankeyturnleftbackward}
  \NewCommandCopy{\sankeyturnleft}{\snk@sankeyturnleft}
  \NewCommandCopy{\sankeyturnrightbackward}{\snk@sankeyturnrightbackward}
  \NewCommandCopy{\sankeyturnright}{\snk@sankeyturnright}
  \NewCommandCopy{\sankeyturn}{\snk@sankeyturn}
  \sankeyset{
    @initial options,
    every diagram,
    % user values
    #1}
}
{} % no code at the end of the environment
%    \end{macrocode}
% \end{environment}
%
%^^A % ------------------------------------------------------------
% \subsection{Predefined start and end styles}
%^^A % ------------------------------------------------------------
%
% The \code{none} style.
%
%    \begin{macrocode}
\sankeyset{
  new start style={none}{}{},
  new end style={none}{}{},
}
%    \end{macrocode}
%
% The \code{simple} style.
%
%    \begin{macrocode}
\sankeyset{
  new start style={simple}{
    (\name.left) -- ([xshift=-.5\pgflinewidth]\name.left)
    -- ([xshift=-.5\pgflinewidth]\name.right) -- (\name.right) -- cycle
  }{
    (\name.left) -- ([xshift=-.5\pgflinewidth]\name.left)
    -- ([xshift=-.5\pgflinewidth]\name.right) -- (\name.right)
  },
  new end style={simple}{
    (\name.left) -- ([xshift=2mm]\name.center)
    -- (\name.right) -- cycle
  }{
    (\name.left)  -- ([xshift=2mm]\name.center) -- (\name.right)
  },
}
%    \end{macrocode}
%
% The \code{arrow} style.
%
%    \begin{macrocode}
\sankeyset{
  new start style={arrow}{
    (\name.left) -- ++(-10pt,0) -- ([xshift=-10pt/6]\name.center)
    -- ([xshift=-10pt]\name.right) -- (\name.right) -- cycle
  }{
    (\name.left) -- ++(-10pt,0) -- ([xshift=-10pt/6]\name.center)
    -- ([xshift=-10pt]\name.right) -- (\name.right)
  },
  new end style={arrow}{
    (\name.left) -- ([yshift=1mm]\name.left)
    -- ([xshift=10pt]\name.center) -- ([yshift=-1mm]\name.right)
    -- (\name.right) -- cycle
  }{
    (\name.left) -- ([yshift=1mm]\name.left)
    -- ([xshift=10pt]\name.center) -- ([yshift=-1mm]\name.right)
    -- (\name.right)
  },
}
%    \end{macrocode}
% \iffalse
%</sankey>
% \fi
%
%^^A % ------------------------------------------------------------
% \section{\ttintitle{tikzlibrarydubins.code.tex}}
%^^A % ------------------------------------------------------------
%
% This section contains the code of the \code{dubins} TikZ library
% (see \vref{sec:dubins} for its user documentation).
%
% All internal macros use the \code{\dbp@} prefix. All distances are
% stored in \emph{points} without unit (as \code{pgfmath} results) and
% all angles in degrees.
%
% \paragraph{Principle.} A Dubins path\footnote{\url{https://en.wikipedia.org/wiki/Dubins_path}}
% is the shortest path between two
% oriented points (a point and a direction) for a curve whose radius of
% curvature is at least a given radius $r$. It is made of three parts:
% either two arcs joined by a straight segment (a \emph{CSC} path:
% \code{rsr}, \code{lsl}, \code{rsl} or \code{lsr}), or three tangent arcs
% (a \emph{CCC} path: \code{lrl} or \code{rlr}). Each letter gives the
% direction of a turn (\code{l} for left, \code{r} for right, \code{s}
% for straight). The \emph{method} is the name of one of these six
% candidates. The library computes the length of each candidate which
% exists and keeps the shortest one. If two candidates have the same
% length (within $0.01$\,pt), the \code{prefer} key chooses the one
% whose first turn is on the preferred side.
%
% \paragraph{The two steps.} The work is split in two macros which share
% the same keys.
% \begin{itemize}
% \item \code{\dubinspathcalc} computes the method and the three
%   parameters of the path (the angle of the first arc, the length of the
%   straight segment or the angle of the middle arc, and the angle of the
%   last arc). It draws nothing. The result may be stored (\code{store}
%   key) and retrieved later by the \code{use store} key or by
%   \code{\dubinspathget}.
% \item \code{\dubinspath} is a TikZ path operation: it draws the path
%   for a given method and given parameters (given directly or by
%   \code{use store}). If no method is given, it calls
%   \code{\dubinspathcalc} itself (with the temporary store
%   \code{dbp@auto}).
% \end{itemize}
% Neither of the two macros uses the TikZ \code{let} operation: all the
% values are computed beforehand and stored in macros, then expanded in
% ordinary path operations (\code{arc} and \code{--}).
%
% \paragraph{Order of the calls.} For one call of
% \code{\dubinspathcalc}, the macros are called in this order:
% \begin{enumerate}
% \item the keys are processed (\code{\dubinspathset}) and checked
%   (\code{\dbp@checkkey});
% \item the angles are normalized, the points are evaluated
%   (\code{\dbp@evalpoint}) and the centers of the four circles of radius
%   $r$ tangent to the start and end directions are computed
%   (\code{\dbp@center});
% \item \code{\dbp@tryouter} (twice: \code{rsr}, whose first call
%   uses \code{\dbp@setparams} to initialize the result, then
%   \code{lsl}), \code{\dbp@tryinner} (\code{rsl} and \code{lsr}) and
%   \code{\dbp@tryccc} (\code{lrl} and \code{rlr}); every candidate calls
%   \code{\dbp@updateparams}, which keeps it if it is better than the
%   current result, via \code{\dbp@setparams}.
% \end{enumerate}
% For one call of \code{\dubinspath}, after the optional call of
% \code{\dubinspathcalc}, the method is checked, the \code{reverse} key is
% applied, then \code{\dbp@prep@}\VAR{method} (\code{\dbp@prepcsc} or
% \code{\dbp@prepccc}) computes the angles and the points of the arcs and
% defines \code{\dbp@ops}, which is finally expanded in the path.
%
% \paragraph{Implicit parameters.} As in \code{sankey.sty}, the macros
% communicate through macros which play the role of variables.
% \begin{itemize}
% \item Set by the keys (\code{\dubinspathset}): \code{\dbp@a} and
%   \code{\dbp@b} (start and end points), \code{\dbp@anga} and
%   \code{\dbp@angb} (start and end angles), \code{\dbp@radius} (the
%   radius $r$: the minimum radius, or the mean of the left and right
%   radii \code{\dbp@lradius} and \code{\dbp@rradius}),
%   \code{\dbp@storename}, \code{\dbp@prefer} and the boolean
%   \code{dbp@reverse}. Read by \code{\dubinspathcalc} and
%   \code{\dubinspath}.
% \item Set by the keys or by \code{\dbp@setparams}: \code{\dbp@method},
%   \code{\dbp@firstangle}, \code{\dbp@midparam} and
%   \code{\dbp@lastangle} (the \code{first angle}, \code{middle param}
%   and \code{last angle} keys); \code{\dbp@length} is set only by
%   \code{\dbp@setparams}. Read by \code{\dbp@updateparams} (the current
%   best result), by \code{\dubinspath} and by the \code{\dbp@prep@}
%   macros.
% \item Set by the \code{\dbp@prep@} macros: the angles
%   \code{\dbp@na}, \dots, the radii \code{\dbp@ra} and \code{\dbp@rb} of
%   the first and last arcs, the point \code{\dbp@tx}, \code{\dbp@ty}
%   and, above all, \code{\dbp@ops}, the path operations.
% \item Temporary values of the candidates: \code{\dbp@c@}\VAR{name}
%   macros (distance \code{\dbp@c@d} between two centers, direction
%   \code{\dbp@c@theta} of the line joining them, angles
%   \code{\dbp@c@one} and \code{\dbp@c@two} of the first and last arcs,
%   and so on).
% \end{itemize}
%
% \iffalse
%<*tikzlibrarydubins.code.tex>
% \fi
% \begin{macro}{\tikzlibrarydubins@version}
% \begin{macro}{\tikzlibrarydubins@date}
%    \begin{macrocode}
\def\tikzlibrarydubins@version{v3.1.0}
\def\tikzlibrarydubins@date{2026/11/29}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \subsection{Declarations and helper macros}
%
% The library requires the \code{calc} TikZ library and the
% \code{etoolbox} and \code{xfp} packages. The
% \code{dbp@reverse} boolean is driven by the \code{reverse} key. The
% \code{\dbp@box} box is used by \code{\dubinspathcalc} (to discard any
% spurious space). The \code{\dbp@prefer} macro (driven by the
% \code{prefer} key) is initially empty.
%
%    \begin{macrocode}
\usetikzlibrary{calc}
\RequirePackage{etoolbox}
\RequirePackage{xfp}

\newbool{dbp@reverse}
\newbox\dbp@box
\def\dbp@prefer{}
%    \end{macrocode}
%
% \begin{macro}{\dbp@ifpgfmathcond}
% \MACRO\code{\dbp@ifpgfmathcond}\ARG{\VAR{condition}}\ARG{\VAR{true}}\ARG{\VAR{false}}
%
% This macro evaluates \VAR{condition} via \code{pgfmath} and executes
% \VAR{true} or \VAR{false}.
%
%    \begin{macrocode}
\def\dbp@ifpgfmathcond#1{%
  \pgfmathtruncatemacro\dbp@cond{(#1)?1:0}%
  \ifnumequal{\dbp@cond}{1}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\dbp@getxy}
% The \code{\dbp@getxy}\ARG{\VAR{x macro}}\ARG{\VAR{y macro}}\ARG{\VAR{point}}
% macro stores the coordinates (in canvas coordinate system) of the TikZ
% \VAR{point} into the two macros.
%
%    \begin{macrocode}
\def\dbp@getxy#1#2#3{%
  \tikz@scan@one@point\pgfutil@firstofone(#3)\relax%
  \edef#1{\the\pgf@x}%
  \edef#2{\the\pgf@y}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\dbp@evalpoint}
% \changes{v3.1.0}{2026/11/29}{Points and angles are evaluated before the \protect\code{let} operations (user coordinates may use the \protect\code{x} and \protect\code{y} macros)}
% The \code{\dbp@evalpoint}\ARG{\VAR{macro}} macro replaces the TikZ
% point stored in \VAR{macro} by its coordinates (\code{\dbp@getxy}).
% All the points (and angles) given by the user are evaluated once, at
% the beginning of \code{\dubinspathcalc} and \code{\dubinspath} (they
% may use, for instance, the \code{\x} and \code{\y} variables of a
% \code{\foreach} loop).
%
%    \begin{macrocode}
\def\dbp@evalpoint#1{%
  \dbp@getxy\dbp@tmpx\dbp@tmpy{#1}%
  \edef#1{\dbp@tmpx,\dbp@tmpy}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\dbp@getnumxy}
% The \code{\dbp@getnumxy}\ARG{\VAR{x macro}}\ARG{\VAR{y macro}}\ARG{\VAR{point}}
% macro is like \code{\dbp@getxy} but stores numbers (in points, without
% unit).
%
%    \begin{macrocode}
\def\dbp@getnumxy#1#2#3{%
  \dbp@getxy#1#2{#3}%
  \pgfmathsetmacro#1{#1}%
  \pgfmathsetmacro#2{#2}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\dbp@center}
% \changes{v3.1.0}{2026/11/29}{The \protect\code{dubinspathcalc} macro can be used outside a \protect\code{tikzpicture} and adds no spurious space}
% The \code{\dbp@center}\ARG{\VAR{macro}}\ARG{\VAR{point}}\ARG{\VAR{angle}}
% macro stores into \VAR{macro} the point located at distance
% \code{\dbp@radius} from \VAR{point} in the direction \VAR{angle}: the
% center of a circle tangent to the path at \VAR{point}.
%
%    \begin{macrocode}
\def\dbp@center#1#2#3{%
  \dbp@getnumxy\dbp@tmpx\dbp@tmpy{#2}%
  \pgfmathsetmacro\dbp@tmpcx{\dbp@tmpx+\dbp@radius*cos(#3)}%
  \pgfmathsetmacro\dbp@tmpcy{\dbp@tmpy+\dbp@radius*sin(#3)}%
  \edef#1{\dbp@tmpcx pt,\dbp@tmpcy pt}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\dbp@anglebetween}
% The \code{\dbp@anglebetween}\ARG{\VAR{macro}}\ARG{\VAR{s}}\ARG{\VAR{t}}
% macro stores into \VAR{macro} the angle of the vector from point
% \VAR{s} to point \VAR{t}.
%
%    \begin{macrocode}
\def\dbp@anglebetween#1#2#3{%macro, s, t
  \dbp@getxy\dbp@ax\dbp@ay{#2}
  \dbp@getxy\dbp@bx\dbp@by{#3}
  \pgfmathsetmacro#1{atan2(\dbp@by-\dbp@ay,\dbp@bx-\dbp@ax)}
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\dbp@distancebetween}
% The \code{\dbp@distancebetween}\ARG{\VAR{macro}}\ARG{\VAR{s}}\ARG{\VAR{t}}
% macro stores into \VAR{macro} the distance (computed via \code{\fpeval})
% between points \VAR{s} and \VAR{t}.
%
%    \begin{macrocode}
\def\dbp@distancebetween#1#2#3{%macro, s, t
  \dbp@getxy\dbp@ax\dbp@ay{#2}
  \dbp@getxy\dbp@bx\dbp@by{#3}
  \edef#1{\fpeval{sqrt(%
      (\dbp@bx-\dbp@ax)*(\dbp@bx-\dbp@ax)%
      +(\dbp@by-\dbp@ay)*(\dbp@by-\dbp@ay)%
      )}}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\dbp@radiusof}
% The \code{\dbp@radiusof}\ARG{\VAR{macro}}\ARG{\VAR{sign}} macro lets
% \VAR{macro} be the left radius (positive \VAR{sign}: left turn) or the
% right radius (negative \VAR{sign}: right turn).
%
%    \begin{macrocode}
\def\dbp@radiusof#1#2{%
  \ifnum#2>0 \let#1\dbp@lradius\else\let#1\dbp@rradius\fi
}
%    \end{macrocode}
% \end{macro}
%
% \subsection{Preparing the drawing of a path}
%
% \begin{macro}{\dbp@prepcsc}
% \begin{macro}{\dbp@opscsc}
% The \code{\dbp@prepcsc}\ARG{\VAR{first sign}}\ARG{\VAR{last sign}}
% macro prepares the drawing of a \emph{CSC} path (the signs give the
% directions of the two turns: $1$ for left, $-1$ for right):
% \begin{itemize}
% \item the first arc (radius \code{\dbp@ra}) goes from
%   \code{\dbp@na} to \code{\dbp@nb} degrees;
% \item the straight segment goes to the point (\code{\dbp@tx},
%   \code{\dbp@ty}), the tangent point of the last circle (its center
%   is located from the end point \code{\dbp@b} with the mean radius
%   \code{\dbp@radius}: it is at distance \code{\dbp@radius} from
%   \code{\dbp@b} in the direction of the end angle plus (left turn) or
%   minus (right turn) $90$ degrees; the tangent point is then at
%   distance \code{\dbp@rb} from this center in the direction
%   \code{\dbp@nd});
% \item the last arc (radius \code{\dbp@rb}) goes from \code{\dbp@nd}
%   to \code{\dbp@nc} degrees.
% \end{itemize}
% The \code{\dbp@opscsc} macro expands to the corresponding path
% operations.
%
%    \begin{macrocode}
\def\dbp@prepcsc#1#2{%
  \pgfmathsetmacro\dbp@na{\dbp@anga-(#1)*90}%
  \pgfmathsetmacro\dbp@nb{\dbp@na+(#1)*(\dbp@firstangle)}%
  \pgfmathsetmacro\dbp@nc{\dbp@angb-(#2)*90}%
  \pgfmathsetmacro\dbp@nd{\dbp@nc-(#2)*(\dbp@lastangle)}%
  \dbp@radiusof\dbp@ra{#1}%
  \dbp@radiusof\dbp@rb{#2}%
  \dbp@getnumxy\dbp@tmpx\dbp@tmpy{\dbp@b}%
  \pgfmathsetmacro\dbp@tx{%
    \dbp@tmpx+\dbp@radius*cos(\dbp@angb+(#2)*90)+\dbp@rb*cos(\dbp@nd)}%
  \pgfmathsetmacro\dbp@ty{%
    \dbp@tmpy+\dbp@radius*sin(\dbp@angb+(#2)*90)+\dbp@rb*sin(\dbp@nd)}%
  \let\dbp@ops\dbp@opscsc
}
\def\dbp@opscsc{%
  arc(\dbp@na:\dbp@nb:\dbp@ra pt)
  -- (\dbp@tx pt,\dbp@ty pt)
  arc(\dbp@nd:\dbp@nc:\dbp@rb pt)
}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\dbp@prepccc}
% \begin{macro}{\dbp@opsccc}
% The \code{\dbp@prepccc}\ARG{\VAR{sign}} macro prepares the drawing of
% a \emph{CCC} path (\VAR{sign} gives the direction of the first and last
% turns): three tangent arcs, from \code{\dbp@na} to \code{\dbp@nb},
% from \code{\dbp@ne} to \code{\dbp@nf} (middle arc, opposite direction,
% opposite radius) and from \code{\dbp@nd} to \code{\dbp@nc} degrees.
% The \code{\dbp@opsccc} macro expands to the corresponding path
% operations.
%
%    \begin{macrocode}
\def\dbp@prepccc#1{%
  \pgfmathsetmacro\dbp@na{\dbp@anga-(#1)*90}%
  \pgfmathsetmacro\dbp@nb{\dbp@na+(#1)*(\dbp@firstangle)}%
  \pgfmathsetmacro\dbp@nc{\dbp@angb-(#1)*90}%
  \pgfmathsetmacro\dbp@nd{\dbp@nc-(#1)*(\dbp@lastangle)}%
  \pgfmathsetmacro\dbp@ne{\dbp@nb+180}%
  \pgfmathsetmacro\dbp@nf{\dbp@ne-(#1)*(\dbp@midparam)}%
  \dbp@radiusof\dbp@ra{#1}%
  \dbp@radiusof\dbp@rb{-#1}%
  \let\dbp@ops\dbp@opsccc
}
\def\dbp@opsccc{%
  arc(\dbp@na:\dbp@nb:\dbp@ra pt)
  arc(\dbp@ne:\dbp@nf:\dbp@rb pt)
  arc(\dbp@nd:\dbp@nc:\dbp@ra pt)
}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\dbp@prep@rsr}
% \begin{macro}{\dbp@prep@lsl}
% \begin{macro}{\dbp@prep@rsl}
% \begin{macro}{\dbp@prep@lsr}
% \begin{macro}{\dbp@prep@lrl}
% \begin{macro}{\dbp@prep@rlr}
% \begin{macro}{\dbp@prep@none}
% The \code{\dbp@prep@}\VAR{method} macros prepare the drawing of each
% method (the \code{none} method draws nothing).
%
%    \begin{macrocode}
\def\dbp@prep@rsr{\dbp@prepcsc{-1}{-1}}
\def\dbp@prep@lsl{\dbp@prepcsc{1}{1}}
\def\dbp@prep@rsl{\dbp@prepcsc{-1}{1}}
\def\dbp@prep@lsr{\dbp@prepcsc{1}{-1}}
\def\dbp@prep@lrl{\dbp@prepccc{1}}
\def\dbp@prep@rlr{\dbp@prepccc{-1}}
\def\dbp@prep@none{\let\dbp@ops\dbp@none}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsubsection{Reversed paths, validity of the methods}
%
% \begin{macro}{\dbp@revname@lsl}
% \begin{macro}{\dbp@revname@rsr}
% \begin{macro}{\dbp@revname@lsr}
% \begin{macro}{\dbp@revname@rsl}
% \begin{macro}{\dbp@revname@lrl}
% \begin{macro}{\dbp@revname@rlr}
% \begin{macro}{\dbp@revname@none}
% When a path is drawn backward (\code{reverse} key), its parts are drawn
% in the reverse order and its left turns become right turns (and vice
% versa). The \code{\dbp@revname@}\VAR{method} macros give the name of
% the method to use to draw backward a path computed with \VAR{method}.
% The \code{none} method (used after an error) remains \code{none}.
%    \begin{macrocode}
\def\dbp@revname@lsl{rsr}
\def\dbp@revname@rsr{lsl}
\def\dbp@revname@lsr{lsr}
\def\dbp@revname@rsl{rsl}
\def\dbp@revname@lrl{rlr}
\def\dbp@revname@rlr{lrl}
\def\dbp@revname@none{none}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\dbp@checkkey}
% \changes{v3.1.0}{2026/11/29}{Errors for missing keys and unknown methods or stores in the \protect\code{dubins} library}
% \MACRO\code{\dbp@checkkey}\ARG{\VAR{macro}}\ARG{\VAR{key}}\ARG{\VAR{fallback}}
%
% This macro checks that the \code{\dbp@}\VAR{macro} macro (set by the
% \VAR{key} key) is defined. If not, it raises an error then sets the
% \VAR{fallback} keys (to avoid a cascade of obscure errors).
%
%    \begin{macrocode}
\def\dbp@checkkey#1#2#3{%
  \pgfutil@ifundefined{dbp@#1}{%
    \PackageError{dubins}{Missing '#2' key}%
    {The '#2' key of the /tikz/dubins path family must be set.}%
    \dubinspathset{#3}%
  }{}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\dbp@valid@rsr}
% \begin{macro}{\dbp@valid@lsl}
% \begin{macro}{\dbp@valid@rsl}
% \begin{macro}{\dbp@valid@lsr}
% \begin{macro}{\dbp@valid@lrl}
% \begin{macro}{\dbp@valid@rlr}
% \begin{macro}{\dbp@none}
% A method is valid only if the \code{\dbp@valid@}\VAR{method} macro
% exists. This macro checks the keys specific to the method (only the
% \emph{CCC} methods use the \code{middle param} key). The
% \code{\dbp@none} method (an empty path operation) is used after an
% error.
%
%    \begin{macrocode}
\def\dbp@valid@rsr{}
\def\dbp@valid@lsl{}
\def\dbp@valid@rsl{}
\def\dbp@valid@lsr{}
\def\dbp@valid@lrl{\dbp@checkkey{midparam}{middle param}{middle param=0}}
\def\dbp@valid@rlr{\dbp@checkkey{midparam}{middle param}{middle param=0}}
\newcommand\dbp@none{}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsection{The \ttintitle{dubinspath} path operation}
%
% \begin{macro}{\dubinspath}
% \changes{v3.1.0}{2026/11/29}{The \protect\code{dubinspath} macro computes the path itself if no method is given}
% \changes{v3.1.0}{2026/11/29}{The \protect\code{reverse} key only applies to the current \protect\code{dubinspath} macro}
% The \code{\dubinspath}\ARG{\VAR{options}} macro processes
% \VAR{options} (via \code{\pgfextra}, so the options remain active until
% the end of the current path, except the method that must be given at
% each call). If no method is given (neither \code{method} nor
% \code{use store} key), it computes the path via \code{\dubinspathcalc}
% (result stored under the \code{dbp@auto} name). Then it checks the
% method and the required keys, then inserts the path operation of the chosen method. If the
% method is \code{none} (after an error, for example an unknown method or
% store), the required keys are not checked (to avoid a cascade of
% errors) and nothing is drawn. If the
% \code{reverse} key is true, it first swaps the start and end points,
% reverses (adding 180 degrees) and swaps the start and end angles,
% swaps the first and last angles, swaps the left and right radii and
% uses the reversed method. Then it resets the \code{reverse} key, so
% that it only applies to the current \code{\dubinspath}. Finally, it
% evaluates the end point and the angles and prepares the drawing
% (\code{\dbp@prep@}\VAR{method}) then inserts the path operations
% (\code{\dbp@ops}).
%
%    \begin{macrocode}
\newcommand\dubinspath[1]{%
  \pgfextra{
    \let\dbp@method\relax
    \dubinspathset{#1}
    \pgfutil@ifundefined{dbp@method}{%
      \dubinspathcalc{store=dbp@auto}%
      \dubinspathset{use store=dbp@auto}%
    }{}
    \pgfutil@ifundefined{dbp@valid@\dbp@method}{%
      \ifdefstring{\dbp@method}{none}{}{%
        \PackageError{dubins}{Unknown method '\dbp@method'}%
        {Valid methods are rsr, lsl, rsl, lsr, rlr and lrl.}%
        \dubinspathset{method=none}%
      }%
    }{%
      \csname dbp@valid@\dbp@method\endcsname
    }%
    \ifdefstring{\dbp@method}{none}{\dbp@prep@none\boolfalse{dbp@reverse}}{%
      \dbp@checkkey{b}{end point}{end point={0,0}}
      \dbp@checkkey{anga}{start angle}{start angle=0}
      \dbp@checkkey{angb}{end angle}{end angle=0}
      \dbp@checkkey{radius}{minimum radius}{minimum radius=1pt}
      \dbp@checkkey{firstangle}{first angle}{first angle=0}
      \dbp@checkkey{lastangle}{last angle}{last angle=0}
      \ifbool{dbp@reverse}{
        \dbp@checkkey{a}{start point}{start point={0,0}}
        \edef\dbp@newa{\dbp@b}
        \edef\dbp@newb{\dbp@a}
        \pgfmathsetmacro\dbp@newanga{180+\dbp@angb}
        \pgfmathsetmacro\dbp@newangb{180+\dbp@anga}
        \edef\dbp@newfirstangle{\dbp@lastangle}
        \edef\dbp@newlastangle{\dbp@firstangle}
        \edef\dbp@newmethod{\csname dbp@revname@\dbp@method\endcsname}
        \edef\dbp@newlradius{\dbp@rradius}
        \edef\dbp@newrradius{\dbp@lradius}
        \dubinspathset{
          start point=\dbp@newa,
          end point=\dbp@newb,
          start angle=\dbp@newanga,
          end angle=\dbp@newangb,
          first angle=\dbp@newfirstangle,
          last angle=\dbp@newlastangle,
          left and right minimum radii=\dbp@newlradius pt and \dbp@newrradius pt,
          method=\dbp@newmethod,
        }
        \boolfalse{dbp@reverse}
      }{}
      \dbp@evalpoint\dbp@b
      \pgfmathsetmacro\dbp@anga{\dbp@anga}
      \pgfmathsetmacro\dbp@angb{\dbp@angb}
      \csname dbp@prep@\dbp@method\endcsname
    }%
  }
  \dbp@ops
}
%    \end{macrocode}
% \end{macro}
%
% \subsection{Storing and comparing the results}
%
% \begin{macro}{\dbp@store}
% \begin{macro}{\dbp@get}
% \MACRO\code{\dbp@store}\ARG{\VAR{store name}}\ARG{\VAR{param}}\\
% \MACRO\code{\dbp@get}\ARG{\VAR{store name}}\ARG{\VAR{param}}
%
% The \code{\dbp@store} macro stores \emph{globally} the current value of
% the \code{\dbp@}\VAR{param} macro under \VAR{store name}. The
% \code{\dbp@get} macro retrieves it.
%
%    \begin{macrocode}
\def\dbp@store#1#2{%
  \expandafter\xdef\csname dbp@store@#1@#2\endcsname%
  {\csname dbp@#2\endcsname}%
}
\def\dbp@get#1#2{%
  \csname dbp@store@#1@#2\endcsname%
}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \begin{macro}{\dbp@setparams}
% The \code{\dbp@setparams} macro sets the current result: the method,
% its length, its first angle, its middle parameter and its last angle.
% If a store name is defined (\code{store} key), the result is also
% stored under this name.
%
%    \begin{macrocode}
\def\dbp@setparams#1#2#3#4#5{%
  % method, length, first angle, middle param, last angle
  \edef\dbp@method{#1}
  \edef\dbp@length{#2}
  \edef\dbp@firstangle{#3}
  \edef\dbp@midparam{#4}
  \edef\dbp@lastangle{#5}
  \ifdef{\dbp@storename}{
    \dbp@store{\dbp@storename}{method}
    \dbp@store{\dbp@storename}{length}
    \dbp@store{\dbp@storename}{firstangle}
    \dbp@store{\dbp@storename}{midparam}
    \dbp@store{\dbp@storename}{lastangle}
  }{}
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\dbp@first}
% \begin{macro}{\dbp@ifprefer}
% \changes{v3.1.0}{2026/11/29}{New \protect\code{prefer} key to choose between paths of the same length}
% \MACRO\code{\dbp@ifprefer}\ARG{\VAR{new method}}\ARG{\VAR{current
% method}}\ARG{\VAR{true}}\ARG{\VAR{false}}
%
% This macro executes \VAR{true}
% only if the first turn of \VAR{new method} (its first letter, given by
% \code{\dbp@first}) is on the preferred side (\code{prefer} key) and
% the first turn of \VAR{current method} is not.
%
%    \begin{macrocode}
\def\dbp@first#1#2\@nil{#1}
\def\dbp@ifprefer#1#2{%
  \edef\dbp@tmpa{\dbp@first#1\@nil}%
  \edef\dbp@tmpb{\expandafter\dbp@first#2\@nil}%
  \ifdefequal{\dbp@tmpa}{\dbp@prefer}%
  {\ifdefequal{\dbp@tmpb}{\dbp@prefer}{\@secondoftwo}{\@firstoftwo}}%
  {\@secondoftwo}%
}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\dbp@updateparams}
% The \code{\dbp@updateparams} macro (same parameters as
% \code{\dbp@setparams}) replaces the current result if the new length
% is shorter (by more than $0.01$\,pt). If the two lengths are the same
% (within $0.01$\,pt), the current result is replaced only if the new
% method starts by a turn on the preferred side (\code{prefer} key).
%
%    \begin{macrocode}
\def\dbp@updateparams#1#2#3#4#5{%
  \dbp@ifpgfmathcond{#2<\dbp@length-0.01}{%
    \dbp@setparams{#1}{#2}{#3}{#4}{#5}%
  }{%
    \dbp@ifpgfmathcond{#2<\dbp@length+0.01}{%
      \dbp@ifprefer{#1}{\dbp@method}%
      {\dbp@setparams{#1}{#2}{#3}{#4}{#5}}{}%
    }{}%
  }%
}
%    \end{macrocode}
% \end{macro}
%
% \subsection{The candidate paths}
%
% \begin{macro}{\dbp@tryouter}
% \MACRO\code{\dbp@tryouter}\ARG{\VAR{method}}\ARG{\VAR{sign}}\ARG{\VAR{center
% 1}}\ARG{\VAR{center 2}}\ARG{\VAR{setter}}
%
% This macro computes an
% \emph{outer} CSC path (\code{rsr} or \code{lsl}: two turns in the same
% direction). \VAR{sign} is $1$ for left turns and $-1$ for right turns.
% \VAR{center 1} and \VAR{center 2} are the centers of the first and
% last circles. The straight segment is parallel to the line joining the
% two centers and has the same length $d$ (the two circles have the same
% radius $r$): its direction is the angle $\theta$ of the vector from the
% first to the last center. The first arc turns from the start angle to
% $\theta$ and the last arc from $\theta$ to the end angle; for a right
% turn (negative \VAR{sign}) the angles are measured clockwise, hence the
% multiplication by \VAR{sign} before reducing modulo $360$ (so each arc
% measures between $0$ and $360$ degrees). The length of an arc of angle
% $\varphi$ is $r\varphi$ (\code{angtodist}, with $\varphi$ in radians).
% \VAR{setter} is \code{\dbp@setparams}
% (first candidate) or \code{\dbp@updateparams}.
%
%    \begin{macrocode}
\def\dbp@tryouter#1#2#3#4#5{%
  \dbp@anglebetween\dbp@c@theta{#3}{#4}%
  \dbp@distancebetween\dbp@c@d{#3}{#4}%
  \pgfmathsetmacro\dbp@c@one{Mod((#2)*(\dbp@c@theta-\dbp@anga),360)}%
  \pgfmathsetmacro\dbp@c@two{Mod((#2)*(\dbp@angb-\dbp@c@theta),360)}%
  \pgfmathsetmacro\dbp@c@len{%
    angtodist(\dbp@c@one,\dbp@radius)
    +\dbp@c@d
    +angtodist(\dbp@c@two,\dbp@radius)}%
  #5{#1}{\dbp@c@len}{\dbp@c@one}{\dbp@c@d}{\dbp@c@two}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\dbp@tryinner}
% \changes{v3.1.0}{2026/11/29}{Fixed length of the straight segment of the \protect\code{rsl} and \protect\code{lsr} paths (used to choose the shortest path)}
% \MACRO\code{\dbp@tryinner}\ARG{\VAR{method}}\ARG{\VAR{sign}}\ARG{\VAR{center
% 1}}\ARG{\VAR{center 2}}
%
% This macro computes an \emph{inner} CSC
% path (\code{rsl} or \code{lsr}: two turns in opposite directions).
% \VAR{sign} is the sign of the first turn. Such a path exists only if
% the distance $d$ between the two centers is at least $2r$. The
% straight segment crosses the line joining the two centers with an
% angle $\alpha=\arcsin(2r/d)$ and its length is $\sqrt{d^2-4r^2}$
% (computed via \code{\fpeval} to avoid an overflow of \code{pgfmath}).
% Indeed, the segment is tangent to both circles and passes through the
% midpoint of the two centers: in the right triangle formed by this
% midpoint, a center and the tangent point, the hypotenuse is $d/2$ and
% the side opposite to $\alpha$ is $r$, hence $\sin\alpha=2r/d$. The
% direction of the segment is $\psi=\theta+\mathit{sign}\cdot\alpha$.
% The first arc turns from the start angle to $\psi$ and, since the
% last turn is in the opposite direction, the last arc turns from
% $\psi$ back to the end angle with the same convention (hence
% \code{\dbp@c@psi-\dbp@angb}, without changing the sign). The
% \code{min(1,...)} and \code{max(0,...)} guard against rounding
% errors when $d=2r$.
%
%    \begin{macrocode}
\def\dbp@tryinner#1#2#3#4{%
  \dbp@distancebetween\dbp@c@d{#3}{#4}%
  \dbp@ifpgfmathcond{\dbp@c@d>=2*\dbp@radius}{%
    \dbp@anglebetween\dbp@c@theta{#3}{#4}%
    \pgfmathsetmacro\dbp@c@psi{%
      \dbp@c@theta+(#2)*asin(min(1,2*\dbp@radius/\dbp@c@d))}%
    \pgfmathsetmacro\dbp@c@one{Mod((#2)*(\dbp@c@psi-\dbp@anga),360)}%
    \pgfmathsetmacro\dbp@c@two{Mod((#2)*(\dbp@c@psi-\dbp@angb),360)}%
    \edef\dbp@c@straight{%
      \fpeval{sqrt(max(0,(\dbp@c@d)^2-4*(\dbp@radius)^2))}}%
    \pgfmathsetmacro\dbp@c@len{%
      angtodist(\dbp@c@one,\dbp@radius)
      +\dbp@c@straight
      +angtodist(\dbp@c@two,\dbp@radius)}%
    \dbp@updateparams{#1}{\dbp@c@len}{\dbp@c@one}{\dbp@c@straight}{\dbp@c@two}%
  }{}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\dbp@tryccc}
% \changes{v3.1.0}{2026/11/29}{Fix the \emph{CCC} paths: a null arc is no longer replaced by a full circle}
% \MACRO\code{\dbp@tryccc}\ARG{\VAR{method}}\ARG{\VAR{sign}}\ARG{\VAR{center
% 1}}\ARG{\VAR{center 2}}
%
% This macro computes a CCC path (\code{lrl}
% or \code{rlr}). \VAR{sign} is the sign of the first turn. Such a path
% exists only if the distance $d$ between the two centers is at most
% $4r$. The center of the middle circle (radius $r$) is at distance $2r$
% from the two centers: it is seen from the first center with an angle
% $\gamma=\arccos(d/4r)$ relative to the line joining the two centers.
% The middle arc measures $180+2\gamma$ degrees (it is a full circle if
% the two centers are the same, a half circle if $d=4r$). At the tangent
% point with the middle circle, the heading is
% $\theta+\mathit{sign}\,(90+\gamma)$, which explains the
% $90+\gamma$ added to the first and last arcs. The two arcs are
% symmetric: the last one is computed as the first one of the reversed
% path (hence \code{\dbp@angb-\dbp@c@theta}). The \code{min(1,...)} guard
% protects \code{acos} against rounding errors when $d=4r$.
%
%    \begin{macrocode}
\def\dbp@tryccc#1#2#3#4{%
  \dbp@distancebetween\dbp@c@d{#3}{#4}%
  \dbp@ifpgfmathcond{\dbp@c@d<=4*\dbp@radius}{%
    \dbp@anglebetween\dbp@c@theta{#3}{#4}%
    \pgfmathsetmacro\dbp@c@gamma{acos(min(1,\dbp@c@d/\dbp@radius/4))}%
    \pgfmathsetmacro\dbp@c@one{%
      Mod((#2)*(\dbp@c@theta-\dbp@anga)+90+\dbp@c@gamma,360)}%
    \pgfmathsetmacro\dbp@c@two{%
      Mod((#2)*(\dbp@angb-\dbp@c@theta)+90+\dbp@c@gamma,360)}%
    \pgfmathsetmacro\dbp@c@mid{180+2*\dbp@c@gamma}%
    \pgfmathsetmacro\dbp@c@len{%
      angtodist(\dbp@c@one,\dbp@radius)
      +angtodist(\dbp@c@mid,\dbp@radius)
      +angtodist(\dbp@c@two,\dbp@radius)}%
    \dbp@updateparams{#1}{\dbp@c@len}{\dbp@c@one}{\dbp@c@mid}{\dbp@c@two}%
  }{}%
}
%    \end{macrocode}
% \end{macro}
%
% \subsection{Keys}
%
% All the keys of the \texttt{/tikz/dubins path} family (see
% \vref{sec:dubins} for their user documentation). The \code{use store}
% key raises an error if the store does not exist.
%
%    \begin{macrocode}
\tikzset{
  dubins path/.is family,
  dubins path,
  start point/.store in=\dbp@a,
  start angle/.store in=\dbp@anga,
  end point/.store in=\dbp@b,
  end angle/.store in=\dbp@angb,
  store/.store in=\dbp@storename,
  use store/.code={
    \pgfutil@ifundefined{dbp@store@#1@method}{%
      \PackageError{dubins}{Unknown store '#1'}%
      {Use the 'store=#1' key with \string\dubinspathcalc\space first.}%
      \pgfkeysalso{/tikz/dubins path/method=none}%
    }{%
      \pgfkeysalso{
        /tikz/dubins path/method=\dbp@get{#1}{method},
        /tikz/dubins path/first angle=\dbp@get{#1}{firstangle},
        /tikz/dubins path/last angle=\dbp@get{#1}{lastangle},
        /tikz/dubins path/middle param=\dbp@get{#1}{midparam},
      }%
    }%
  },
  minimum radius/.code={
    \pgfmathsetmacro\dbp@radius{#1}
    \pgfmathsetmacro\dbp@rradius{#1}
    \pgfmathsetmacro\dbp@lradius{#1}
  },
  left and right minimum radii/.code args={#1 and #2}{
    \pgfmathsetmacro\dbp@lradius{#1}
    \pgfmathsetmacro\dbp@rradius{#2}
    \pgfmathsetmacro\dbp@radius{(\dbp@lradius + \dbp@rradius)/2}
  },
  method/.store in=\dbp@method,
  first angle/.store in=\dbp@firstangle,
  last angle/.store in=\dbp@lastangle,
  middle param/.store in=\dbp@midparam,
  reverse/.is if=dbp@reverse,
  prefer/.is choice,
  prefer/left/.code={\def\dbp@prefer{l}},
  prefer/right/.code={\def\dbp@prefer{r}},
  prefer/none/.code={\def\dbp@prefer{}},
}
%    \end{macrocode}
%
% \begin{macro}{\dubinspathset}
% The \code{\dubinspathset} macro processes its parameter with
% \texttt{/tikz/dubins path} as default path.
%
%    \begin{macrocode}
\newcommand\dubinspathset[1]{\tikzset{dubins path,#1}}
%    \end{macrocode}
% \end{macro}
%
%
% \subsubsection{Retrieving a stored result}
%
% \begin{macro}{\dubinspathget}
% \changes{v3.1.0}{2026/11/29}{New \protect\code{dubinspathget} macro}
% The expandable \code{\dubinspathget}\ARG{\VAR{store name}}\ARG{\VAR{param}}
% macro retrieves a parameter of a stored result.
%
%    \begin{macrocode}
\newcommand\dubinspathget[2]{%
  \csname dbp@getkey@#2\endcsname{#1}%
}
\def\dbp@getkey@method#1{\dbp@get{#1}{method}}
\def\dbp@getkey@length#1{\dbp@get{#1}{length}}
\expandafter\def\csname dbp@getkey@first angle\endcsname#1{%
  \dbp@get{#1}{firstangle}}
\expandafter\def\csname dbp@getkey@middle param\endcsname#1{%
  \dbp@get{#1}{midparam}}
\expandafter\def\csname dbp@getkey@last angle\endcsname#1{%
  \dbp@get{#1}{lastangle}}
%    \end{macrocode}
% \end{macro}
%
% \subsection{The \ttintitle{dubinspathcalc} macro}
%
% \begin{macro}{\dubinspathcalc}
% The \code{\dubinspathcalc} macro computes the shortest Dubins path
% within a box (it is discarded, so this macro may be used anywhere
% without adding any space). It declares the \code{angtodist}
% \code{pgfmath} function (to convert an arc angle into a length),
% normalizes the start and end angles between $-180$ and $180$, checks
% the radius, then locates the centers of the four circles tangent to the
% start and end directions (\code{\dbp@ar}, \code{\dbp@al},
% \code{\dbp@br} and \code{\dbp@bl}: right and left of start and end
% points). If the start and end points and directions are the same, the
% result is a null path. The length of each of the six
% candidates is computed (only if it exists, via \code{\dbp@tryouter},
% \code{\dbp@tryinner} and \code{\dbp@tryccc}) and the shortest one is
% kept via
% \code{\dbp@setparams} and \code{\dbp@updateparams}.
% \changes{v3.1.0}{2026/11/29}{Null path when the start and end points and directions are the same}
% \changes{v3.1.0}{2026/11/29}{Error for a non-positive minimum radius}
% \changes{v3.1.0}{2026/11/29}{The \protect\code{dubinspathcalc} macro uses the mean of the left and right radii}
%
%    \begin{macrocode}
\newcommand\dubinspathcalc[1]{%
  \setbox\dbp@box\hbox{%
  \dubinspathset{#1}
  \dbp@checkkey{a}{start point}{start point={0,0}}
  \dbp@checkkey{b}{end point}{end point={0,0}}
  \dbp@checkkey{anga}{start angle}{start angle=0}
  \dbp@checkkey{angb}{end angle}{end angle=0}
  \dbp@checkkey{radius}{minimum radius}{minimum radius=1pt}
  \tikzset{
    declare function={
      angtodist(\dbp@fa,\dbp@fr)={rad(abs(\dbp@fa))*\dbp@fr};
    },
  }
  \pgfmathsetmacro\dbp@anga{mod((\dbp@anga)+180,360)-180}
  \pgfmathsetmacro\dbp@angb{mod((\dbp@angb)+180,360)-180}
  \dbp@evalpoint\dbp@a
  \dbp@evalpoint\dbp@b
  \dbp@ifpgfmathcond{\dbp@radius<=0}{%
    \PackageError{dubins}{The minimum radius must be positive}%
    {A Dubins path requires a positive minimum radius.}%
    \dubinspathset{minimum radius=1pt}%
  }{}
  % centers of the four circles
  \dbp@center\dbp@ar\dbp@a{\dbp@anga-90}
  \dbp@center\dbp@al\dbp@a{\dbp@anga+90}
  \dbp@center\dbp@br\dbp@b{\dbp@angb-90}
  \dbp@center\dbp@bl\dbp@b{\dbp@angb+90}
  % null path?
  \dbp@distancebetween\dbp@c@d{\dbp@a}{\dbp@b}
  \pgfmathsetmacro\dbp@c@dang{Mod(\dbp@anga-\dbp@angb,360)}
  \dbp@ifpgfmathcond{%
    and(\dbp@c@d<0.01,or(\dbp@c@dang<0.01,\dbp@c@dang>359.99))}{%
    \dbp@setparams{lsl}{0}{0}{0}{0}
  }{%
    % CSC paths
    \dbp@tryouter{rsr}{-1}{\dbp@ar}{\dbp@br}{\dbp@setparams}
    \dbp@tryouter{lsl}{1}{\dbp@al}{\dbp@bl}{\dbp@updateparams}
    \dbp@tryinner{rsl}{-1}{\dbp@ar}{\dbp@bl}
    \dbp@tryinner{lsr}{1}{\dbp@al}{\dbp@br}
    % CCC paths
    \dbp@tryccc{lrl}{1}{\dbp@al}{\dbp@bl}
    \dbp@tryccc{rlr}{-1}{\dbp@ar}{\dbp@br}
  }
  }%
}
%    \end{macrocode}
% \end{macro}
% \iffalse
%</tikzlibrarydubins.code.tex>
% \fi
%
% \PrintChanges
%
% {
%   \setcounter{IndexColumns}{2}
%   \let\code\relax
%   \IndexPrologue{\section{Index} Italic numbers refer page where the
%   corresponding entry is described; Underlined numbers refer to the
%   code line of the definition; Roman numbers refer to the code lines
%   where the entry is used.}
%
%   \PrintIndex
% }
% \Finale
%
% \iffalse
%<*sankey-doc-preamble>
\usepackage[paper=a4paper,vmargin=1.5cm,left=4.5cm,right=3.5cm,marginparwidth=3.8cm]{geometry}
\usepackage[utf8]{inputenc}
\usepackage{cmap}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[lining,scaled=.85]{FiraMono}
\usepackage[final,protrusion=true,expansion=true]{microtype}
\usepackage{xcolor}
\PassOptionsToPackage{final,colorlinks,linkcolor=cyan!25!blue!75!black}{hyperref}
\usepackage{dtxdescribe}
\usepackage[numbered]{hypdoc}
\usepackage{fancyvrb}
\usepackage[final]{listings}
\usepackage{enumitem}
\usepackage{bookmark}
\usepackage{siunitx}
\usepackage{footnote}
\usepackage{etoc}
\usepackage{accsupp}
\usepackage{tikz}
\usetikzlibrary{positioning,patterns.meta,fit}
\usepackage[american]{babel}
\usepackage{varioref}
\usepackage{embedfile}
\usepackage{dtx-attach}
\embedfile[mimetype=text/plain]{sankey.ins}
\usepackage{sankey}

\colorlet{bgcode}{yellow!50!gray!10}
\colorlet{keyword}{blue!50!cyan!50!black}
\colorlet{comment}{red!75!black}

\newcommand\emptyaccsupp[1]{\BeginAccSupp{ActualText={}}#1\EndAccSupp{}}

\lstset{
  literate=
  {á}{{\'a}}1 {é}{{\'e}}1 {í}{{\'i}}1 {ó}{{\'o}}1 {ú}{{\'u}}1
  {Á}{{\'A}}1 {É}{{\'E}}1 {Í}{{\'I}}1 {Ó}{{\'O}}1 {Ú}{{\'U}}1
  {à}{{\`a}}1 {è}{{\`e}}1 {ì}{{\`i}}1 {ò}{{\`o}}1 {ù}{{\`u}}1
  {À}{{\`A}}1 {È}{{\'E}}1 {Ì}{{\`I}}1 {Ò}{{\`O}}1 {Ù}{{\`U}}1
  {ä}{{\"a}}1 {ë}{{\"e}}1 {ï}{{\"i}}1 {ö}{{\"o}}1 {ü}{{\"u}}1
  {Ä}{{\"A}}1 {Ë}{{\"E}}1 {Ï}{{\"I}}1 {Ö}{{\"O}}1 {Ü}{{\"U}}1
  {â}{{\^a}}1 {ê}{{\^e}}1 {î}{{\^i}}1 {ô}{{\^o}}1 {û}{{\^u}}1
  {Â}{{\^A}}1 {Ê}{{\^E}}1 {Î}{{\^I}}1 {Ô}{{\^O}}1 {Û}{{\^U}}1
  {œ}{{\oe}}1 {Œ}{{\OE}}1 {æ}{{\ae}}1 {Æ}{{\AE}}1 {ß}{{\ss}}1
  {ç}{{\c c}}1 {Ç}{{\c C}}1 {ø}{{\o}}1 {å}{{\r a}}1 {Å}{{\r A}}1
  {€}{{\texteuro}}1 {£}{{\pounds}}1 {°}{{\degres}}1
  {’}{{\textquoteright}}1 {‘}{{\textquoteleft}}1
  {«}{{<<}}1 {»}{{>>}}1
  {—}{{---}}1 {−}{{$-$}}1
  {\^\^A}{{}}0                % verbatim in .dtx file
}

\lstset{
  fancyvrb=true,
  escapechar=`,
  extendedchars=true,
  fontadjust=true,
  columns=fullflexible,
  flexiblecolumns=true,
  inputencoding=utf8,
  keepspaces=true,
  backgroundcolor=\color{bgcode},
  basicstyle=\mdseries\ttfamily,
  keywordstyle=\color{keyword},
  stringstyle=\ttfamily\color{green!50!black},
  commentstyle=\color{comment}\itshape,
  emphstyle=\bfseries\color{red},
  numbersep=5pt,
  %numbers=left,
  numberstyle=\tiny\emptyaccsupp,
  showstringspaces=false,
  upquote=true,
  aboveskip=.5\parskip,
  belowskip=.5\parskip,
  framexleftmargin=1pt,
  framexrightmargin=1pt,
  gobble=2,              % \lstlisting code in .dtx
}

\lstdefinestyle{textsmall}{basicstyle=\color{black}\small\mdseries\ttfamily}
\lstdefinestyle{textfootnotesize}{basicstyle=\color{black}\footnotesize\mdseries\ttfamily}
\lstdefinestyle{textscriptsize}{basicstyle=\color{black}\scriptsize\mdseries\ttfamily}
\lstdefinestyle{texttiny}{basicstyle=\color{black}\tiny\mdseries\ttfamily}

\lstdefinestyle{bash}{
  language=bash,
  backgroundcolor=\color{gray!10},
}
\lstdefinestyle{bashsmall}{style=bash,style=textsmall}
\lstdefinestyle{bashfootnotesize}{style=bash,style=footnotesize}
\lstdefinestyle{bashscriptsize}{style=bash,style=scriptsize}

\lstdefinestyle{LaTeX}{
  language=[LaTeX]TeX,
  moretexcs={
    abovelabel,
    ancname,
    ang,
    colorlet,
    coordinate,
    countries,
    country,
    countryname,
    cubic,
    definecolor,
    draw,
    dubinspath,
    dubinspathcalc,
    dubinspathget,
    dubinspathset,
    endcountry,
    energylabel,
    fill,
    flow,
    flowlabel,
    foreach,
    fpeval,
    gap,
    gapof,
    hashband,
    hdist,
    hshift,
    hwidth,
    ins,
    iolabel,
    Lab,
    LabSet,
    lostenergylabel,
    lostenergylabelbottom,
    metre,
    minr,
    n,
    name,
    node,
    nodename,
    num,
    outs,
    pairs,
    path,
    pdfstrcmp,
    per,
    percent,
    pgfmathsetmacro,
    pgfmathtruncatemacro,
    pos,
    q,
    Qty,
    qty,
    QtySet,
    R,
    rmdefault,
    rot,
    sankeyadvance,
    sankeydubins,
    sankeyend,
    sankeyfork,
    sankeygetnodeorient,
    sankeygetnodeqty,
    sankeynode,
    sankeynodealias,
    sankeynodeend,
    sankeynodestart,
    sankeyoutin,
    sankeyqtytolen,
    sankeyset,
    sankeystart,
    sankeyturn,
    sankeyturnleft,
    sankeyturnleftbackward,
    sankeyturnright,
    sankeyturnrightbackward,
    sfdefault,
    side,
    sisetup,
    stage,
    startcountry,
    text,
    tikzset,
    tmp,
    turnandstop,
    turnandstopbottom,
    usepackage,
    usetikzlibrary,
    vdist,
  }
}
\lstdefinestyle{LaTeXsmall}{style=LaTeX,style=textsmall}
\lstdefinestyle{LaTeXfootnotesize}{style=LaTeX,style=textfootnotesize}
\lstdefinestyle{LaTeXscriptsize}{style=LaTeX,style=textscriptsize}
\lstdefinestyle{LaTeXtiny}{style=LaTeX,style=texttiny}

\def\code{\lstinline[basicstyle=\mdseries\ttfamily\color{red!50!black}]}

\edef\samplecodename{\jobname-code.vrb}

\newcommand\constant[1]{\textcolor{violet}{\texttt{#1}}}
\newcommand\ARG[1]{\texttt{\{#1\}}}
\newcommand\OPTARG[1]{\textcolor{green!50!black}{\texttt{[#1]}}}
\newcommand\VAR[1]{\textit{\texttt{\ensuremath{\langle}#1\ensuremath{\rangle}}}}
\newcommand\NOTE[1]{\leavevmode\marginpar{#1}}

\def\mynobreakpar{\par\nobreak\@afterheading}
\def\docprefix#1{\texttt{\textcolor{gray}{#1}}}
\def\sankeykeysprefix{/sankey}

\newenvironment{sankeyoption}[5][]{% [prefix] key, val, default, initially
  \begingroup
  % 
  \def\keypath{#1}%
  \ifdefempty{\keypath}{\def\keypath{\sankeykeysprefix}}{}%
  \def\key{#2}%
  \def\val{#3}%
  \def\default{#4}%
  \def\initially{#5}%
  %\setlength\parindent{\dimexpr.5\parindent\relax}%
  % \vspace{.25\baselineskip plus .25\baselineskip minus 0mm}
  \parfillskip 0pt plus 1fil%
  \leavevmode%
  \expandafter\DescribeKey\expandafter{\key}%
  \ttfamily%
  %\hspace*{-1cm}%
  \textcolor{red!75!black}{\texttt{\docprefix{\keypath/}\key}}%
  \ifdefempty{\val}{}{=\val}%
  \hfill%
  \ifdefempty{\default}{\null}{{\rmfamily (default:\,\constant{\default})}}%
  \ifdefempty{\initially}{\null}{{\rmfamily (initially:\,\constant{\initially})}}%
  \mynobreakpar%
  \endgroup%
  \parskip=.5\baselineskip plus .25\baselineskip minus .3\baselineskip
  \parfillskip=30pt plus 1fil
  \itemize[topsep=0pt,partopsep=0pt,itemsep=0pt]\item[]
}{%
  \enditemize%
}

\newcommand\MACRO{\hspace*{0cm}}

\newlist{sankeyconstantsdesc}{description}{1}
\setlist[sankeyconstantsdesc]{align=right,labelindent=1.5em,labelsep=.5em,leftmargin=!,font=\normalfont}

\newlength{\myparskip}
\setlength{\myparskip}{.75\baselineskip plus 8\baselineskip minus .25\baselineskip}
\usepackage[skip=\myparskip]{parskip}
\setlength{\emergencystretch}{2em}
\newenvironment{miniblock}{%
  \vspace{.5\parskip}%
}{%
}

\tikzset{
  every picture/.style={
    execute at end picture={
      \begin{pgfonlayer}{background}
        \node[fit=(current bounding box),inner sep=0](bb){};
        \def\rs{5mm}
        \draw[gray!25] let
        \p{sw}=(bb.south west), \p{ne}=(bb.north east),
        \n{maxx}={ceil(\x{ne}/\rs)*\rs}, \n{minx}={floor(\x{sw}/\rs)*\rs},
        \n{maxy}={ceil(\y{ne}/\rs)*\rs}, \n{miny}={floor(\y{sw}/\rs)*\rs}
        in (\n{minx},\n{miny}) grid (\n{maxx},\n{maxy});
        \begin{scope}[overlay]
          \draw[gray!50,-latex] let
          \p{sw}=(bb.south west), \p{ne}=(bb.north east),
          \n{maxx}={ceil(\x{ne}/\rs)*\rs}, \n{minx}={floor(\x{sw}/\rs)*\rs},
          \n{maxy}={ceil(\y{ne}/\rs)*\rs}, \n{miny}={floor(\y{sw}/\rs)*\rs}
          in (\n{minx},0) -- (\n{maxx}+1mm,0);
          \draw[gray!50,-latex] let
          \p{sw}=(bb.south west), \p{ne}=(bb.north east),
          \n{maxx}={ceil(\x{ne}/\rs)*\rs}, \n{minx}={floor(\x{sw}/\rs)*\rs},
          \n{maxy}={ceil(\y{ne}/\rs)*\rs}, \n{miny}={floor(\y{sw}/\rs)*\rs}
          in (0,\n{miny}) -- (0,\n{maxy}+1mm);
        \end{scope}
      \end{pgfonlayer}
    }
  }
}

\def\MacroFont{
  \fontencoding\encodingdefault
  \fontfamily\ttdefault
  \fontseries\mddefault
  \fontshape\updefault
  \footnotesize
}

%</sankey-doc-preamble>
% \fi
\endinput

% Local Variables:
% mode: doctex
% LaTeX-verbatim-macros-with-braces-local: ("code")
% TeX-master: t
% End:
