summaryrefslogtreecommitdiff
path: root/graphics
diff options
context:
space:
mode:
authorNorbert Preining <norbert@preining.info>2024-01-17 03:01:02 +0000
committerNorbert Preining <norbert@preining.info>2024-01-17 03:01:02 +0000
commit4fd81a66c82a2ba8787c6ca78bfcc14820e4017c (patch)
treebd843b1d561c776d5f54e18c0f07c05b079bb791 /graphics
parent384734a07c53090ad651e786d248c5ba8cd4606e (diff)
CTAN sync 202401170301
Diffstat (limited to 'graphics')
-rw-r--r--graphics/pgf/contrib/zx-calculus/README.md2
-rw-r--r--graphics/pgf/contrib/zx-calculus/biblio.bib48
-rw-r--r--graphics/pgf/contrib/zx-calculus/tikzlibraryzx-calculus.code.tex2754
-rw-r--r--graphics/pgf/contrib/zx-calculus/zx-calculus.pdfbin616917 -> 1142885 bytes
-rw-r--r--graphics/pgf/contrib/zx-calculus/zx-calculus.sty3
-rw-r--r--graphics/pgf/contrib/zx-calculus/zx-calculus.tex2376
6 files changed, 4930 insertions, 253 deletions
diff --git a/graphics/pgf/contrib/zx-calculus/README.md b/graphics/pgf/contrib/zx-calculus/README.md
index de8a2d5819..55d714bed6 100644
--- a/graphics/pgf/contrib/zx-calculus/README.md
+++ b/graphics/pgf/contrib/zx-calculus/README.md
@@ -2,6 +2,6 @@
This library (based on the great TikZ and Tikz-cd packages) allows you to typeset ZX-calculus directly in LaTeX. It comes with a default (but highly customizable) style. For more information, see the documentation in [`zx-calculus.pdf`][1].
-The project is hosted at https://github.com/leo-colisson/zx-calculus , feel free to report any bug there. It is licensed under MIT and its author is Léo Colisson.
+The project, created by Léo Colisson, is hosted at https://github.com/leo-colisson/zx-calculus . Feel free to report any bug there. It is licensed under MIT.
[1]: https://raw.githubusercontent.com/leo-colisson/zx-calculus/main/doc/zx-calculus.pdf
diff --git a/graphics/pgf/contrib/zx-calculus/biblio.bib b/graphics/pgf/contrib/zx-calculus/biblio.bib
new file mode 100644
index 0000000000..dec2f682e1
--- /dev/null
+++ b/graphics/pgf/contrib/zx-calculus/biblio.bib
@@ -0,0 +1,48 @@
+@book{CK17_PicturingQuantumProcesses,
+ title = {Picturing {{Quantum Processes}}: {{A First Course}} in {{Quantum Theory}} and {{Diagrammatic Reasoning}}},
+ shorttitle = {Picturing {{Quantum Processes}}},
+ author = {Coecke, Bob and Kissinger, Aleks},
+ date = {2017},
+ publisher = {{Cambridge University Press}},
+ location = {{Cambridge}},
+ doi = {10.1017/9781316219317},
+ url = {https://www.cambridge.org/core/books/picturing-quantum-processes/1119568B3101F3A685BE832FEEC53E52},
+ urldate = {2021-11-17},
+ abstract = {The unique features of the quantum world are explained in this book through the language of diagrams, setting out an innovative visual method for presenting complex theories. Requiring only basic mathematical literacy, this book employs a unique formalism that builds an intuitive understanding of quantum features while eliminating the need for complex calculations. This entirely diagrammatic presentation of quantum theory represents the culmination of ten years of research, uniting classical techniques in linear algebra and Hilbert spaces with cutting-edge developments in quantum computation and foundations. Written in an entertaining and user-friendly style and including more than one hundred exercises, this book is an ideal first course in quantum theory, foundations, and computation for students from undergraduate to PhD level, as well as an opportunity for researchers from a broad range of fields, from physics to biology, linguistics, and cognitive science, to discover a new set of tools for studying processes and interaction.},
+ isbn = {978-1-107-10422-8},
+ file = {/home/leo/Zotero/storage/ACRTPLF2/Bob Coecke, Aleks Kissinger - Picturing Quantum Processes_ A First Course in Quantum Theory and Diagrammatic Reasoning (2017, Cambridge Uni.djvu;/home/leo/Zotero/storage/H4JRJABV/Kissinger_Coecke.pdf;/home/leo/Zotero/storage/MX3QRG3Z/1119568B3101F3A685BE832FEEC53E52.html}
+}
+
+@unpublished{CHP19_SZXcalculusScalableGraphical,
+ title = {{{SZX-calculus}}: {{Scalable Graphical Quantum Reasoning}}},
+ shorttitle = {{{SZX-calculus}}},
+ author = {Carette, Titouan and Horsman, Dominic and Perdrix, Simon},
+ date = {2019},
+ eprint = {1905.00041},
+ eprinttype = {arxiv},
+ primaryclass = {quant-ph},
+ pages = {15 pages},
+ doi = {10.4230/LIPIcs.MFCS.2019.55},
+ url = {http://arxiv.org/abs/1905.00041},
+ urldate = {2022-09-08},
+ abstract = {We introduce the Scalable ZX-calculus (SZX-calculus for short), a formal and compact graphical language for the design and verification of quantum computations. The SZX-calculus is an extension of the ZX-calculus, a powerful framework that captures graphically the fundamental properties of quantum mechanics through its complete set of rewrite rules. The ZX-calculus is, however, a low level language, with each wire representing a single qubit. This limits its ability to handle large and elaborate quantum evolutions. We extend the ZX-calculus to registers of qubits and allow compact representation of sub-diagrams via binary matrices. We show soundness and completeness of the SZX-calculus and provide two examples of applications, for graph states and error correcting codes.},
+ archiveprefix = {arXiv},
+ keywords = {Quantum Physics},
+ file = {/home/leo/Zotero/storage/F4PPGLC6/Carette et al. - 2019 - SZX-calculus Scalable Graphical Quantum Reasoning.pdf;/home/leo/Zotero/storage/MUPUEFDZ/1905.html}
+}
+
+@unpublished{van20_ZXcalculusWorkingQuantum,
+ title = {{{ZX-calculus}} for the Working Quantum Computer Scientist},
+ author = {van de Wetering, John},
+ options = {useprefix=true},
+ date = {2020-12-27},
+ eprint = {2012.13966},
+ eprinttype = {arxiv},
+ primaryclass = {quant-ph},
+ url = {http://arxiv.org/abs/2012.13966},
+ urldate = {2021-05-29},
+ abstract = {The ZX-calculus is a graphical language for reasoning about quantum computation that has recently seen an increased usage in a variety of areas such as quantum circuit optimisation, surface codes and lattice surgery, measurement-based quantum computation, and quantum foundations. The first half of this review gives a gentle introduction to the ZX-calculus suitable for those familiar with the basics of quantum computing. The aim here is to make the reader comfortable enough with the ZX-calculus that they could use it in their daily work for small computations on quantum circuits and states. The latter sections give a condensed overview of the literature on the ZX-calculus. We discuss Clifford computation and graphically prove the Gottesman-Knill theorem, we discuss a recently introduced extension of the ZX-calculus that allows for convenient reasoning about Toffoli gates, and we discuss the recent completeness theorems for the ZX-calculus that show that, in principle, all reasoning about quantum computation can be done using ZX-diagrams. Additionally, we discuss the categorical and algebraic origins of the ZX-calculus and we discuss several extensions of the language which can represent mixed states, measurement, classical control and higher-dimensional qudits.},
+ archiveprefix = {arXiv},
+ keywords = {Not published,Quantum Physics,Reviews,ZX-Calculus},
+ file = {/home/leo/Zotero/storage/ZY35RJC6/van de Wetering - 2020 - ZX-calculus for the working quantum computer scien.pdf;/home/leo/Zotero/storage/LFUZAV6Q/2012.html}
+}
diff --git a/graphics/pgf/contrib/zx-calculus/tikzlibraryzx-calculus.code.tex b/graphics/pgf/contrib/zx-calculus/tikzlibraryzx-calculus.code.tex
index af29676b46..c23955e6cf 100644
--- a/graphics/pgf/contrib/zx-calculus/tikzlibraryzx-calculus.code.tex
+++ b/graphics/pgf/contrib/zx-calculus/tikzlibraryzx-calculus.code.tex
@@ -1,26 +1,43 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-%%% Version: 2021/10/22
+%%% Version: 2.0
%%% License: MIT
%%% Author: Léo Colisson
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%% Understand why if a "fake" alias does not exists but was created before I get no error
+
+%% TODO:
+%% - Check why this displays weirdly:
+% \begin{ZX}[myBold]
+% & & \zxDivider[a=div]{} \ar['>, to=Gll] \ar['>, to=Gll2] & & & \\
+% & \zxH{} \ar[to=div,<',wce] \ar[to=root,<.] & & \zxMatrix[a=Gll]'*{G^\matrixUr} & \zxMatrix[a=Gll2]'/*{G^\matrixUr} & \\
+% \zxN{} \ar[rr] & & [\zxwCol] \zxZ[a=root]{} \ar[B,rrr] \ar[to=Gll,.>] \ar[to=Gll2,.>] & & &
+% \end{ZX}
+%
% A tikzlibrary[libraryName].code.tex is loaded automatically by tikz when using
% \usetikzlibrary{libraryName}. Therefore, you should just use
% \usetikzlibrary{zx} to load this library. We also provide a package to
% directly load this library using \usepackage{zx}.
+%%% Some random notes for myself:
+%%% - \tikz@pp@name{X} outputs the name prefix + X + the name suffix, where these prefix are local prefix assigned to all node names. While they are often empty, it might not be always the case.
+
\RequirePackage{amssymb} % For short minus
-\RequirePackage{etoolbox}
+\RequirePackage{etoolbox} % \AfterEndPreamble...
\RequirePackage{ifthen} % For conditions
\RequirePackage{xparse} % For NewDocumentComments
\RequirePackage{bm} % For bold math fonts
+\RequirePackage{xstring} % For \IfInteger
+\RequirePackage{varwidth} % For varwidth
-\usetikzlibrary{cd,backgrounds,positioning,shapes,calc,intersections}
+\usetikzlibrary{cd,backgrounds,positioning,shapes,calc,intersections,fit,decorations.pathreplacing}
% Declare layers.
\pgfdeclarelayer{background} % Fox boxes using "fit" to group parts of the graph.
-\pgfdeclarelayer{edgelayer} % For edges that are explicitely defined "wc"
-\pgfdeclarelayer{nodelayer} % For nodes... in theory, this fails for now. https://tex.stackexchange.com/questions/618823/node-on-layer-style-in-tikz-matrix-tikzcd
+\pgfdeclarelayer{belownodelayer} % For nodes that always want to stay below any arrow...
+\pgfdeclarelayer{edgelayer} % For nodes that always want to stay below any arrow...
+\pgfdeclarelayer{nodelayer} % For nodes... in theory, this fails for now.
\pgfdeclarelayer{main}
+\pgfdeclarelayer{abovenodelayer} % For nodes that want to stay above others.
\pgfdeclarelayer{box} % For boxes using "fit" to fake multi-column boxes
\pgfdeclarelayer{labellayer} % For labels... in theory, this fails for now. https://tex.stackexchange.com/questions/618823/node-on-layer-style-in-tikz-matrix-tikzcd
\pgfdeclarelayer{foreground} % For the user, if they want to put anything really above everything.
@@ -33,6 +50,7 @@
\definecolor{colorZxZ}{RGB}{204,255,204}
\definecolor{colorZxX}{RGB}{255,136,136}
\definecolor{colorZxH}{RGB}{255,255,0}
+\definecolor{colorZxMatrix}{RGB}{200,200,200}
%%% Some wires (the one having an intermediate H, X, or S gate) may need some additional space for
%%% specific columns.
@@ -66,9 +84,12 @@
%% Default separation between rows and columns
\newcommand{\zxDefaultColumnSep}{1.5mm}
\newcommand{\zxDefaultRowSep}{1.5mm}
+% In circuit mode, we have mostly gates, and the default setting might be too small
+\newcommand{\zxDefaultColumnSepCircuit}{4mm}
+\newcommand{\zxDefaultRowSepCircuit}{4mm}
% To cancel the default tow separation
-\newcommand{\zxZeroCol}{-\zxDefaultColumnSep}
-\newcommand{\zxZeroRow}{-\zxDefaultRowSep}
+\newcommand{\zxZeroCol}{-\pgfmatrixcolumnsep}%\zxDefaultColumnSep}
+\newcommand{\zxZeroRow}{-\pgfmatrixrowsep}%\zxDefaultRowSep}
%% When adding two lines with only empty nodes, it can create quite a large space. Use this to reduce it
%% Yes, we can add multiple arguments, space will add up (see documentation pgfmatrixnextcell)
\newcommand{\zxNCol}{-\zxDefaultColumnSep,.5mm}
@@ -92,6 +113,9 @@
\def\zxDefaultSoftAngleO{40}
\def\zxDefaultSoftAngleChevron{60}
+\def\zxGroundScale{1.8}
+\def\zxMeterScale{1}
+
% Styles for O,N,... (new bezier version)
\tikzset{
/zx/args/-andL/.cd,
@@ -126,6 +150,15 @@
% Scale to use when scaling 3 dots
\def\zxScaleDots{.7}
+% Size of the minimum width of boxes
+% We need 4ex to fit most elements in height, at least with the default font (f_a is the heigher), and 1.83em to fit them in width (W is the wider).
+% Since these two values are quite close, lets take the maximum (1.83em) to have a square shape
+\def\zxBoxMinimumWidth{1.83em}
+\def\zxBoxMinimumHeight{1.83em}
+\def\zxEltMinimumWidth{1.83em}
+\def\zxEltMinimumHeight{1.83em}
+
+
% 0.4pt is default in tikz. Also used to ensure it has not been modified document wise by other libraries
% (quantikz notably changes this parameter).
\newcommand{\zxDefaultLineWidth}{0.4pt}
@@ -168,12 +201,43 @@
% center does not exists), but then the wire will be hidden behind the node (it is a problem
% mostly if you use H nodes a lot, otherwise we recommend this solution):
\def\zxWireInsideIfNoIntersectionName{}
-% If you prefer to start the wire on the surface of the node, do that instead...
-% but be aware that the shape of the wire will be changed a lot, since we can't use anymore the
-% fake anchors... You could also define a style that does that.
+% If you prefer to start the wire on the surface of the node, do that instead... but it will take longer to compute. See also our ui style
+% as the default styles are not meant to work in that setting.
% \let\zxWireInsideIfNoIntersectionName\undefined
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%% Global temporary variables/dimensions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+\newsavebox{\zx@tmp@box}%
+
+%%%%%%%%%%%%%%%%%%%%%
+%%%% Utils
+%%%%%%%%%%%%%%%%%%%%%
+
+% by default "execute at end node" accumulate by adding at the end of the existing value,
+% it can be helpful to reset completely the value, or add it before
+\tikzset{
+ zx execute before end node/.code={%
+ \def\zx@options{#1}%
+ \edef\zx@cmd{%
+ \noexpand\def\noexpand\tikz@atend@node{\expandonce{\zx@options}\expandonce{\tikz@atend@node}}%
+ }%
+ \zx@cmd%
+ },
+ zx set execute at begin node/.code={%
+ \def\tikz@atbegin@node{#1}%
+ },
+ zx set execute at end node/.code={%
+ \def\tikz@atend@node{#1}%
+ },
+ zx reset execute node/.style={
+ zx set execute at begin node={},
+ zx set execute at end node={},
+ },
+}
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Adding anchors
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@@ -257,6 +321,14 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%% For readability
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+\NewExpandableDocumentCommand{\zxWire}{m}{
+ \arrow[r,#1]
+}
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Tikz styles
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@@ -421,12 +493,10 @@
%%% First intersection: we use the line between the two nodes... but it's really ugly (e.g. in o it does not make a lot of sense)
\begin{pgfinterruptboundingbox}%
\ifdefined\zxIntersectionLineBetweenStartEnd%
- %% Not idea why, but x axis is inverted???
- \pgfpointdiff{\tikz@scan@one@point\pgf@process(#2)}{\pgfpointanchor{#1}{center}}%
- \pgfpathmoveto{\pgfpoint{-\pgf@x}{\pgf@y}}%
- % And now both axis are???
- \pgfpointdiff{\tikz@scan@one@point\pgf@process(#3)}{\pgfpointanchor{#1}{center}}%
- \pgfpathlineto{\pgfpoint{-\pgf@x}{-\pgf@y}}%
+ \pgfpointdiff{\pgfpointanchor{#1}{center}}{\tikz@scan@one@point\pgf@process(#2)}%
+ \pgfpathmoveto{\pgfpoint{\pgf@x}{\pgf@y}}%
+ \pgfpointdiff{\pgfpointanchor{#1}{center}}{\tikz@scan@one@point\pgf@process(#3)}%
+ \pgfpathlineto{\pgfpoint{\pgf@x}{\pgf@y}}%
\else%
%% We use now the method used for bezier curve (at least it's what I see "experimentally")
%% More precisely, we use the direction of the bezier curve to know where to start the wire.
@@ -546,6 +616,12 @@
\fi%
}%
+\def\zxRevertToNormalSpacing{%
+ \thinmuskip=3.0mu\relax%
+ \medmuskip=4.0mu plus 2.0mu minus 4.0mu\relax%
+ \thickmuskip=5.0mu plus 5.0mu\relax%
+}
+
% Styles. User should not modify "wires definition", but is free to change:
% - "/zx/default style nodes/" to change completely the node style
% - "/zx/user overlay nodes" to add stuff on current node style
@@ -559,12 +635,58 @@
draw,
-,
line width=\zxDefaultLineWidth,
+ % This changes globally the thickness of boxes and wires, empty by default,
+ % mostly useful to change gates and wires at the same time
+ zx thickness wires style,
%%% Useful shortcut (shorter lines means easy "align" of & symbols. Love M-x align in emacs btw.)
ls/.style={looseness=##1},
looseness wires only/.style={% Looseness used for wires only.
looseness=1.2,
},
lw/.style={looseness wires only},
+ bold/.style={very thick},
+ non bold/.style={
+ line width=\zxDefaultLineWidth,
+ % We need to disable bold later since "bold wires" will automatically add bold at the end
+ bold/.style={},
+ },
+ B/.style={bold},
+ NB/.style={non bold},
+ %% Adds a n above to denote the number of wires
+ Bn/.style={BnArgs={##1}{}},
+ Bn/.default={n},
+ boldn/.style={BnArgs={##1}{}},
+ boldn/.default={n},
+ Bn'/.style={Bn'Args={##1}{}},
+ Bn'/.default={n},
+ boldn'/.style={Bn'Args={##1}{}},
+ boldn'/.default={n},
+ Bn./.style={Bn.Args={##1}{}},
+ Bn./.default={n},
+ boldn./.style={Bn.Args={##1}{}},
+ boldn./.default={n},
+ Bn-/.style={Bn-Args={##1}{}},
+ Bn-/.default={n},
+ boldn-/.style={Bn-Args={##1}{}},
+ boldn-/.default={n},
+ %% For wires left to right
+ Bn'Args/.style 2 args={bold, "|" {rotate=65-90,anchor=center,##2}, "##1" {above,yshift=3pt,##2}},
+ Bn'Args/.default={n}{},
+ Bn.Args/.style 2 args={bold, "|" {rotate=65-90,anchor=center,##2}, "##1" {below,yshift=-3pt,##2}},
+ Bn.Args/.default={n}{},
+ %% for wires top/down (left,right)
+ BnArgs/.style 2 args={bold, "|" {rotate=-65,anchor=center,##2}, "##1" {left,xshift=-2pt,##2}},
+ BnArgs/.default={n}{},
+ Bn-Args/.style 2 args={bold, "|" {rotate=-65,anchor=center,##2}, "##1" {right,xshift=2pt,##2}},
+ Bn-Args/.default={n}{},
+ type'/.style={Bn'={##1}, non bold},
+ type./.style={Bn.={##1}, non bold},
+ type/.style={Bn={##1}, non bold},
+ type-/.style={Bn-={##1}, non bold},
+ % boldnPos/.style={bold, "/" {anchor=center}, "##1" {yshift=3pt}},
+ % boldnPos/.default={n}{pos=50},
+ % boldn.Pos/.style={bold, "/" {anchor=center}, "##1" {below,yshift=-3pt}},
+ % boldn.Pos/.default={n}{pos=50},
% Use this when you are drawing lines between none nodes only (like swap gates...) in IO mode
between none/.style={
looseness wires only,
@@ -633,18 +755,34 @@
C@generic/.style n args={8}{ % min/max, angle1, angle2, anchor, \x or \y, \y or \x, where to move,radius code (for circle should be "radius=\n3")
to path={
\pgfextra{%% <- we will use def... so need to "exit" a few seconds pgf
+ \zxTryFirstSubnodeThenAnchorThenNode{\tikztostart}{true ##4}{##4}%
+ \edef\StartPoint{\zx@result}%
+ % % Test if tikztostart is a point or a node, and define StartPoint accordingly.
+ % \ifPgfpointOrNode{\tikztostart}{%
+ % \def\StartPoint{\tikztostart}%
+ % }{%
+ % % For some nodes, "north" might not point to north (notably after a rotation). So we can define some anchors "true north" that actually point
+ % % to the north.
+ % % Test if "true north" etc exists:
+ % \ifAnchorExistsNodeSpecific{\tikztostart}{true ##4}{%
+ % \def\StartPoint{\tikztostart.true ##4}%
+ % }{%
+ % \def\StartPoint{\tikztostart.##4}%
+ % }%
+ % }%
% Test if tikztostart is a point or a node, and define StartPoint accordingly.
- \ifPgfpointOrNode{\tikztostart}{%
- \def\StartPoint{\tikztostart}%
- }{%
- \def\StartPoint{\tikztostart.##4}%
- }%
- % Test if tikztostart is a point or a node, and define StartPoint accordingly.
- \ifPgfpointOrNode{\tikztotarget}{%
- \def\TargetPoint{\tikztotarget}%
- }{%
- \def\TargetPoint{\tikztotarget.##4}%
- }%
+ \zxTryFirstSubnodeThenAnchorThenNode{\tikztotarget}{true ##4}{##4}%
+ \edef\TargetPoint{\zx@result}%
+ % \ifPgfpointOrNode{\tikztotarget}{%
+ % \def\TargetPoint{\tikztotarget}%
+ % }{%
+ % % Test if "true north" etc exists:
+ % \ifAnchorExistsNodeSpecific{\tikztotarget}{true ##4}{%
+ % \def\TargetPoint{\tikztotarget.true ##4}%
+ % }{%
+ % \def\TargetPoint{\tikztotarget.##4}%
+ % }%
+ % }%
}%
(\StartPoint) % <- the path starts at StartPoint
%%% Get x coordinate of left-most point
@@ -676,7 +814,7 @@
\pgfmathapproxequalto{##52}{\n1}%
}%
\ifpgfmathcomparison\else -- (\TargetPoint)\fi
- \tikztonodes% All to path finishes with that to deal with futur nodes I think
+ \tikztonodes% All to path finishes with that to deal with future nodes I think
}
},
% At the first version, styles were defined using in=... out=... looseness=... However
@@ -684,10 +822,6 @@
% too close or too far appart. However, it may still be useful, so now we define the old
% styles, that you can use them using \ar[r,IO,C].
% NB: for the newest styles, we add new anchors to the nodes depending on the direction.
- % I also wanted to add more complicated ways to configqure the starting point (i.e. start at the boundary
- % and not behind the node), but seems like it's hard (impossible?) to do with matrices...
- % The reason is that the intersection library seems to fail with matrices.
- % If you know how to solve that, you can help here: https://tex.stackexchange.com/questions/619274
C/.style={C@generic={min}{90}{180+90}{west}{\x}{\y}{(\n1,\y1)}{y radius=\n3, x radius=##1*\n3}},
C/.default=1,
% Like C, but rotated
@@ -866,30 +1000,49 @@
bezier 4 y={\pgfkeysvalueof{/zx/args/-andL/1-}}{\pgfkeysvalueof{/zx/args/-andL/1L}}{\pgfkeysvalueof{/zx/args/-andL/2-}}{\pgfkeysvalueof{/zx/args/-andL/2L}}
}%
},
+ %% /zx/utils/change@tikz@fake@center={\tikztostart}{fake center west}{\myoutput} will set \myoutput to be the coordinate of the fake center
+ %% if it exists, and of center otherwise (and if tikztostart is already a coordinate, we just set myoutput to this coordinate):
% Directions: configure start/end points to "fake center *" if it exists.
% If the input is not a node, it's copied to ##3
/zx/utils/change@tikz@fake@center/.code n args={3}{%
% ##1: \tikztostart or \tikztotarget,
% ##2: fake center north...
% ##3 name of result. e.g. \tikztostart
- \ifPgfpointOrNode{##1}{%
- %%% Sometimes, ##1 is not 1pt,2pt but "tikz-1-2.north east". Since later we use
- %%% a parsing mechanism which assumes that we have a coordinate... this is a problem.
- \edef##3{##1}%
- % This is a great explaination of how parsing is done in tikz:
- % https://tex.stackexchange.com/a/516897/116348
- }{% This is a node, not a point:
- \ifAnchorExists{##1}{##2}{%
- \pgfpointanchor{##1}{##2}%
- }{%
- \pgfpointanchor{##1}{center}%
- }%
- %%% Whoo, pgfpoint only redefine pgf@x/pgf@y, but in no way it stores it!!!
- %%% So can't do \pgfpoint{\pgf@x}{\pgf@y}...
- %%% I needed to create my own system... see \zx@parse@coordx.
- \edef##3{\the\pgf@x,\the\pgf@y}%
- }%
+ % This sets \zx@result to the appropriate node or to center if no exists:
+ \zxTryFirstSubnodeThenAnchorThenNodeToCoordinate{##1}{##2}{center}%
+ \edef##3{\zx@result}%
},
+ % /zx/utils/change@tikz@fake@center/.code n args={3}{%
+ % % ##1: \tikztostart or \tikztotarget,
+ % % ##2: fake center north...
+ % % ##3 name of result. e.g. \tikztostart
+ % \ifPgfpointOrNode{##1}{%
+ % %%% Sometimes, ##1 is not (1pt,2pt) but "tikz-1-2.north east". Since later we use
+ % %%% a parsing mechanism which assumes that we have a coordinate... this is a problem.
+ % \edef##3{##1}%
+ % % This is a great explaination of how parsing is done in tikz:
+ % % https://tex.stackexchange.com/a/516897/116348
+ % }{% This is a node, not a point:
+ % % "zx add anchor to node" might define per-node anchors, and they are stored in
+ % % a macro called like \pgf@sh@ma@tikz@f@3-2-2, so we need to read this first:
+ % % TODO: maybe use pp@name everywhere? (see comment beginning of this file)
+ % \begingroup% This group avoids pollution done by executing pgf@sh@ma@NODENAME
+ % \pgfutil@ifundefined{pgf@sh@ma@\tikz@pp@name{##1}}{}{%
+ % % We the per-node macro exists, we run it.
+ % \csname pgf@sh@ma@\tikz@pp@name{##1}\endcsname%
+ % }%
+ % \ifAnchorExists{##1}{##2}{%
+ % \pgfpointanchor{##1}{##2}%
+ % }{%
+ % \pgfpointanchor{##1}{center}%
+ % }%
+ % %%% Whoo, pgfpoint only redefine pgf@x/pgf@y, but in no way it stores it!!!
+ % %%% So can't do \pgfpoint{\pgf@x}{\pgf@y}...
+ % %%% I needed to create my own system... see \zx@parse@coordx.
+ % \xdef##3{\the\pgf@x,\the\pgf@y}%
+ % \endgroup%
+ % }%
+ % },
% Directions: configure start/end points to the intersection between
% the "fake center *" if it exists and the "fake center *" of the destination.
% If the input is not a node, nothing is done.
@@ -971,6 +1124,119 @@
start anchor=,
end anchor=,
},
+ % Classical wires: we make them bend
+ classical/.style={
+ double distance=1pt,
+ double,
+ line cap=rect,
+ % the .5pt is half of the double distance
+ shorten <=.5pt+.5\pgflinewidth,
+ shorten >=.5pt+.5\pgflinewidth,
+ % to path={},
+ },
+ cl/.style={classical},
+ connect -|/.style={
+ on layer={edgelayer},
+ to path={(\tikztostart) -| (\tikztotarget) \tikztonodes}
+ },
+ --|/.style={connect -|},
+ connect |-/.style={
+ on layer={edgelayer},
+ to path={(\tikztostart) |- (\tikztotarget) \tikztonodes}
+ },
+ |--/.style={connect |-},
+ horizontal |--/.style={
+ on layer={edgelayer},
+ to path={(\tikztostart |- \tikztotarget) -- (\tikztotarget) \tikztonodes}
+ },
+ horizontal --|/.style={
+ on layer={edgelayer},
+ to path={(\tikztostart) -- (\tikztostart -| \tikztotarget) \tikztonodes}
+ },
+ vertical |--/.style={
+ on layer={edgelayer},
+ to path={(\tikztostart) -- (\tikztostart |- \tikztotarget) \tikztonodes}
+ },
+ vertical --|/.style={
+ on layer={edgelayer},
+ to path={(\tikztostart -| \tikztotarget) -- (\tikztotarget) \tikztonodes}
+ },
+ h|--/.style={horizontal |--},
+ h--|/.style={horizontal --|},
+ v|--/.style={vertical |--},
+ v--|/.style={vertical --|},
+ % fake a wire being above by putting white stuff around
+ 3d above/.style={
+ draw=white,
+ double=black,
+ double distance=\pgflinewidth,
+ very thick,
+ },
+ %% To go to a subnode defined in a pic with from subnode=mysubnode.
+ start subnode/.code={%
+ \zxGetSubnodeOfNode{\tikzcd@ar@start}{##1}{\edef\tikzcd@ar@start{\zx@result}}{\PackageError{zx-calculus}{In "start subnode=##1", \zx@error}}%
+ },
+ % start subnode/.code={%
+ % \edef\zx@tmp{zx@alias@\zxCurrentDiagram @\tikzcd@ar@start}%
+ % % First, rewrite \tikzcd@ar@start so that it equals the name of the current node without alias
+ % \ifcsname \zx@tmp\endcsname% There exists an alias
+ % \edef\zx@tmp@alias{(alias \zx@tmp) }% Mostly for the error message
+ % \edef\tikzcd@ar@start{\csname zx@alias@\zxCurrentDiagram @\tikzcd@ar@start\endcsname}%
+ % \else%
+ % \edef\zx@tmp@alias{(no alias) }% Mostly for the error message
+ % \fi
+ % % First, we check if there is a node with this name on this node. If not, we will try with the parent node
+ % \@ifundefined{pgf@sh@ns@\tikzcd@ar@start ##1}{%
+ % % The current node has no such subnode name: let's start its parent.
+ % \@ifundefined{\tikzcd@ar@start -zxOriginalRow}{%
+ % % There is no original coordinate: error
+ % \PackageError{zx-calculus}{In "start subnode=##1", the subnode ##1 of node \tikzcd@ar@start \zx@tmp@alias does not exist.}{}%
+ % }{%
+ % % There is an original coordinate: we try to see if the original node admits a subnode.
+ % \edef\zx@tmp@originalRow{\csname \tikzcd@ar@start-zxOriginalRow\endcsname}%
+ % \edef\zx@tmp@originalCol{\csname \tikzcd@ar@start-zxOriginalCol\endcsname}%
+ % \@ifundefined{pgf@sh@ns@\zxCurrentDiagram-\zx@tmp@originalRow-\zx@tmp@originalCol ##1}{%
+ % \PackageError{zx-calculus}{In "start subnode=##1", the subnode ##1 of aliased node \tikzcd@ar@start{} \zx@tmp@alias does not exist (even in the parent node at coordinate \zx@tmp@originalRow - \zx@tmp@originalCol).}{}%
+ % }{%
+ % \edef\tikzcd@ar@start{\zxCurrentDiagram-\zx@tmp@originalRow-\zx@tmp@originalCol ##1}%%
+ % }%
+ % }%
+ % }{% There exists a subnode in the current name
+ % \edef\tikzcd@ar@start{\tikzcd@ar@start ##1}%%
+ % }%
+ % },
+ end subnode/.code={% The edef is needed, or it always go into the first loop and might give errors later
+ \zxGetSubnodeOfNode{\tikzcd@ar@target}{##1}{\edef\tikzcd@ar@target{\zx@result}}{\PackageError{zx-calculus}{In "end subnode=##1", \zx@error}}%
+ },
+ % end subnode/.code={% The edef is needed, or it always go into the first loop and might give errors later
+ % \edef\zx@tmp{zx@alias@\zxCurrentDiagram @\tikzcd@ar@target}%
+ % % First, rewrite \tikzcd@ar@target so that it equals the name of the current node without alias
+ % \ifcsname \zx@tmp\endcsname% There exists an alias
+ % \edef\zx@tmp@alias{(alias \zx@tmp) }% Mostly for the error message
+ % \edef\tikzcd@ar@target{\csname zx@alias@\zxCurrentDiagram @\tikzcd@ar@target\endcsname}%
+ % \else%
+ % \edef\zx@tmp@alias{(no alias) }% Mostly for the error message
+ % \fi
+ % % First, we check if there is a node with this name on this node. If not, we will try with the parent node
+ % \@ifundefined{pgf@sh@ns@\tikzcd@ar@target ##1}{%
+ % % The current node has no such subnode name: let's start its parent.
+ % \@ifundefined{\tikzcd@ar@target -zxOriginalRow}{%
+ % % There is no original coordinate: error
+ % \PackageError{zx-calculus}{In "end subnode=##1", the subnode ##1 of node \tikzcd@ar@target{} \zx@tmp@alias does not exist.}{}%
+ % }{%
+ % % There is an original coordinate: we try to see if the original node admits a subnode.
+ % \edef\zx@tmp@originalRow{\csname \tikzcd@ar@target-zxOriginalRow\endcsname}%
+ % \edef\zx@tmp@originalCol{\csname \tikzcd@ar@target-zxOriginalCol\endcsname}%
+ % \@ifundefined{pgf@sh@ns@\zxCurrentDiagram-\zx@tmp@originalRow-\zx@tmp@originalCol ##1}{%
+ % \PackageError{zx-calculus}{In "end subnode=##1", the subnode ##1 of aliased node \tikzcd@ar@target{} \zx@tmp@alias does not exist (even in the parent node at coordinate \zx@tmp@originalRow - \zx@tmp@originalCol).}{}%
+ % }{%
+ % \edef\tikzcd@ar@target{\zxCurrentDiagram-\zx@tmp@originalRow-\zx@tmp@originalCol ##1}%%
+ % }%
+ % }%
+ % }{% There exists a subnode in the current name
+ % \edef\tikzcd@ar@target{\tikzcd@ar@target ##1}%%
+ % }%
+ % },
%% Forced versions are versions which do not nicely fallback to center if shape does not
%% have "fake center XXX". This is used mostly for wires based on in/out (our function b.
%% Not sure how to have a code which always fallback to center if shape does not.
@@ -1258,9 +1524,11 @@
N.-/.default=\zxDefaultSoftAngleN,
},
% No line but vdots/dots in between.
- 3 vdots/.style={draw=none, "\makebox[0pt][r]{##1}\scalebox{\zxScaleDots}{$\cvdotsCenterMathline$}" anchor=center},
+ 3 vdots/.style={draw=none, "\makebox[0pt][r]{\footnotesize\smash{##1\,}}\scalebox{\zxScaleDots}{$\cvdotsCenterMathline$}" {anchor=center,zxNormalFont}},
3 vdots/.default={},
- 3 dots/.style={draw=none, "\makebox[0pt][r]{##1}\scalebox{\zxScaleDots}{$\chdots$}" anchor=center},
+ 3 vdotsr/.style={draw=none, "\scalebox{\zxScaleDots}{$\cvdotsCenterMathline$}\makebox[0pt][l]{\footnotesize\smash{\,##1}}" {anchor=center,zxNormalFont}},
+ 3 vdotsr/.default={},
+ 3 dots/.style={draw=none, "\makebox[0pt][r]{\footnotesize\smash{##1}}\scalebox{\zxScaleDots}{$\chdots$}" {anchor=center,zxNormalFont}},
3 dots/.default={},
% Add a Hadmard/Z/X (no phase) in the middle of the line. Practical to add small nodes without creating
% a new column/row. However, make sure the corresponding row/column is larger, using &[\zxHCol]
@@ -1272,7 +1540,19 @@
Z/.default={},
X/.style={"" {zxNoPhaseSmallX,anchor=center,##1}},
X/.default={},
- % Arrow will go out from the center of the shape instead of from the border. Useful
+ % Sometimes, it might be handy to specify an anchor only if no anchor was set before, notably when using "post arrow style if end node" (see
+ % for instance the Divider).
+ end anchor if not set/.code={%
+ \ifx\tikzcd@endanchor\pgfutil@empty% If there is no anchor, we can set ours:
+ \pgfkeysalso{/tikz/commutative diagrams/end anchor={##1}}%
+ \fi%
+ },
+ start anchor if not set/.code={%
+ \ifx\tikzcd@startanchor\pgfutil@empty% If there is no anchor, we can set ours:
+ \pgfkeysalso{/tikz/commutative diagrams/start anchor=##1}%
+ \fi%
+ },
+ % Arrow will go out from the center of the shape instead of from the border. Useful e.g.
% when connecting nodes with different shapes, it will give back a symetric connection.
wire centered/.style={
on layer=edgelayer,
@@ -1295,14 +1575,90 @@
/tikz/commutative diagrams/end anchor=,
},
},
+ %% Will be loaded in tikzcd options directly.
+ /zx/styles/rounded style preload/.style={
+ content fixed baseline/.style={
+ /zx/user overlay nodes/.style={
+ zxShort/.append style={content fixed baseline},
+ % fixed baseline gives poor result in fractions, so we disable it here
+ zxSpecificFrac/.append style={content vertically centered},
+ },
+ },
+ content fixed baseline also frac/.style={
+ /zx/user overlay nodes/.style={
+ zxShort/.append style={content fixed baseline},
+ },
+ },
+ content vertically centered/.style={
+ /zx/user overlay nodes/.style={
+ zxShort/.append style={content vertically centered}
+ },
+ },
+ /zx/styles/rounded style common nodes and ZX,
+ },
+ % These styles make sense both in "ZX" options and in nodes options.
+ /zx/styles/rounded style common nodes and ZX/.style={
+ small minus/.code={
+ \def\zxMinus{\zxShortMinus}%
+ \def\zxMinusInShort{\zxShortMinus}%
+ },
+ big minus/.code={
+ \def\zxMinus{-}%
+ \def\zxMinusInShort{-}%
+ },
+ },
/zx/styles/rounded style/.style={
+ /zx/styles/rounded style common nodes and ZX,
%% Can be redefined by user
% Style for empty nodes
+ zxSpacingInsideNodes/.style={
+ execute at begin node={\thinmuskip=0mu\medmuskip=0mu\thickmuskip=0mu}, % Reduce space around +/-...
+ },
+ zxNormalSpacing/.style={
+ execute at begin node={\thinmuskip=3.0mu\medmuskip=4.0mu plus 2.0mu minus 4.0mu\thickmuskip=5.0mu plus 5.0mu}, %
+ },
+ %% Normalize fonts to avoid different rendering when document has a different font shape.
+ zxNormalFont/.style={
+ font={\fontsize{10}{12}\selectfont},
+ },
+ zxTinyFont/.style={
+ font={\fontsize{6}{6}\selectfont},
+ },
+ zxTinyFontAndSpacing/.style={
+ zxSpacingInsideNodes,
+ zxTinyFont,
+ },
+ % Practical styles to either vertically center the content, or fix the position of the baseline.
+ content fixed baseline/.style={
+ text height=1.5mm,%5.4pt,%1.5mm,%.45em,
+ text depth=0.1mm,%1.8pt,%0.1mm,%.15em,
+ },
+ % Style for empty nodes
+ content vertically centered/.style={
+ text height=,
+ text depth=,
+ },
+ bold/.style={very thick},
+ B/.style={bold},
+ non bold/.style={%
+ line width=\zxDefaultLineWidth,
+ },
+ NB/.style={non bold},
+ %% To set bold all wires connected to the current wire
+ bold wires/.style={
+ post arrow style if end node={B},
+ post arrow style if start node={B},
+ },
+ wires bold/.style={bold wires},% backward compatible
+ Bw/.style={wires bold},
+ BBw/.style={bold, wires bold,},
zxAllNodes/.style={
shape=rectangle, % Otherwise nodes are asymetrical rectangle, which is not practical in our case. Gives notably anchor "center" which is really centered compared to asymatrical rectangles
anchor=center, % Center cells
line width=\zxDefaultLineWidth,
- execute at begin node={\thinmuskip=0mu\medmuskip=0mu\thickmuskip=0mu}, % Reduce space around +/-...
+ % Normalize the font size (avoids different rendering of dots...)
+ zxSpacingInsideNodes,
+ zxNormalFont,
},
% Use this to denote an empty diagram
zxEmptyDiagram/.style={
@@ -1408,6 +1764,9 @@
stylePhaseInLabel,
fill=red!20!white
},
+ % Some styles should be applied only on frac
+ zxSpecificFrac/.style={
+ },
%%%%%%%%%%% Style defined depending on above ones. Feel free to redefine.
zxNoPhaseZ/.style={zxNoPhase,fill=colorZxZ},
zxNoPhaseX/.style={zxNoPhase,fill=colorZxX},
@@ -1523,23 +1882,23 @@
}%
}%
},
- pil/.style={phase in label=##1},
+ pil/.style={phase in label={##1}},
phase in label below/.style={
phase in label={label position=below,##1}
},
- pilb/.style={phase in label below=##1},
+ pilb/.style={phase in label below={##1}},
phase in label above/.style={
phase in label={label position=above,##1}
},
- pila/.style={phase in label above=##1},
+ pila/.style={phase in label above={##1}},
phase in label right/.style={
phase in label={label position=right,##1}
},
- pilr/.style={phase in label right=##1},
+ pilr/.style={phase in label right={##1}},
phase in label left/.style={
phase in label={label position=left,##1}
},
- pill/.style={phase in label left=##1},
+ pill/.style={phase in label left={##1}},
%%% Was supposed to automatically find the good style depending on content... Can't find how to do.
% Styles zxLong{X/Z} zxNoPhase{X/Z} are automatically selected by \zxZ4{...} and \zxX4{...} commands
% and zxShort is selected for fractions only like in \zxFracZ-{\pi}{4}
@@ -1609,11 +1968,11 @@
%% These take 6 arguments: additional style, sign (string "-" for minus, nothing for "+",
%% otherwise inserted directly), above fraction (no parens), below fraction (no parens), above fraction (parens), below fraction (parens).
zxFracZ6/.style n args={6}{
- add@Phase@Spider@Frac={zxNoPhaseZ}{zxShortZ}{stylePhaseInLabelZ}{##2}{##3}{##4}{##5}{##6},
+ add@Phase@Spider@Frac={zxNoPhaseZ}{zxShortZ,zxSpecificFrac}{stylePhaseInLabelZ}{##2}{##3}{##4}{##5}{##6},
/zx/post preparation labels,
/zx/user post preparation labels,
##1,
- zx@Execute@Very@End@Frac={zxNoPhaseZ}{zxShortZ}{stylePhaseInLabelZ}{##2}{##3}{##4}{##5}{##6},
+ zx@Execute@Very@End@Frac={zxNoPhaseZ}{zxShortZ,zxSpecificFrac}{stylePhaseInLabelZ}{##2}{##3}{##4}{##5}{##6},
},
zxFracX6/.style n args={6}{
add@Phase@Spider@Frac={zxNoPhaseX}{zxShortX}{stylePhaseInLabelX}{##2}{##3}{##4}{##5}{##6},
@@ -1638,9 +1997,16 @@
/zx/default style nodes/.style={
/zx/styles/rounded style
},
+ % Will be executed in tikzcd options. Useful to define a "global" option specific to a given style.
+ /zx/default style nodes preload/.style={
+ /zx/styles/rounded style preload,
+ },
% User can put here any additional property
/zx/user overlay nodes/.style={
},
+ % User can put here any global ZX options
+ /zx/user overlay/.style={
+ },
% Any additional property that needs to be loaded after add@Phase@Spider (by script, not by user).
/zx/post preparation labels/.style={
},
@@ -1653,6 +2019,34 @@
% User can add stuff in this style to improve wire styles
/zx/user overlay wires/.style={
},
+ /zx/every arrow pre/.style={%
+ /utils/exec={% We provide a way to disable the default behavior
+ \ifdefined\zxDisablePreRunStart\else%
+ %%% If it is an alias, we replace it with the original node:
+ \ifcsname zx@alias@\zxCurrentDiagram @\tikzcd@ar@start\endcsname% This is an alias: let's rename it to the original node
+ \edef\tikzcd@ar@start{\csname zx@alias@\zxCurrentDiagram @\tikzcd@ar@start\endcsname}%
+ \fi%
+ %%% Load the arrow style set by the start node:
+ \edef\zx@tmp{% Make sure that the style exists and load it:
+ /zx/internals/preRunIfIamStartNode-\tikzcd@ar@start/.append style={},%
+ /zx/internals/preRunIfIamStartNode-\tikzcd@ar@start,%
+ }%
+ \pgfkeysalsofrom{\zx@tmp}%
+ \fi%
+ %%% Load the arrow style set by the end node:
+ \ifdefined\zxDisablePreRunEnd\else%
+ %%% If it is an alias, we replace it with the original node:
+ \ifcsname zx@alias@\zxCurrentDiagram @\tikzcd@ar@target\endcsname% This is an alias: let's rename it to the original node
+ \edef\tikzcd@ar@target{\csname zx@alias@\zxCurrentDiagram @\tikzcd@ar@target\endcsname}%
+ \fi%
+ \edef\zx@tmp{% Make sure that the style exists and load it:
+ /zx/internals/preRunIfIamEndNode-\tikzcd@ar@target/.append style={},%
+ /zx/internals/preRunIfIamEndNode-\tikzcd@ar@target,%
+ }%
+ \pgfkeysalsofrom{\zx@tmp}%
+ \fi%
+ }%
+ },%
/zx/defaultEnv/.style={
%tiny depends on the size of the font... which we want to keep consistent look
column sep=\zxDefaultColumnSep,
@@ -1678,18 +2072,87 @@
1-row diagram/.style={},
%% usage: math baseline=wantedBaseline, where you have somewhere \zxX[a=wantedBaseline]{\beta}
math baseline/.style={baseline={([yshift=-axis_height]##1)}},
+ % math baseline row/.style={math baseline=\zxCurrentDiagram-##1-1},
+ math baseline row/.code={%
+ \IfInteger{##1}{%
+ \pgfkeysalso{math baseline=\zxCurrentDiagram-##1-1}%
+ }{%
+ % We have a non-integer value like 1.5 that means between both values.
+ % We first extract these values:
+ \pgfmathtruncatemacro{\zx@first@index}{floor(##1)}%
+ \pgfmathtruncatemacro{\zx@second@index}{floor(##1)+1}%
+ \pgfmathsetmacro{\zx@percent}{##1-floor(##1)}%
+ \pgfkeysalso{math baseline/.expanded={$(\noexpand\zxCurrentDiagram-\zx@first@index-1)!\zx@percent!(\noexpand\zxCurrentDiagram-\zx@second@index-1)$}}%
+ }%
+ },
+ math baseline row/.default={1},
+ mbr/.style={math baseline row={##1}},
+ mbr/.default={1},
+ thick lines/.style={
+ /tikz/zx thickness wires style/.style={thick, line cap=round},
+ },
+ % In circuits (mostly gates), the default separation feels too small, so we adjust it here
+ circuit/.style={
+ column sep=\zxDefaultColumnSepCircuit,
+ row sep=\zxDefaultRowSepCircuit,
+ },
+ bold/.style={
+ /tikz/commutative diagrams/arrows={B},
+ /zx/user overlay nodes/.style={
+ zxSpiders/.append style={BBw},
+ zxH/.append style={BBw},
+ },
+ /utils/exec={\def\zxEnableAllElementsBold{}},
+ },
+ B/.style={
+ bold
+ },
+ debug mode/.code={\def\zxDebugMode{}},
+ no debug mode/.code={\let\zxDebugMode\undefined},
+ amp/.style={
+ ampersand replacement=\&,
+ },
%%% Include a diagram in another diagram.
use diagram/.style 2 args={
execute at end picture={
- \node[fit=##2,inner sep=0pt,yshift=-axis_height]{\zxUseDiagram{##1}};
+ \node[fit=##2,anchor=center,inner sep=0pt,yshift=-axis_height]{\zxUseDiagram{##1}};
+ }
+ },
+ %%% Include a diagram in another diagram.
+ use diagram advanced/.style n args={3}{
+ execute at end picture={
+ \node[fit=##2,anchor=center,inner sep=0pt,yshift=-axis_height,##3]{\zxUseDiagram{##1}};
}
},
% Load (thanks ".search also") our own style
/tikz/every node/.style={%
+ % Otherwise, the empty nodes take some space… and create weird bugs. But I don't know how to add empties
+ % https://tex.stackexchange.com/questions/675958/tikz-empty-nodes-with-different-style-coordinate
+ % ==> solved, see "empty"
+ nodes={
+ zxAllNodes,
+ inner sep=0pt,
+ outer sep=0mm,
+ },
% For quickly adding alias, and displaying this alias in debug mode.
a/.code={%
\pgfkeysalso{%
- alias=####1,%
+ % alias=####1,%
+ % alias seems to fail with nodes in pic… let's try another method. See also:
+ % https://tex.stackexchange.com/questions/679647/tikz-pic-alias-to-internal-node
+ %% TODO: according to the above discussion, this append after command should be done after the
+ %% add anchor to node is finished, as an alias is basically copying all the macros of the initial node,
+ %% so you want to do it once its finished (in particular to preserve the anchors). But maybe
+ %% append after command is already avoiding that issue. In any case it would be good to make it more
+ %% robust (\tikzlastnode might change, so defining my own \tikzlastnode might help, use link instead
+ %% of copy alias to be sure the anchors are preserved etc...)
+ append after command={\pgfextra{%
+ \pgfnodealias{####1}{\tikzlastnode}%
+ % There is no way anymore to remember the link between the alias and the non-alias. Let's rembember it
+ % manually
+ \expandafter\xdef\csname zx@alias@\zxCurrentDiagram @####1\endcsname{\tikzlastnode}%
+ }%
+ },
}%
%% name path won't work with alias... So let's create two name path ^^
%% https://tex.stackexchange.com/questions/619622
@@ -1706,14 +2169,181 @@
}%
\fi%
},
+ % runs a=foo only if we are at the origin (0,0) of a zxExecuteAtRegionRelative
+ a if origin/.code={%
+ \ifnum \the\pgfmatrixcurrentrow=\zxOriginalRow\relax%
+ \ifnum \the\pgfmatrixcurrentcolumn=\zxOriginalCol\relax%
+ \pgfkeysalso{a={####1}}%
+ \fi%
+ \fi%
+ },
+ %% To allow blocks
+ block/.style={
+ zx set execute at begin node={\begin{varwidth}{50cm}}, % 50cm is just hardcoded to be long enough so that any content fits inside
+ zx set execute at end node={\end{varwidth}},
+ },
+ %% This allows nodes to specify styles for the arrows that start/end from them.
+ %% This style will be loaded last as otherwise we don't know yet the starting and ending point.
+ %% See how we apply it on the arrow side using "every arrow post"
+ post arrow style if start node/.style={%
+ append after command={% This expects a path, but we want to write a code without any path:
+ \pgfextra% this syntax with \endpgfextra completely turns off the tikz syntax, that might be safer than \pgfextra{...}.
+ \def\zx@arguments{####1}%
+ \edef\zx@tmp{%
+ /zx/internals/postRunIfIamStartNode-\tikzlastnode/.append style={\unexpanded\expandafter{\zx@arguments}},%
+ }% https://tex.stackexchange.com/questions/47905/how-to-globally-tikzset-styles
+ {%
+ \globaldefs=1\relax%
+ \pgfkeysalsofrom{\zx@tmp}%
+ }%
+ \endpgfextra%
+ },%
+ },
+ post arrow style if end node/.style={%
+ append after command={% This expects a path, but we want to write a code without any path:
+ \pgfextra% this syntax with \endpgfextra completely turns off the tikz syntax, that might be safer than \pgfextra{...}.
+ \def\zx@arguments{####1}%
+ \edef\zx@tmp{%
+ /zx/internals/postRunIfIamEndNode-\tikzlastnode/.append style={\unexpanded\expandafter{\zx@arguments}},%
+ }% https://tex.stackexchange.com/questions/47905/how-to-globally-tikzset-styles
+ {%
+ \globaldefs=1\relax%
+ \pgfkeysalsofrom{\zx@tmp}%
+ }%
+ \endpgfextra%
+ },%
+ },%
+ pre arrow style if start node/.style={%
+ append after command={% This expects a path, but we want to write a code without any path:
+ \pgfextra% this syntax with \endpgfextra completely turns off the tikz syntax, that might be safer than \pgfextra{...}.
+ \def\zx@arguments{####1}%
+ \edef\zx@tmp{%
+ /zx/internals/preRunIfIamStartNode-\tikzlastnode/.append style={\unexpanded\expandafter{\zx@arguments}},%
+ }% https://tex.stackexchange.com/questions/47905/how-to-globally-tikzset-styles
+ {%
+ \globaldefs=1\relax%
+ \pgfkeysalsofrom{\zx@tmp}%
+ }%
+ \endpgfextra%
+ },%
+ },
+ pre arrow style if end node/.style={%
+ append after command={% This expects a path, but we want to write a code without any path:
+ \pgfextra% this syntax with \endpgfextra completely turns off the tikz syntax, that might be safer than \pgfextra{...}.
+ \def\zx@arguments{####1}%
+ \edef\zx@tmp{%
+ /zx/internals/preRunIfIamEndNode-\tikzlastnode/.append style={\unexpanded\expandafter{\zx@arguments}},%
+ }% https://tex.stackexchange.com/questions/47905/how-to-globally-tikzset-styles
+ {%
+ \globaldefs=1\relax%
+ \pgfkeysalsofrom{\zx@tmp}%
+ }%
+ \endpgfextra%
+ },%
+ },
/zx/default style nodes,
/zx/user overlay nodes,
},
every arrow/.style={%
/zx/wires definition,
/zx/default style wires,
+ /zx/every arrow pre,
/zx/user overlay wires,
+ %%% Load the post arrow style at the end:
+ %% See also every arrow pre if you want to run it before the style of the arrow
+ /tikz/commutative diagrams/every arrow post/.append style={%
+ /utils/exec={% We provide a way to disable the default behavior
+ \ifdefined\zxDisablePostRunStart\else%
+ %%% If it is an alias, we replace it with the original node:
+ \ifcsname zx@alias@\zxCurrentDiagram @\tikzcd@ar@start\endcsname% This is an alias: let's rename it to the original node
+ \edef\tikzcd@ar@start{\csname zx@alias@\zxCurrentDiagram @\tikzcd@ar@start\endcsname}%
+ \fi%
+ %%% Load the arrow style set by the start node:
+ \edef\zx@tmp{% Make sure that the style exists and load it:
+ /zx/internals/postRunIfIamStartNode-\tikzcd@ar@start/.append style={},%
+ /zx/internals/postRunIfIamStartNode-\tikzcd@ar@start,%
+ }%
+ \pgfkeysalsofrom{\zx@tmp}%
+ \fi%
+ %%% Load the arrow style set by the end node:
+ \ifdefined\zxDisablePostRunEnd\else%
+ %%% If it is an alias, we replace it with the original node:
+ \ifcsname zx@alias@\zxCurrentDiagram @\tikzcd@ar@target\endcsname% This is an alias: let's rename it to the original node
+ \edef\tikzcd@ar@target{\csname zx@alias@\zxCurrentDiagram @\tikzcd@ar@target\endcsname}%
+ \fi%
+ \edef\zx@tmp{% Make sure that the style exists and load it:
+ /zx/internals/postRunIfIamEndNode-\tikzcd@ar@target/.append style={},%
+ /zx/internals/postRunIfIamEndNode-\tikzcd@ar@target,%
+ }%
+ \pgfkeysalsofrom{\zx@tmp}%
+ \fi%
+ }%
+ },%
+ disable post run start/.code={\def\zxDisablePostRunStart{}},
+ disable post run end/.code={\def\zxDisablePostRunEnd{}},
+ disable post run/.style={
+ disable post run start,
+ disable post run end,
+ },
+ enable post run start/.code={\let\zxDisablePostRunStart\undefined},
+ enable post run end/.code={\let\zxDisablePostRunEnd\undefined},
+ enable post run/.style={
+ enable post run start,
+ enable post run end,
+ },
+ enable post run,
+ },
+ %% We add an empty coordinate in every node. This has multiple advantages: first this avoids errors about
+ %% single ampersand when the matrix does not start with None, and it also avoids using \zxN{} everywhere.
+ %% However, we can't just use 'nodes in empty cells=true' or it will add nodes that might take some space:
+ % https://tex.stackexchange.com/questions/696622/tikz-allow-the-style-syntax-in-execute-at-empty-cells?noredirect=1#comment1729912_696622
+ % /tikz/replace empty cell with/.code={%
+ % \def\tikz@at@emptycell{%
+ % \tikz@lib@matrix@start@cell
+ % #1%
+ % \tikz@lib@matrix@end@cell
+ % }%
+ % },
+ % /tikz/replace empty cell with={%
+ % /tikz/execute at empty cell/.code={%
+ % \expandafter\def\expandafter\tikz@at@emptycell\expandafter
+ % {\tikz@at@emptycell\expandafter\expandafter\expandafter
+ % \tikz@lib@matrix@start@cell##1\tikz@lib@matrix@end@cell}},
+ % This is started at the beginning of non-empty cells
+ every matrix/.append style={
+ /tikz/execute at end cell={%
+ \ifcsname zxExecuteAtCell-\zxCurrentDiagram-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn\endcsname%
+ \csname zxExecuteAtCell-\zxCurrentDiagram-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn\endcsname%
+ \fi%
+ },%
+ },%
+ /tikz/execute at empty cell={%
+ % We want to check if there is a
+ \ifcsname zxExecuteAtCell-\zxCurrentDiagram-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn\endcsname%
+ % I wanted to allow a syntax with |[]| but first it seems to be quite hard (as it depends on the number of extensions):
+ % %% https://tex.stackexchange.com/questions/696622/tikz-allow-the-style-syntax-in-execute-at-empty-cells
+ % but anyway I guess it is better to turn everything into nodes so that \zxX{} can be inserted outside of a matrix.
+ \csname zxExecuteAtCell-\zxCurrentDiagram-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn\endcsname%
+ \else%
+ \ifdefined\zxCustomExecuteAtEmptyCell\zxCustomExecuteAtEmptyCell%
+ \else%
+ \coordinate[
+ % yshift=axis_height, % We already do that elsewhere
+ name=\zxCurrentDiagram-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn];%
+ \fi%
+ \fi%
},
+ % When an arrow is present, it will not detect it as an empty cell… The below code tries to avoid this issue, but actually has another issue as it removes all nodes without text in it, like |[circle, draw, inner sep=3pt]|, so
+ % we disable it for now.
+ %% https://tex.stackexchange.com/questions/675958/tikz-empty-nodes-with-different-style-coordinate/675971#675971
+ % /tikz/every node/.append code={%
+ % \tikz@addoption{%
+ % \ifdim\wd\pgfnodeparttextbox=0pt
+ % \pgfutil@ifx\tikz@shape\tikz@coordinate@text{}{%
+ % \def\tikz@shape{coordinate}%
+ % \pgftransformyshift{axis_height}}%
+ % \fi}%
+ % },
%%% To be used only in \zx{...} environment.
%%% Exemple:
phase in content/.style={
@@ -1723,38 +2353,49 @@
},
phase in label/.style={
/zx/post preparation labels/.append style={
- phase in label=##1,
+ phase in label={##1},
}
},
phase in label above/.style={
/zx/post preparation labels/.append style={
- phase in label above=##1,
+ phase in label above={##1},
}
},
phase in label below/.style={
/zx/post preparation labels/.append style={
- phase in label below=##1,
+ phase in label below={##1},
}
},
phase in label right/.style={
/zx/post preparation labels/.append style={
- phase in label right=##1,
+ phase in label right={##1},
}
},
phase in label left/.style={
/zx/post preparation labels/.append style={
- phase in label left=##1,
+ phase in label left={##1},
}
},
% for "Phase In Label"
- pil/.style={phase in label=##1},
- pilb/.style={phase in label below=##1},
- pila/.style={phase in label above=##1},
- pilr/.style={phase in label right=##1},
- pill/.style={phase in label left=##1},
+ pil/.style={phase in label={##1}},
+ pilb/.style={phase in label below={##1}},
+ pila/.style={phase in label above={##1}},
+ pilr/.style={phase in label right={##1}},
+ pill/.style={phase in label left={##1}},
+ % Load the global options style-specific
+ /zx/default style nodes preload,
+ /zx/user overlay,
},
}
+% % Call \zxSetStyleWhenEndingHere{your, zx, style} when you want to configure a particular style when arriving on a particular cell
+% \NewExpandableDocumentCommand{\zxSetStyleWhenEndingHere}{m}{%
+% \pgfkeys{
+% /zx/internals/postRunIfIamEndNode-\zxCurrentDiagram-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn/.append code={#1},
+% /zx/internals/postRunIfIamEndNode-\zxCurrentDiagram-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn
+% }%
+% }
+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Helper functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@@ -1782,7 +2423,8 @@
\def\node@on@layer{\aftergroup\node@@on@layer}
%%% Declare a symbol for a short minus (useful in fractions)
-\DeclareMathSymbol{\zxMinus}{\mathbin}{AMSa}{"39}% Requires amssymb
+\DeclareMathSymbol{\zxShortMinus}{\mathbin}{AMSa}{"39}% Requires amssymb. This version should not be redefined by the user to obtain a normal minus (or "small minus" won't work anymore)
+\def\zxMinus{\zxShortMinus}
%%% Checks if a function is a point or a node.
%%% Not sure if best solution (needed to dig into source of TeX), but can't find anything better in manual
@@ -1797,7 +2439,7 @@
% shape anchor name if exists if not. Works, while doing \pgfutil@ifundefined{pgf@anchor@\shapenode{}@#2} fails.
% I guess it has to do with the way macro are expanded...
-\def\ifAnchorExistsFromShape#1#2#3#4{
+\def\ifAnchorExistsFromShape#1#2#3#4{%
\pgfutil@ifundefined{pgf@anchor@#1@#2}{%
#4%
}{%
@@ -1809,10 +2451,135 @@
\def\ifAnchorExists#1#2#3#4{%
%%% First we extract the shape of the node:
\edef\pgf@node@name{#1}%
- \edef\shapenode{\csname pgf@sh@ns@\pgf@node@name\endcsname}%
- \ifAnchorExistsFromShape{\shapenode}{#2}{#3}{#4}
+ \edef\shapenode{\csname pgf@sh@ns@\pgf@node@name\endcsname}% e.g. rectangle
+ \ifAnchorExistsFromShape{\shapenode}{#2}{#3}{#4}%
+}
+
+%% If we manually add an anchor to a note, \ifAnchorExists will not work. Hence this improved version:
+%% Note that #3 and #4 will run in a group
+\def\ifAnchorExistsNodeSpecific#1#2#3#4{%
+ \let\zxcalculus@tmp\undefined% This is used to run #3 and #4 outside the group
+ {% group not to pollute stuff with pgf@sh@ma
+ \ifcsname pgf@sh@ma@#1\endcsname% per node config
+ \csname pgf@sh@ma@#1\endcsname% we run the config
+ \fi%
+ %%% First we extract the shape of the node:
+ \edef\pgf@node@name{#1}%
+ \edef\shapenode{\csname pgf@sh@ns@\pgf@node@name\endcsname}% e.g. rectangle
+ \ifAnchorExistsFromShape{\shapenode}{#2}{\gdef\zxcalculus@tmp{}}{}%
+ }%
+ \ifdefined\zxcalculus@tmp%
+ #3%
+ \else%
+ #4%
+ \fi%
+}
+
+% \zxGetSubnodeOfNode{\tikzcd@ar@start}{mysubnode}{True branch}{False branch} will set \zx@result to the corresponding node if it exits and run True branch
+% otherwise it will run False branch, where \zx@error will contain more details on why it failed. This function also try to use \zxOriginalRow to find
+% a possible parent.
+\def\zxGetSubnodeOfNode#1#2#3#4{%
+ \edef\zx@result{#1}%
+ % First we try to see if there is an alias:
+ \edef\zx@tmp{zx@alias@\zxCurrentDiagram @#1}%
+ % First, rewrite #1 so that it equals the name of the current node without alias
+ \ifcsname \zx@tmp\endcsname% There exists an alias
+ \edef\zx@tmp@alias{(alias \zx@tmp) }% Mostly for the error message
+ \edef\zx@result{\csname zx@alias@\zxCurrentDiagram @#1\endcsname}%
+ \else%
+ \edef\zx@tmp@alias{(no alias) }% Mostly for the error message
+ \fi
+ % First, we check if there is a node with this name on this node. If not, we will try with the parent node
+ \@ifundefined{pgf@sh@ns@\zx@result #2}{%
+ % The current node has no such subnode name: let's start its parent.
+ \@ifundefined{\zx@result -zxOriginalRow}{%
+ % There is no original coordinate: error
+ \def\zx@error{the subnode #2 of node \zx@result \zx@tmp@alias does not exist.}%
+ #4%
+ }{%
+ % There is an original coordinate: we try to see if the original node admits a subnode.
+ \edef\zx@tmp@originalRow{\csname \zx@result -zxOriginalRow\endcsname}%
+ \edef\zx@tmp@originalCol{\csname \zx@result -zxOriginalCol\endcsname}%
+ \@ifundefined{pgf@sh@ns@\zxCurrentDiagram-\zx@tmp@originalRow-\zx@tmp@originalCol #2}{%
+ \def\zx@error{the subnode #2 of aliased node \zx@result {} \zx@tmp@alias does not exist (even in the parent node at coordinate \zx@tmp@originalRow - \zx@tmp@originalCol).}%
+ #4%
+ }{%
+ \edef\zx@result{\zxCurrentDiagram-\zx@tmp@originalRow-\zx@tmp@originalCol #2}%%
+ #3%
+ }%
+ }%
+ }{% There exists a subnode in the current name
+ \edef\zx@result{\zx@result #2}%%
+ #3%
+ }%
}
+% \zxTryFirstSubnodeThenAnchorThenNode{\tikztostart}{true north}{north} will set \zx@result to the corresponding subnode if it exists, otherwise the true north anchor,
+% otherwise the north anchor
+\def\zxTryFirstSubnodeThenAnchorThenNode#1#2#3{%
+ \zxGetSubnodeOfNode{#1}{#2}{%
+ % The subnode exists: we forward \zx@result
+ }{%
+ % No submode exists:
+ % Test if it is a point or a node, and define StartPoint accordingly.
+ \ifPgfpointOrNode{#1}{%
+ \edef\zx@result{#1}%
+ }{% This is a node
+ % "zx add anchor to node" might define per-node anchors, and they are stored in
+ % a macro called like \pgf@sh@ma@tikz@f@3-2-2, so we need to read this first:
+ % TODO: maybe use pp@name everywhere? (see comment beginning of this file)
+ \begingroup% This group avoids pollution done by executing pgf@sh@ma@NODENAME
+ \pgfutil@ifundefined{pgf@sh@ma@\tikz@pp@name{##1}}{}{%
+ % We the per-node macro exists, we run it.
+ \csname pgf@sh@ma@\tikz@pp@name{##1}\endcsname%
+ }%
+ % Test if "true north" etc exists:
+ \ifAnchorExistsNodeSpecific{#1}{#2}{%
+ \xdef\zx@result{#1.#2}%
+ }{%
+ \xdef\zx@result{#1.#3}%
+ }%
+ \endgroup%
+ }%
+ }
+}
+
+% Like zxTryFirstSubnodeThenAnchorThenNodeToCoordinate but \zx@result will contain coordinates of the final point.
+\def\zxTryFirstSubnodeThenAnchorThenNodeToCoordinate#1#2#3{%
+ \zxGetSubnodeOfNode{#1}{#2}{%
+ % The subnode exists: we forward \zx@result after turning it in a coordinate
+ \ifPgfpointOrNode{\zx@result}{}{%
+ % this is a node, so we take the center
+ \pgfpointanchor{\zx@result}{#3}%
+ \def\zx@result{\the\pgf@x,\the\pgf@y}%
+ }%
+ }{%
+ % No submode exists:
+ % Test if it is a point or a node, and define StartPoint accordingly.
+ \ifPgfpointOrNode{#1}{%
+ \edef\zx@result{#1}%
+ }{% This is a node
+ % "zx add anchor to node" might define per-node anchors, and they are stored in
+ % a macro called like \pgf@sh@ma@tikz@f@3-2-2, so we need to read this first:
+ % TODO: maybe use pp@name everywhere? (see comment beginning of this file)
+ \begingroup% This group avoids pollution done by executing pgf@sh@ma@NODENAME
+ \pgfutil@ifundefined{pgf@sh@ma@\tikz@pp@name{#1}}{}{%
+ % We the per-node macro exists, we run it.
+ \csname pgf@sh@ma@\tikz@pp@name{#1}\endcsname%
+ }%
+ % Test if "true north" etc exists:
+ \ifAnchorExistsNodeSpecific{#1}{#2}{%
+ \pgfpointanchor{#1}{#2}%
+ }{%
+ \pgfpointanchor{#1}{#3}%
+ }%
+ \xdef\zx@result{\the\pgf@x,\the\pgf@y}%
+ \endgroup%
+ }%
+ }
+}
+
+
%%% Create different kinds of dots...
%% https://tex.stackexchange.com/questions/617959
%% https://tex.stackexchange.com/questions/528774/excess-vertical-space-in-vdots/528775#528775
@@ -1842,44 +2609,1599 @@
\DeclareRobustCommand{\cvdots}{\cvdotsCenterMathline}
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%% Practical functions to define multirow/multicols gates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% We provide a generic set of functions to execute code later
+% (in a later cell, or at the end of the picture), together with
+% a way to pass any kind of variables for later
+
+\NewExpandableDocumentCommand{\zxCoordinateMain}{O{}m}{
+ \coordinate[#1,#2](\zxCurrentDiagram-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn);
+}
+
+\NewExpandableDocumentCommand{\zxCoordinateSubnode}{O{}m}{
+ \coordinate[#1](\zxCurrentDiagram-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn#2);
+}
+
+\NewDocumentCommand{\zxMainNodeAlreadySet}{m}{\def\zxMainNodeAlreadySetMacro{}}
+
+\tikzset{
+ % When using the \node{}; instead of |[foo]| bar structure, no name is given to the node. This is fixed with
+ % this:
+ zx main node/.code={%
+ % If we are in a matrix, we can give it the name of the current column
+ \ifdefined\zxCurrentDiagram%
+ % Useful to temporarily disable this, for instance useful in matrix to change the size of a single cell.
+ \ifdefined\zxMainNodeAlreadySetMacro\else%
+ \tikzset{name=\zxCurrentDiagram-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn}%
+ \fi%
+ \fi%
+ },
+ zx at origin/.style={at={(0,0)}},
+ zx subnode/.code={
+ % we forbid empty subnode as otherwise it will be equivalent to "zx main node" due to the way we handle subnodes for now.
+ % and most of the time when it is empty it just means that the user does not want to set a subnode.
+ % test if empty: https://tex.stackexchange.com/questions/53068/how-to-check-if-a-macro-value-is-empty-or-will-not-create-text-with-plain-tex-co
+ \if\relax\detokenize{#1}\relax%
+ \message{Empty subnode name}%
+ \else%
+ \ifdefined\zxCurrentDiagram%
+ \ifdefined\zxOriginalRow%
+ \tikzset{alias=\zxCurrentDiagram-\zxOriginalRow-\zxOriginalCol#1}%
+ % \tikzset{name=\zxCurrentDiagram-\zxOriginalRow-\zxOriginalCol#1}%
+ \else%
+ \tikzset{alias=\zxCurrentDiagram-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn#1}%
+ % \tikzset{name=\zxCurrentDiagram-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn#1}%
+ \fi%
+ \else%
+ \message{Warning: you or outside of a tikzcd environment, so you will not be able to implement subnodes for now. But you might want to try to define zxCurrentDiagram, pgfmatrixcurrentrow and pgfmatrixcurrentcolumn yourself, you might be lucky.}%
+ \fi%
+ \fi%
+ },
+ zx independent subnode/.style={
+ name=\zxCurrentDiagram-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn#1,%
+ },
+ zx apply style/.code={\tikzset{/tikz/.cd,#1}},
+ zx style from variable/.style={%
+ zx apply style/.expand twice={\csname zxGateMultiVariable-\zxCurrentDiagram-\zxOriginalRow-\zxOriginalCol-#1\endcsname},
+ % \expandafter\scantokens\expandafter{\zx@tmp}%
+ % \zx@tmp%
+ },
+}
+
+\NewExpandableDocumentCommand{\zxGetNameAbsoluteNode}{mm}{%
+ \tikzcdmatrixname-#1-#2%
+}%
+
+%% here you can use previously defined variables if you created them
+%% will only work inside environments where \zxOriginalRow/Col are defined
+\NewExpandableDocumentCommand{\zxGetNameRelativeNode}{mm}{%
+ \ifdefined\zxOriginalRow%
+ \zxCurrentDiagram-\the\numexpr\zxOriginalRow+#1\relax-\the\numexpr\zxOriginalCol+#2\relax%
+ \else%
+ \zxCurrentDiagram-\the\numexpr\the\pgfmatrixcurrentrow+#1\relax-\the\numexpr\the\pgfmatrixcurrentcolumn+#2\relax%
+ \fi%
+}%
+
+\NewExpandableDocumentCommand{\zxGetNameRelativeNodeStartOne}{mm}{%
+ \zxGetNameRelativeNode{\numexpr #1-1\relax}{\numexpr #2-1\relax}%
+}%
+
+
+% \zxExecuteAtEndPicture{\node{A};} will execute \node{A}; at the end of the picture (or rather after the draw of the matrix, but before the draw of the wires)
+\NewExpandableDocumentCommand{\zxExecuteAtEndPicture}{m}{%
+ \edef\zx@tmp@args{\unexpanded{#1}}%
+ \edef\zx@tmp{\noexpand\pgfutil@g@addto@macro\noexpand\tikzcd@before@paths@hook{%
+ % We give random value just to avoid having errors when it is not yet defined, but you should always specify the
+ % to and from.
+ \noexpand\def\noexpand\tikzcd@currentrow{In execute at end picture}%
+ \noexpand\def\noexpand\tikzcd@currentcolumn{In execute at end picture}%
+ \noexpand\def\noexpand\tikzcd@lineno{In zxArrowNow}%
+ \noexpand\def\noexpand\zxOriginalRow{\the\pgfmatrixcurrentrow}%
+ \noexpand\def\noexpand\zxOriginalCol{\the\pgfmatrixcurrentcolumn}%
+ \expandonce\zx@tmp@args%
+ }%
+ }%
+ \zx@tmp%
+}
+
+\NewExpandableDocumentCommand{\zxExecuteWhenDrawingArrows}{m}{%
+ \edef\zx@tmp@args{\unexpanded{#1}}%
+ \edef\zx@tmp{\noexpand\pgfutil@g@addto@macro\noexpand\tikzcd@savedpaths{%
+ \noexpand\def\noexpand\zxOriginalRow{\the\pgfmatrixcurrentrow}%
+ \noexpand\def\noexpand\zxOriginalCol{\the\pgfmatrixcurrentcolumn}%
+ \expandonce\zx@tmp@args%
+ }%
+ }%
+ \zx@tmp%
+}
+
+% like \ar but run it directly. Usually run it in \zxExecuteWhenDrawingArrows.
+\NewExpandableDocumentCommand{\zxArrowNow}{O{}m}{%
+ \path[/tikz/commutative diagrams/.cd,every arrow,#1] (\tikzcd@ar@start\tikzcd@startanchor) to (\tikzcd@ar@target\tikzcd@endanchor);%
+}
+
+% \zxExecuteAtCellAbsolute{1}{2}{\node{A};} will execute at cell row 1, column 2 the code \node{A};, just make sure that nothing is already present in that cell
+\NewExpandableDocumentCommand{\zxExecuteAtCellAbsolute}{mmm}{%
+ \def\zx@tmp@args{#3}%
+ \edef\zx@tmp{zxExecuteAtCell-\zxCurrentDiagram-#1-#2}%
+ % Make sure to define the macro as we can't add to it if it does not exist
+ \ifcsname \zx@tmp\endcsname\else\expandafter\gdef\csname \zx@tmp\endcsname{}\fi%
+ \edef\zx@tmp@code{
+ \noexpand\expandafter\noexpand\pgfutil@g@addto@macro\noexpand\csname zxExecuteAtCell-\zxCurrentDiagram-#1-#2\noexpand\endcsname{%
+ \noexpand\def\noexpand\zxOriginalRow{\the\pgfmatrixcurrentrow}%
+ \noexpand\def\noexpand\zxOriginalCol{\the\pgfmatrixcurrentcolumn}%
+ % To allow to recover \zxOriginalRow from the name of the node later, we create a new macro "namenode-zxOriginalRow" with the value of the original row, same for Col
+ \noexpand\expandafter\noexpand\xdef\noexpand\csname\zxCurrentDiagram-\noexpand\the\noexpand\pgfmatrixcurrentrow-\noexpand\the\noexpand\pgfmatrixcurrentcolumn-zxOriginalRow\endcsname{\noexpand\zxOriginalRow}%
+ \noexpand\expandafter\noexpand\xdef\noexpand\csname\zxCurrentDiagram-\noexpand\the\noexpand\pgfmatrixcurrentrow-\noexpand\the\noexpand\pgfmatrixcurrentcolumn-zxOriginalCol\endcsname{\noexpand\zxOriginalCol}%
+ \expandonce{\zx@tmp@args}%
+ }%
+ }%
+ \zx@tmp@code%
+}
+
+% TODO: maybe use instead /tikz/every cell={n}{m} that is always run even if the cell is not empty? Or execute at begin cell that applies to non-empty cells?
+% \zxExecuteAtCellRelative{1}{2}{\node{A};} will execute at cell current row + 1, current column + 2 the code \node{A};, just make sure that nothing is already present in that cell
+\NewExpandableDocumentCommand{\zxExecuteAtCellRelative}{mmm}{%
+ \def\zx@tmp@args{#3}%
+ % putting this in the csname directly does not work
+ \edef\zx@tmp{zxExecuteAtCell-\zxCurrentDiagram-\the\numexpr \the\pgfmatrixcurrentrow+#1\relax-\the\numexpr\the\pgfmatrixcurrentcolumn+#2\relax}%
+ % \noexpand\expandafter\noexpand\gdef\noexpand\csname \zx@tmp\noexpand\endcsname{%
+ % Make sure to define the macro as we can't add to it if it does not exist
+ \ifcsname \zx@tmp\endcsname\else\expandafter\gdef\csname \zx@tmp\endcsname{}\fi%
+ \edef\zx@tmp@code{%
+ \noexpand\expandafter\noexpand\pgfutil@g@addto@macro\noexpand\csname \zx@tmp\noexpand\endcsname{%
+ \noexpand\def\noexpand\zxOriginalRow{\the\pgfmatrixcurrentrow}%
+ \noexpand\def\noexpand\zxOriginalCol{\the\pgfmatrixcurrentcolumn}%
+ % To allow to recover \zxOriginalRow from the name of the node later, we create a new macro "namenode-zxOriginalRow" with the value of the original row, same for Col
+ \noexpand\expandafter\noexpand\xdef\noexpand\csname\zxCurrentDiagram-\noexpand\the\noexpand\pgfmatrixcurrentrow-\noexpand\the\noexpand\pgfmatrixcurrentcolumn-zxOriginalRow\endcsname{\noexpand\zxOriginalRow}%
+ \noexpand\expandafter\noexpand\xdef\noexpand\csname\zxCurrentDiagram-\noexpand\the\noexpand\pgfmatrixcurrentrow-\noexpand\the\noexpand\pgfmatrixcurrentcolumn-zxOriginalCol\endcsname{\noexpand\zxOriginalCol}%
+ \expandonce{\zx@tmp@args}%
+ }%
+ }%
+ \zx@tmp@code%
+ % \edef\zx@tmp{}%
+ % \expandafter\gdef\csname \zx@tmp\endcsname{#3}%
+}
+
+% \zxExecuteAtRegionRelative{n}{m}{code} will execute code \zxExecuteAtCellRelative in all cells starting from the current cell (note that
+% it will have no effect on the (0,0) cell since this cell is not empty and already processed
+\NewExpandableDocumentCommand{\zxExecuteAtRegionRelative}{mmm}{%
+ \pgfmathparse{#1-1}%
+ \foreach \i in {0,...,\pgfmathresult}{%
+ \pgfmathparse{#2-1}%
+ \foreach \j in {0,...,\pgfmathresult}{%
+ \zxExecuteAtCellRelative{\i}{\j}{#3}%
+ }%
+ }%
+}
+
+\NewExpandableDocumentCommand{\zxExecuteAtRegionRelativeAndOrigin}{mmm}{%
+ % Just a trick or the tikz matrix parser will not understand that we are in a node if we start with def:
+ \coordinate(zx@Useless);
+ \def\zxOriginalRow{\the\pgfmatrixcurrentrow}%
+ \def\zxOriginalCol{\the\pgfmatrixcurrentcolumn}%
+ %#3%
+ \zxExecuteAtRegionRelative{#1}{#2}{#3}%
+}
+
+%%%
+%%% Variables that you can create in one cell and reuse later
+%%
+
+% \zxGateMultiNewVariable{my variable}{value}
+\NewExpandableDocumentCommand{\zxSetVariable}{mm}{%
+ % For some reasons it fails inside the csname directly
+ \edef\zx@tmp{zxGateMultiVariable-\zxCurrentDiagram-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn-#1}%
+ \expandafter\gdef\csname \zx@tmp\endcsname{%
+ #2%
+ }%
+}
+
+\NewExpandableDocumentCommand{\zxSetVariableExpandOnce}{mm}{%
+ % For some reasons it fails inside the csname directly
+ \edef\zx@tmp{zxGateMultiVariable-\zxCurrentDiagram-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn-#1}%
+ \expandafter\xdef\csname \zx@tmp\endcsname{%
+ \expandonce{#2}%
+ }%
+}
+
+\NewExpandableDocumentCommand{\zxSetVariableExpand}{mm}{%
+ % For some reasons it fails inside the csname directly
+ \edef\zx@tmp{zxGateMultiVariable-\zxCurrentDiagram-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn-#1}%
+ \expandafter\xdef\csname \zx@tmp\endcsname{%
+ #2%
+ }%
+}
+
+\def\zxGetVariable#1{%
+ \csname zxGateMultiVariable-\zxCurrentDiagram-\zxOriginalRow-\zxOriginalCol-#1\endcsname%
+}
+
+\def\zxShowVariable#1{%
+ \expandafter\show\csname zxGateMultiVariable-\zxCurrentDiagram-\zxOriginalRow-\zxOriginalCol-#1\endcsname%
+}
+
+%%%%%%%%%%
+%%% Slices
+%%%%%%%%%%
+
+\tikzset{
+ /zx/slice label style/.style={
+ align=center,pos=0, black, anchor=south,zxTinyFont,
+ },
+ /zx/slice line style/.style={
+ dashed, red, thick,
+ },
+}
+
+\NewDocumentCommand{\zxSlice}{O{}O{}O{.5}m}{%
+ \zxExecuteAtEndPicture{
+ \draw[/zx/slice line style,#2]
+ (\tikzcdmatrixname.north-|{$(\zxCurrentDiagram-1-\zxOriginalCol)!#3!(\zxCurrentDiagram-1-\the\numexpr\zxOriginalCol+1\relax)$})
+ -- (\tikzcdmatrixname.south-|{$(\zxCurrentDiagram-1-\zxOriginalCol)!#3!(\zxCurrentDiagram-1-\the\numexpr\zxOriginalCol+1\relax)$})
+ node[rotated/.style={anchor=south west,yshift=-.5ex,rotate=##1},rotated/.default=30, /zx/slice label style,#1]{#4};
+ }
+}
+
+\tikzset{
+ /zx/vertical slice label style/.style={
+ align=center,pos=1, black, anchor=west,zxTinyFont,
+ },
+ /zx/vertical slice line style/.style={
+ dashed, red, thick,
+ },
+}
+
+\NewDocumentCommand{\zxVSlice}{O{}O{}m}{%
+ \zxExecuteAtEndPicture{%
+ % \pgfextra{
+ \pgfpointanchor{\tikzcdmatrixname}{west}%
+ \pgfgetlastxy{\zx@tmp@west@x}{\zx@tmp@west@y}%
+ \pgfpointanchor{\tikzcdmatrixname}{east}%
+ \pgfgetlastxy{\zx@tmp@east@x}{\zx@tmp@east@y}%
+ \pgfmathparse{\zx@tmp@east@x-\zx@tmp@west@x}%
+ \edef\zxMatrixWidth{\pgfmathresult pt}%
+ % }%
+ \draw[/zx/vertical slice line style,#2]
+ (\tikzcdmatrixname.west|-{$(\zxCurrentDiagram-\zxOriginalRow-1)!.5!(\zxCurrentDiagram-\the\numexpr\zxOriginalRow+1\relax-1)$})
+ -- (\tikzcdmatrixname.east|-{$(\zxCurrentDiagram-\zxOriginalRow-1)!.5!(\zxCurrentDiagram-\the\numexpr\zxOriginalRow+1\relax-1)$})
+ node[rotated/.style={anchor=south west,yshift=-.5ex,rotate=####1},rotated/.default=30, /zx/vertical slice label style,#1]{#3};
+ }
+}
+
+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Practical functions to nest diagrams
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\NewDocumentCommand{\zxSaveDiagram}{mO{}m}{
\newsavebox{#1}%
- \savebox{#1}{\begin{ZX}[ampersand replacement=\&,#2]#3\end{ZX}}%
+ \savebox{#1}{%
+ \ifdefined\tikz@library@external@loaded% Library external is loaded...
+ \tikzset{external/optimize=false}% Otherwise, tikz will try to optimize and replace the box with a text
+ \fi%
+ \begin{ZX}[#2]#3\end{ZX}
+ }%
}
\NewDocumentCommand{\zxUseDiagram}{m}{
\usebox{#1}%
}
+%%%%%%%%%%%%%%%%%%%%%
+%%% Main environments
+%%%%%%%%%%%%%%%%%%%%%
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-%%% Practical macros to automatically choose appropriate style and arrows
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-% /!\ Warning: you should add {} at the end of all macros (except arrows)!
-% Not using that may work for now, but it may break later...
-% TODO: define them only in \zx environment.
+% Quantikz has a bug which adds space automatically.
+% https://tex.stackexchange.com/questions/618330
+% Fixing that by copying the original (unpatched) functions, and reusing them later.
+% Warning: you must load this package **before** quantikz otherwise the fix will not work.
+\let\tikzcd@@originalCopyZx\tikzcd@
+\let\endtikzcd@originalCopyZx\endtikzcd
-% % Example: \leftManyDots{n}
-% Useful to put on the left of a node like "n \vdots", linked to the next node. Example: \leftManyDots{n}.
-% First optional argument is scale of text, second is scale of =.
-\NewExpandableDocumentCommand{\leftManyDots}{O{1}O{\zxScaleDots}m}{%
- |[zxNone+,inner xsep=0pt]| \scalebox{#1}{$#3$\,}\makebox[0pt][l]{\scalebox{#2}{$\cvdotsCenterMathline$}} \ar[r,-N.,start anchor=north east] \ar[r,-N',start anchor=south east] \pgfmatrixnextcell[\zxwCol]%
+%%%%% Main environment \begin{ZX}...\end{ZX}. However, we call it ZXNoExt because when using
+%%%%% externalization (to save compilation time), we need to wrap it around a figure.
+\NewDocumentEnvironment{ZXNoExt}{O{}}{%
+ \bgroup%
+ % Do not change the font size here or it will change axis_height... Use \fontsize{10}{12}\selectfont
+ % when drawing some texts instead.
+ % Add a switch in case someone really wants the current tikzcd version:
+ \ifdefined\doNotPatchQuantikz% Do not patch tikzcd.
+ \else% Restore locally original tikzcd.
+ \let\tikzcd@\tikzcd@@originalCopyZx%
+ \let\endtikzcd\endtikzcd@originalCopyZx%
+ \fi%
+ % we need to reset this or it will get data from previous pictures
+ \global\let\tikzcd@before@paths@hook\pgfutil@empty%
+ \global\let\tikzcd@savedpaths\pgfutil@empty%
+ \ifdefined\zxDoNotPatchArrows% Do not patch arrows (we need sometimes "every arrow post")
+ \else% Copy/pasted from https://github.com/astoff/tikz-cd/blob/master/tikzlibrarycd.code.tex, just added "every arrow post".
+ %% I'm not sure which method is more resilient: patchcmd is likely to fail on minor library update,
+ %% while redefining \tikzcd@ar@new might not apply some major library upgrades (note that we redefine it
+ %% only locally). Since I don't know what is better, I do both depending on this macro
+ \ifdefined\zxUsePatchCmdToPatchArrows%
+ \patchcmd\tikzcd@ar@new%
+ {\path[/tikz/commutative diagrams/.cd,every arrow,#1]}%
+ {\path[/tikz/commutative diagrams/.cd,every arrow,#1,every arrow post]}%
+ {}%
+ {}%
+ \else%
+ \def\tikzcd@ar@new[##1]{% Make sure to turn #1 into ##1 as the command is nested
+ \pgfutil@g@addto@macro\tikzcd@savedpaths{%
+ \path[/tikz/commutative diagrams/.cd,every arrow,##1,every arrow post]%<--- we added every arrow post
+ (\tikzcd@ar@start\tikzcd@startanchor) to (\tikzcd@ar@target\tikzcd@endanchor); }}%
+ \fi%
+ \fi%
+ % We make sure "every arrow post" exists:
+ \tikzset{%
+ /tikz/commutative diagrams/every arrow post/.append style={}%
+ }%
+ \pgfsetlayers{background,belownodelayer,edgelayer,nodelayer,main,abovenodelayer,box,labellayer,foreground}% Layers are defined locally to avoid to disturb other drawings
+ %% Provide a way to reference the current diagram. This way it is for instance possible to do
+ %% \ar[from=Zbotright, to=\zxCurrentDiagram-1-1]
+ %% For this to work, you should not modify the name of the matrix.
+ %% Old way
+ % \def\zxCurrentDiagram{tikz@f@\the\tikz@fig@count}%Does not exists yet... Hopefully it's updated soon enough
+ % Should be equivalent but might even work if we change the name of the matrix, hopefully we only use it at the right time.
+ % Also, when drawing the lines, we are not anymore inside the tikzmatrix, but tikzcdmatrixname contains the name of the matrix instead:
+ \def\zxCurrentDiagram{\ifdefined\tikzmatrixname\tikzmatrixname\else\tikzcdmatrixname\fi}%
+ % \pgfutil@g@addto@macro\tikzcd@before@paths@hook{%
+ % \def\zxCurrentDiagram{\tikzcdmatrixname}%
+ % }%
+ % the problem with \tikzcdmatrixname is that it is only defined at the end, once the matrix is built
+ % We provide a way to get the current matrix name:
+ \begin{tikzcd}[%
+ /zx/defaultEnv,%
+ #1]%
+ }{\end{tikzcd}%
+ \global\let\tikzcd@before@paths@hook\pgfutil@empty%
+ \global\let\tikzcd@savedpaths\pgfutil@empty%
+ \egroup}
+
+% https://tex.stackexchange.com/a/619983/116348
+\ExplSyntaxOn
+%%%%% Shortcut macro \zxNoExt{...} equivalent to \begin{ZX}...\end{ZX}
+%%%%% We will create an alias \zx, but when we use externalization we
+%%%%% wrap it around a figure.
+\NewDocumentCommand{\zxNoExt}{O{}+m}{% Warning, expl syntax removes space.
+ \tl_rescan:nn { \char_set_catcode_active:N \& } { \begin{ZXNoExt}[#1] #2 \end{ZXNoExt} }
}
+\ExplSyntaxOff
-% Useful to link two nodes and put a vdots in between.
-\NewExpandableDocumentCommand{\middleManyDots}{}{%
- \ar[r,3 vdots] \ar[o',r] \ar[o.,r]%
+%% Version to use when using externalize (it wraps it around a
+\NewDocumentCommand{\zxExt}{O{}O{}O{}+m}{% Warning, expl syntax removes space.
+ \begin{tikzpicture}[baseline=(zxlibrarymainnode.base),#2]%
+ \node(zxlibrarymainnode)[inner sep=0pt,outer sep=0pt,#3]{\zxNoExt[#1]{#4}};%
+ \end{tikzpicture}%
}
-% Like \leftManyDots but on the right. Do *not* create a new node, like in |[zxShortZ]| \alpha \rightManyDots{m}
-\NewExpandableDocumentCommand{\rightManyDots}{O{1}O{\zxScaleDots}m}{%
- \ar[r,N'-,end anchor=north west] \ar[r,N.-,end anchor=south west] \pgfmatrixnextcell[\zxwCol] |[zxNone+,inner xsep=0pt]| \makebox[0pt][r]{\scalebox{#2}{$\cvdotsCenterMathline$}}\scalebox{#1}{\,$#3$}
+\NewDocumentEnvironment{ZXExt}{O{}O{}O{}b}{%
+ \zxExt[#1][#2][#2]{#4}%
+}{}%
+
+\NewDocumentEnvironment{ZX}{O{}O{}O{}b}{%
+ \zx[#1][#2][#3]{#4}%
+}{}
+
+% The external library is not compatible with tikzcd directly.
+% So if:
+% \zx@external@mode is enabled, we wrap the figure into another figure to be compatible with tikz externalize
+% otherwise, we check if the external library is loaded, and disable it temporarily.
+\NewDocumentCommand\zx{O{}O{}O{}+m}{%
+ {%
+ % Suffix for pictures made only with zx when using the external library
+ \ifdefined\tikz@library@external@loaded% Library external is loaded...
+ \ifdefined\zx@external@suffix%
+ \tikzappendtofigurename{\zx@external@suffix}%
+ \fi%
+ \fi%
+ \ifdefined\zx@external@mode%
+ % We wrap everything around figures and enable tikz external (useful when many figures
+ % are not compatible with external):
+ \ifthenelse{\equal{\zx@external@mode}{wrapForceExt}}{%
+ {\tikzexternalenable\zxExt[#1][#2][#3]{#4}}%
+ }{%
+ \ifthenelse{\equal{\zx@external@mode}{wrap}}{% We wrap everything around figures to be compatible with external
+ \zxExt[#1][#2][#3]{#4}%
+ }{% We don't wrap anything inside figures, so we lose external compatibility.
+ \ifthenelse{\equal{\zx@external@mode}{noWrapNoExt}}{%
+ % We disable the tikz external library temporarily (tikzcd is not compatible with it)
+ \ifdefined\tikz@library@external@loaded% Library external is loaded...
+ \tikzexternaldisable%
+ \message{WARNING: you chose to disable temporarily the tikz external library.}%
+ \fi%
+ }{}%
+ \zxNoExt[#1]{#4}%
+ }%
+ }%
+ \else% Mode auto enabled
+ {% If the tikz library is loaded:
+ \ifdefined\tikz@library@external@loaded% Library external is loaded...
+ \zxExt[#1][#2][#3]{#4}%
+ \else%
+ \zxNoExt[#1]{#4}%
+ \fi%
+ }%
+ \fi%
+ }%
+}
+
+%% By default, the error displayed when compiling using "external"
+%% is not meaningful and does not stop if a picture already exists.
+%% https://tex.stackexchange.com/questions/633100/stop-at-error-meaningfull-errors-with-shell-escape-and-tikz-externalize/633121#633121
+%% See also this bug, that shows that if you have an error and compile twice, the error disappears, but the old file is used instead.
+%% https://github.com/pgf-tikz/pgf/issues/1137
+\NewDocumentCommand\zxConfigureExternalSystemCall{O{}}{
+ %% Code inspired by https://github.com/pgf-tikz/pgf/blob/a7b45b35e99af11bf7156aa3697b897b98870e5b/tex/generic/pgf/frontendlayer/tikz/libraries/tikzexternalshared.code.tex#L277
+ \expandafter\def\csname zx@driver@pgfsys-luatex.def\endcsname{%
+ \pgfkeyssetvalue{/tikz/external/system call}{%
+ lualatex \tikzexternalcheckshellescape #1 -jobname "\image" "\texsource"%
+ }%
+ }%
+ \expandafter\def\csname zx@driver@pgfsys-pdftex.def\endcsname{%
+ \pgfutil@IfUndefined{directlua}{%
+ \pgfkeyssetvalue{/tikz/external/system call}{%
+ pdflatex \tikzexternalcheckshellescape #1 -jobname "\image" "\texsource"%
+ }%
+ }{%
+ \pgfkeyssetvalue{/tikz/external/system call}{%
+ lualatex \tikzexternalcheckshellescape #1 -jobname "\image" "\texsource"%
+ }%
+ }%
+ }%
+ \expandafter\def\csname zx@driver@pgfsys-xetex.def\endcsname{%
+ \pgfkeyssetvalue{/tikz/external/system call}{%
+ xelatex \tikzexternalcheckshellescape #1 -jobname "\image" "\texsource"%
+ }%
+ }%
+ \expandafter\def\csname zx@driver@pgfsys-dvips.def\endcsname{%
+ \pgfkeyssetvalue{/tikz/external/system call}{%
+ latex \tikzexternalcheckshellescape #1 -jobname "\image" "\texsource" %
+ && dvips -o "\image".ps "\image".dvi %
+ }%
+ }%
+ % Auto-select a suitable default value fo 'system call':
+ \pgfutil@ifundefined{tikzexternal@driver@\pgfsysdriver}{%
+ % fallback. We do not know the driver here.
+ \csname zx@driver@pgfsys-pdftex.def\endcsname
+ }{%
+ \csname zx@driver@\pgfsysdriver\endcsname
+ }%
+}
+
+% Call zxConfigureExternalSystemCall with the same system call as the calling program
+% Useful otherwise the error may be missed (for instance errorstopmode works in pdflatex but not in
+% emacs, and nonstopmode works in emacs, but not in pdflatex).
+% The current mode is stored in \interactionmode, 0, 1, 2, 3 corresponding respectively to batch, nonstop, scroll or errorstop.
+% https://tex.stackexchange.com/questions/91592/where-to-find-official-and-extended-documentation-for-tex-latexs-commandlin
+\NewDocumentCommand\zxConfigureExternalSystemCallAuto{}{%
+ \ifnum\interactionmode=0 %
+ \zxConfigureExternalSystemCall[-interaction=batchmode]%
+ \fi%
+ \ifnum\interactionmode=1 %
+ \zxConfigureExternalSystemCall[-interaction=nonstopmode]% emacs
+ \fi%
+ \ifnum\interactionmode=2 %
+ \zxConfigureExternalSystemCall[-interaction=scrollmode]%
+ \fi%
+ \ifnum\interactionmode=3 %
+ \zxConfigureExternalSystemCall[-interaction=errorstopmode]% pdflatex by default
+ \fi%
+}
+
+
+\ifdefined\zxDoNotPatchSystemCall\else%
+ \zxConfigureExternalSystemCallAuto
+\fi
+
+% \zx@external@mode can be undefined (=auto), wrap or nowrap.
+
+%% Automatically check if the external library is loaded, and use it.
+\NewDocumentCommand\zxExternalAuto{}{%
+ \let\zx@external@mode\undefined%
+}
+
+%% Force to wrap the ZX figures around a figure to ensure compatibility with external.
+\NewDocumentCommand\zxExternalWrap{}{%
+ \def\zx@external@mode{wrap}%
+}
+
+%% Do not wrap the ZX figures around another figure (not compatible with external)
+\NewDocumentCommand\zxExternalNoWrap{}{%
+ \def\zx@external@mode{nowrap}%
+}
+
+%% Do not wrap the ZX figures, but disable external for these figures (semi-compatible with external)
+\NewDocumentCommand\zxExternalNoWrapNoExt{}{%
+ \def\zx@external@mode{noWrapNoExt}%
+}
+
+%% Wrap the ZX figures, and enable external for these figures (useful when most other environments
+%% are not compatible with tikz external)
+\NewDocumentCommand\zxExternalWrapForceExt{}{%
+ \def\zx@external@mode{wrapForceExt}%
}
+% Mode auto is enabled by default
+\zxExternalAuto
+
+\NewDocumentCommand\zxExternalSuffix{m}{
+ \ifthenelse{\equal{#1}{}}{% Nothing submitted: we erase the suffix
+ \let\zx@external@suffix\undefined%
+ }{%
+ \def\zx@external@suffix{#1}
+ }%
+}
+
+\zxExternalSuffix{zx}
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%% Custom nodes from Pic
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% It is quite complicated to define custom node shapes, especially when using anchors. Here, we define a
+%% Way to easily create a custom node from a picture.
+
+%% This code allows to add a new anchor to a given node:
+%% https://tex.stackexchange.com/a/676090/116348
+\tikzset{
+ zx add anchor to node/.code n args={3}{%
+ \edef\tikz@temp##1{% \tikz@pp@name/\tikzlastnode needs to be expanded
+ %% This codes does the following thing:
+ %% First, it modifies the "\pgf@anchor@rectangle@fake center west" macro (rectangle might be another shape,
+ %% same for anchor). But since this macro might be different between nodes sharing the same shape,
+ %% it adds it to a per-node macro called like \pgf@sh@ma@tikz@f@3-2-2 (tikz@f@3-2-2 is the name of the
+ %% node).
+ \noexpand\pgfutil@g@addto@macro\expandafter\noexpand\csname pgf@sh@ma@\tikz@pp@name{#1}\endcsname{%
+ \def\expandafter\noexpand\csname pgf@anchor@\csname pgf@sh@ns@\tikz@pp@name{#1}\endcsname @#2\endcsname{##1}%
+ }%
+ }%
+ \tikz@temp{#3}%
+ },
+ zx add anchor to pic default/.style={/tikz/zx add anchor to pic={#1}{#1}},
+ zx add anchor to pic/.code 2 args={%
+ % If base coordinate isn't created yet, do so at (0,0)
+ % in the current coordinate system!
+ \pgfutil@ifundefined{pgf@sh@ns@\tikz@pp@name{}}{%
+ \pgfcoordinate{\tikz@pp@name{}}{\pgfpointorigin}%
+ }{}%
+ \begingroup
+ % What is the distance between coordinate and base?
+ % We have to do this in the coordinate system of the base coordinate.
+ \pgfsettransform{\csname pgf@sh@nt@\tikz@pp@name{}\endcsname}%
+ \pgf@process{\pgfpointanchor{\tikz@pp@name{#2}}{center}}%
+ % This distance is the new anchors coordinate
+ % in the base's coordinate system.
+ % Adding an anchor to a node must be global
+ % which is why we can do this inside the group.
+ \pgfkeysalso{
+ /tikz/zx add anchor to node/.expanded=%
+ {}{#1}{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}
+ }%
+ \endgroup
+ }%
+}
+
+%%% Create automatically a new pic-based node
+%%% \zxNewNodeFromPic{nameOfNode}[default style before user][default style after user]{content of the pic}
+%%% - In 'default style before user', we can put any style that is given to the pic (e.g. colors, rotate, scale…)
+%%% or even custom properties that will be read by the pic (e.g. to allow the define the number of spikes of a
+%%% star). This style can notably have "zx create anchors={a, list, of, coordinates, to, turn, into, anchors}"
+%%% that will automatically turn any coordinate in the pic in the list of coordinates into an anchor of the
+%%% parent node.
+%%% - In 'default style after user', the style is run after the code provided by the user. In particular, you can
+%%% use "invert top bottom" to invert the "top" version with the "bottom" version (rotation is minus 90 instead
+%%% of 90 for instance).
+\NewDocumentCommand{\zxNewNodeFromPic}{mO{}O{}O{}O{}m}{%
+ \tikzset{%
+ #1Pic/.pic={%
+ #6%
+ % The user can even add more stuff to draw after if needed by redefining this macro:
+ \ifdefined\zxCustomPicAdditionalPic\zxCustomPicAdditionalPic\fi%
+ \tikzset{%
+ % We store the list of anchors to create into \zxListOfNewAnchors. If it does not exist we create it:
+ /utils/exec={\ifdefined\zxListOfNewAnchors\else\def\zxListOfNewAnchors{}\fi},
+ % We add the coordinates in \zxListOfNewAnchors as anchors for the node
+ zx add anchor to pic default/.list/.expanded={\zxListOfNewAnchors}}%
+ },%
+ #1/.style={%
+ %shape=coordinate, %yshift=axis_height, %% already applied
+ #4,
+ append after command={%
+ pic[
+ % We configure the name and position of the pic
+ at=(\tikzlastnode), name=\tikzlastnode,
+ % We create a command to add anchors via zx create anchors={my, list, of, anchors}. This way, it also allows dynamic anchors using
+ % the default style after user.
+ zx create anchors/.store in={\zxListOfNewAnchors},
+ zx create anchors={},
+ % We create a new style to apply to the main node
+ zx main node/.style={
+ name=,
+ zx forward to node/.append style={},
+ zx forward to node,
+ },
+ % We load the other default arguments:
+ #2,
+ % We try to load a potentially global style configured by the user (mostly used to override this library)
+ /zx/picCustomStyleBeforeUser#1/.append style={}, % Make sure it exists to avoid errors
+ /zx/picCustomStyleBeforeUser#1,
+ % We load the per-instance arguments:
+ ##1,
+ % We try to load a potentially global style configured by the user (mostly used to override this library)
+ /zx/picCustomStyleAfterUser#1/.append style={}, % Make sure it exists to avoid errors
+ /zx/picCustomStyleAfterUser#1,
+ #3,
+ % We try to load a potentially global style configured by the user (mostly used to override this library)
+ /zx/picCustomStyleLastPic#1/.append style={}, % Make sure it exists to avoid errors
+ /zx/picCustomStyleLastPic#1,
+ ]{#1Pic}%
+ },
+ }%
+ }%
+ %% \ExpandArgs{c} is an equivalent of expandafter + csname, to expand the first argument before evaluating the function:
+ %% https://tex.stackexchange.com/a/676103/116348
+ %% ##1: pic additional style
+ %% ##2: node additional style
+ %% ##3: text to consume with \tikzpictext
+ % \ExpandArgs{c}\NewExpandableDocumentCommand{zx#1}{t.t-t'O{}O{}m}{%
+ % |[#1={pic text={##6}, ##4}, ##5]|%
+ % }%
+ % Actually ExpandArgs is not available before ~2023? maybe, so let’s use expandafter
+ \expandafter\NewExpandableDocumentCommand\csname zx#1\endcsname{O{}O{}t.t-t't/t*e_m}{%
+ \node[zx main node, #1={
+ pic text={##9},
+ %% The alias=… should rather be called on the second element. But it's quite handy to write it here, so here we go:
+ a/.style={%
+ zx forward to node/.append style={
+ a={########1},
+ },
+ },
+ %% The mode stored in \zxRotationMode contains the current rotation mode (i.e. the angle between 0 and 359, typically 0,90,180,270),
+ %% to allow further tweaks (for instance, a pic might be mirrored instead of rotated by 180° when using the parameter -, and this
+ %% can be configured by reading this variable).
+ /utils/exec={%
+ \def\zxCurrentRotationMode{0}%
+ %%% Fake center is mostly for curves like <', and true north/ is mostly for curves like C, C'...
+ %%% These anchor name are changed depending on the rotation: the north/… is before the rotation.
+ \def\zxVirtualCenterNorth{fake center north}%
+ \def\zxVirtualCenterSouth{fake center south}%
+ \def\zxVirtualCenterEast{fake center east}%
+ \def\zxVirtualCenterWest{fake center west}%
+ \def\zxTrueNorth{true north}%
+ \def\zxTrueSouth{true south}%
+ \def\zxTrueEast{true east}%
+ \def\zxTrueWest{true west}%
+ \IfBooleanT{##3}{%
+ \def\zxCurrentRotationMode{90}%
+ \def\zxVirtualCenterNorth{fake center west}%
+ \def\zxVirtualCenterSouth{fake center east}%
+ \def\zxVirtualCenterEast{fake center north}%
+ \def\zxVirtualCenterWest{fake center south}%
+ \def\zxTrueNorth{true west}%
+ \def\zxTrueSouth{true east}%
+ \def\zxTrueEast{true north}%
+ \def\zxTrueWest{true south}%
+ }%
+ \IfBooleanT{##4}{%
+ \def\zxCurrentRotationMode{180}%
+ \def\zxVirtualCenterNorth{fake center south}%
+ \def\zxVirtualCenterSouth{fake center north}%
+ \def\zxVirtualCenterEast{fake center west}%
+ \def\zxVirtualCenterWest{fake center east}%
+ \def\zxTrueNorth{true south}%
+ \def\zxTrueSouth{true north}%
+ \def\zxTrueEast{true west}%
+ \def\zxTrueWest{true east}%
+ }%
+ \IfBooleanT{##5}{%
+ \def\zxCurrentRotationMode{270}%
+ \def\zxVirtualCenterNorth{fake center east}%
+ \def\zxVirtualCenterSouth{fake center west}%
+ \def\zxVirtualCenterEast{fake center south}%
+ \def\zxVirtualCenterWest{fake center north}%
+ \def\zxTrueNorth{true east}%
+ \def\zxTrueSouth{true west}%
+ \def\zxTrueEast{true south}%
+ \def\zxTrueWest{true north}%
+ }%
+ \IfBooleanT{##6}{%
+ \def\zxModeSlash{}%
+ }%
+ \IfBooleanT{##7}{%
+ \def\zxModeStar{}%
+ }%
+ % Embellishments can contain something like \zxMynode_{Text A}{Text B}
+ \IfNoValueTF{##8}{}{%
+ \def\zxModeUnderscore{##8}%
+ }%
+ },
+ rotate=\zxCurrentRotationMode,%
+ %%% Sometimes it can be quite handy to invert the top and the bottom version if it does not match with the
+ %%% intuitive position it should have.
+ %%% Make sure to call this in the second optional parameter (after user style)
+ invert top bottom/.style={
+ rotate=-\zxCurrentRotationMode,
+ /utils/exec={%
+ \ifnum\zxCurrentRotationMode=90\relax
+ \def\zxCurrentRotationMode{270}%
+ \else
+ \ifnum\zxCurrentRotationMode=270\relax
+ \def\zxCurrentRotationMode{90}%
+ \fi
+ \fi
+ },
+ rotate=\zxCurrentRotationMode,%
+ },%
+ invert right left/.style={
+ rotate=-\zxCurrentRotationMode,
+ /utils/exec={%
+ \ifnum\zxCurrentRotationMode=0\relax
+ \def\zxCurrentRotationMode{180}%
+ \else
+ \ifnum\zxCurrentRotationMode=180\relax
+ \def\zxCurrentRotationMode{0}%
+ \fi
+ \fi
+ },
+ rotate=\zxCurrentRotationMode,%
+ },%
+ ##1}, #5, ##2]{};%
+ }%
+}%
+
+%% Useful to increase or decrease the bounding box of a custom node.
+%% Parameters are like extend=5mm (that extends on all directions), and similarly for top/bottom/left/right/horizontal/vertical
+\NewExpandableDocumentCommand{\zxExtendBoundingBox}{m}{%
+ \pgfkeys{
+ /zx/.cd,
+ left/.store in=\zx@left,
+ left=0pt,
+ right/.store in=\zx@right,
+ right=0pt,
+ top/.store in=\zx@top,
+ top=0pt,
+ bottom/.store in=\zx@bottom,
+ bottom=0pt,
+ horizontal/.style={
+ left=##1,
+ right=##1,
+ },
+ vertical/.style={
+ /zx/top=##1,
+ /zx/bottom=##1,
+ },
+ extend/.style={
+ vertical=##1,
+ horizontal=##1,
+ },
+ #1,
+ }%
+ \path[use as bounding box] ([xshift=-\zx@left,yshift=\zx@top]current bounding box.north west)
+ rectangle ([xshift=\zx@right,yshift=-\zx@bottom]current bounding box.south east);%
+}
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%% Some special nodes based on \zxNewNodeFromPic
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%% Ground symbol
+\zxNewNodeFromPic{Ground}[scale=\zxGroundScale][invert top bottom]{
+ \draw[line width=\zxDefaultLineWidth]
+ (0,0) -- (1mm,0)
+ -- +(0,1mm) -- +(0,-1mm)
+ ++(.4mm,0)
+ -- +(0,.7mm) -- +(0,-.7mm)
+ ++(.4mm,0)
+ -- +(0,.35mm) -- +(0,-.35mm);
+ \coordinate() at (0,0); % Empty coordinate make the center start at the right position
+}
+
+%% From scalable ZX calculus
+\zxNewNodeFromPic{Divider}[][
+ % Because of the rounded corners, the lines will stop before touching the shape when arriving on the angle. So we force such nodes to be drawn below
+ % the shape, targeting a point inside the node.
+ %post arrow style if end node/.expanded={% we need to expand everything before setting the style, as this style will be executed much later in the arrow,
+ post arrow style if end node={% if the text contains macro like \zxVirtualCenterWest use post arrow style if end node/.expanded instead as these macro
+ % will not exist anymore once the line is drawn
+ on layer=edgelayer,%
+ end anchor if not set=fake center north,
+ },%
+ post arrow style if start node={% if the text contains macro like \zxVirtualCenterWest use post arrow style if end node/.expanded instead as these macro
+ % will not exist anymore once the line is drawn
+ on layer=edgelayer,%
+ start anchor if not set=fake center south,
+ },%
+ zx create anchors={\zxVirtualCenterWest, \zxVirtualCenterEast, \zxVirtualCenterNorth, \zxVirtualCenterSouth},
+ every node/.append style={transform shape}
+]{
+ \node[regular polygon, regular polygon sides=3,shape border rotate=90, draw=black,fill=gray!50, inner sep=1.6pt, rounded corners=0.8mm,zx main node] {};
+ \coordinate(\zxVirtualCenterEast) at (.2mm,0); % Used to start lines on the side of the shape
+ \coordinate(\zxVirtualCenterWest) at (-1mm,0);
+ \coordinate(\zxVirtualCenterNorth) at (\zxVirtualCenterWest); % Synonyme, useful to determine where to start
+ \coordinate(\zxVirtualCenterSouth) at (\zxVirtualCenterEast); % Synonyme, useful to determine where to start
+}
+
+%% Matrix symbol
+\zxNewNodeFromPic{Matrix}
+ [
+ % As we want - to only swap the position of the label but not the rotation (we use * already for transpose)
+ % we disable the above rotation:
+ rotate=-\zxCurrentRotationMode,
+ % Otherwise the space between colums is too big
+ /utils/exec={\setlength\arraycolsep{1pt}},
+ ][zx create anchors={true north,true south,true east,true west}]{
+ \node[zx main node, draw, signal, fill=colorZxMatrix, inner sep=1pt, minimum height=6pt, transform shape,
+ % The direction of the shape is turned when using the * symbol (transpose).
+ signal to/.expanded={\ifdefined\zxModeStar west\else east\fi},
+ signal from/.expanded={\ifdefined\zxModeStar east\else west\fi},
+ % We disabled the default rotation (* is for transpose), but we still want to rotate it to read to/down:
+ rotate/.expanded={mod(-\zxCurrentRotationMode,180)},
+ % If we want the syntax \zxMatrix{45:f} to put f at 45 degrees, we want to expand \tikzpictext
+ % *before* to read the key, hence the need for expanded.
+ label/.expanded={[
+ inner sep=2pt,
+ % The position of the label is independent of the rotation, but depends on the rotation mode ('.-):
+ absolute,
+ label position=\ifdefined\zxLabelAngle \zxLabelAngle\else 90+\zxCurrentRotationMode\fi,
+ font=\noexpand\footnotesize, % We don't want to expand \footnotesize before defining the label
+ % we use the / decoration
+ overlay/.expanded={\ifdefined\zxModeSlash true\else false\fi},
+ % Math mode by default:
+ execute at begin node=$, execute at end node=$,
+ /zx/picCustomStyleMatrixLabel/.append style={}, % Make sure it exists to avoid errors
+ /zx/picCustomStyleMatrixLabel,
+ ]
+ % We put as the label the text directly. Note that \unexpanded\expandafter expands the next token only once
+ % as if it gets expanded further, we can get errors (e.g.\ with pmatrix)
+ \unexpanded\expandafter{\tikzpictext}
+ \ifdefined\zxModeUnderscore\noexpand\begin{bmatrix}\noexpand\zxModeUnderscore\noexpand\end{bmatrix}\fi
+ },
+ /zx/picCustomStyleMatrixMainNode/.append style={}, % Make sure it exists to avoid errors
+ /zx/picCustomStyleMatrixMainNode,
+ ]{};
+ \coordinate(true east) at (.east); % Used to start lines on the side of the shape
+ \coordinate(true west) at (.west);
+ \coordinate(true north) at (true west); % Synonyme, useful to determine where to start
+ \coordinate(true south) at (true east); % Synonyme, useful to determine where to start
+}
+
+%% Gates
+
+\pgfkeys{
+ /zx/every box/.style={
+ draw,
+ inner sep=1.3mm,
+ rectangle,
+ zx filling style,
+ zx thickness wires style,
+ % not sure why, but seems to be already in math mode (maybe global options), and writing it twice disturbs the system
+ % execute at begin node=$, execute at end node=$,
+ execute at begin node={\renewcommand{\arraystretch}{1}\setlength\arraycolsep{2pt}},
+ zxNormalFont,
+ minimum width=\zxBoxMinimumWidth,
+ minimum height=\zxBoxMinimumHeight,
+ },
+ % https://tex.stackexchange.com/questions/696958/simple-way-to-specify-a-pass-a-style-with-syntax-my-style-foo/697043
+ /zx/boxes/.code={%
+ \scantokens{%
+ \pgfkeysalso{%
+ /zx/every box/.append style={#1}%
+ }%
+ }%
+ },
+ /zx/box load style/.style={
+ add label advanced/.style 2 args={
+ label={[inner sep=1.8pt,zxTinyFont,##1]##2},
+ },
+ add label/.style={
+ add label advanced={}{##1},
+ },
+ },
+}
+
+\NewExpandableDocumentCommand{\zxBox}{O{}m}{
+ \node[%
+ zx main node,
+ zx at origin,
+ alias=zxTmp,
+ /zx/box load style,
+ /zx/every box,%
+ #1%
+ ]{#2};%
+ % Nicer if you want '> to work
+ \zxCoordinateSubnode[at={(zxTmp.center)}]{fake center north};%
+ \zxCoordinateSubnode[at={(zxTmp.center)}]{fake center south};%
+ \zxCoordinateSubnode[at={(zxTmp.center)}]{fake center east};%
+ \zxCoordinateSubnode[at={(zxTmp.center)}]{fake center west};%
+}
+
+
+\NewCommandCopy\zxGate\zxBox
+
+\pgfkeys{
+ /zx/every elt/.style={
+ zx main node,
+ minimum width=\zxEltMinimumWidth,
+ minimum height=\zxEltMinimumHeight,
+ },
+ % https://tex.stackexchange.com/questions/696958/simple-way-to-specify-a-pass-a-style-with-syntax-my-style-foo/697043
+ /zx/elts/.code={%
+ \scantokens{%
+ \pgfkeysalso{%
+ /zx/every elt/.append style={#1}%
+ }%
+ }%
+ },
+ /zx/elt load style/.style={
+ add label advanced/.style 2 args={
+ label={[inner sep=1.8pt,zxTinyFont,##1]##2},
+ },
+ add label/.style={
+ add label advanced={}{##1},
+ },
+ },
+}
+
+\NewExpandableDocumentCommand{\zxElt}{O{}m}{
+ \node[%
+ zx main node,
+ zx at origin,
+ alias=zxTmp,
+ /zx/elt load style,
+ /zx/every elt,%
+ #1%
+ ]{#2};%
+ % Nicer if you want '> to work
+ \zxCoordinateSubnode[at={(zxTmp.center)}]{fake center north};%
+ \zxCoordinateSubnode[at={(zxTmp.center)}]{fake center south};%
+ \zxCoordinateSubnode[at={(zxTmp.center)}]{fake center east};%
+ \zxCoordinateSubnode[at={(zxTmp.center)}]{fake center west};%
+}
+
+
+% \NewExpandableDocumentCommand{\zxEltMulti}{O{}mmm}{
+% \zxGateMulti[#1]{#2}{#3}{#4}
+% }
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%% Gate Multi (user part)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+\NewExpandableDocumentCommand{\zxGenericMulti}{m}{%
+ \path;%
+ \pgfkeys{%
+ /zx/generic multi/.cd,%
+ %%% Some default styles
+ /tikz/cleanup style for measure node/.style={
+ a/.style={},%
+ },
+ cleanup style for fit node/.store in=\zx@cleanupStyleFitNode,
+ cleanup style for fit node={},
+ %%% this part is mostly used by the wrapping macro (e.g. to create \zxGateMulti)
+ command to run to measure node/.store in=\zx@commandToRunToMeasureNode,
+ command to run to create inner nodes/.store in=\zx@commandToRunToCreateInnerNodes,
+ command to run to create the fit node/.store in=\zx@commandToCreateTheFitNode,
+ command to run to create the main label/.store in=\zx@commandToCreateTheMainLabel,%
+ minimum height inner nodes/.store in=\zx@minimumHeightInnerNodes,
+ minimum width inner nodes/.store in=\zx@minimumWidthInnerNodes,
+ number rows/.store in=\zx@nbRows,
+ number columns/.store in=\zx@nbColumns,%
+ %%% this part can be used by the end user, and may be used inside the above commands
+ %%% Note that the wrapping macro should also initialize these values that might be changed by the user
+ %%% It might seem like this part is redundant, but not really, as this part can be changed by the user
+ %%% and is more fine grained that the above commands
+ content inner nodes/.store in=\myContent,
+ %%% TODO: in the function: content inner nodes={#4},
+ style inner nodes/.store in=\zx@genericMultiStyle,
+ style inner nodes={},
+ % this will be set by fit content not to override the user value
+ before style inner nodes/.store in=\zx@genericBeforeStyleInnerNodes,
+ before style inner nodes={},
+ % style for the main style
+ main/.store in=\zx@genericMultiMainStyle,
+ main={},
+ main text/.store in=\zx@genericMultiMainTextStyle,
+ main text={},
+ original content/.store in=\zx@GenericMultiOriginalContent,
+ % Run additional code after the last \node
+ additional code/.store in=\zx@genericMultiAdditionalCode,
+ additional code=,
+ do not run fit content/.code={\def\zx@donotrunfitcontent{}},
+ run fit content/.code={\let\zx@donotrunfitcontent\undefined},
+ run fit content,
+ % This will compute the size of the content, and adapt the width of the inner nodes
+ % leaving around a margin specified in the 2 first arguments (row/column), the last argument is the minimum width of the inner nodes
+ % note that we take as a reference the content of \pgfmatrixcolumnsep which might not be constant: if you change the width of the columns,
+ % you are on your own.
+ fit content/.code n args={4}{
+ % New version:
+ \begin{lrbox}{\zx@tmp@box}%
+ \begin{pgfinterruptpicture}%
+ \begin{pgfpicture}%
+ \zx@commandToRunToMeasureNode%
+ \end{pgfpicture}%
+ \end{pgfinterruptpicture}%
+ \end{lrbox}%
+ % % we measure the content of the box (##x appears 2 times since we have left and right margins):
+ \edef\zx@totalheight{\the\dimexpr\ht\zx@tmp@box + \dp\zx@tmp@box + ##1 + ##1\relax}%
+ \edef\zx@width{\the\dimexpr\wd\zx@tmp@box + ##2 + ##2\relax}%
+ \edef\zx@width{\the\dimexpr\wd\zx@tmp@box\relax}%
+ % \show\zx@totalheight
+ % \show\zx@width
+ %% We compute now the width/total height of each node. Basically, we have #3 blocks, and #3-1 column separations, so we want to find x such that:
+ %% x*#2 + (#2-1)*\pgfmatrixcolumnsep = \zx@width, i.e.
+ %% x = (\zx@width - (#2-1)*\pgfmatrixcolumnsep)/#2,
+ \pgfmathsetmacro{\zx@final@width@block}{max(##4,(\zx@width - (\zx@nbColumns-1)*\pgfmatrixcolumnsep)/(\zx@nbColumns))}%
+ \pgfmathsetmacro{\zx@final@height@block}{max(##3,(\zx@totalheight - (\zx@nbRows-1)*\pgfmatrixrowsep)/(\zx@nbRows))}%
+ \pgfkeysalso{%
+ content inner nodes={},
+ before style inner nodes/.expanded={
+ inner sep=0pt,
+ outer sep=0pt,
+ % opacity=0,
+ minimum width=\zx@final@width@block pt,
+ minimum height=\zx@final@height@block pt,
+ },
+ % we disable it not to run it more than once in case the user decided to run it
+ do not run fit content,
+ }%
+ },
+ fit content/.default={0mm}{0mm}{\zx@minimumHeightInnerNodes}{\zx@minimumWidthInnerNodes},
+ safe fit/.style={
+ before style inner nodes={},
+ content inner nodes/.expand once={\zx@GenericMultiOriginalContent},
+ do not run fit content,
+ },
+ #1,
+ /utils/exec={
+ \ifdefined\zx@donotrunfitcontent\else%
+ \pgfkeysalso{fit content}%
+ \fi%
+ },
+ }%
+ % Store the content for letter use
+ \zxSetVariableExpandOnce{content inner nodes}{\myContent}%
+ \zxSetVariableExpandOnce{style inner nodes}{\zx@genericMultiStyle}%
+ \zxSetVariableExpandOnce{before style inner nodes}{\zx@genericBeforeStyleInnerNodes}%
+ \zxSetVariableExpandOnce{style main node}{\zx@genericMultiMainStyle}%
+ \zxSetVariableExpandOnce{style main text node}{\zx@genericMultiMainTextStyle}%
+ \zxSetVariableExpandOnce{additional code}{\zx@genericMultiAdditionalCode}%
+ \zxSetVariableExpandOnce{command to run to create inner nodes}{\zx@commandToRunToCreateInnerNodes}%
+ \zxSetVariableExpandOnce{command to run to create the fit node}{\zx@commandToCreateTheFitNode}%
+ \zxSetVariableExpandOnce{command to run to create the main label}{\zx@commandToCreateTheMainLabel}%
+ \zxSetVariableExpandOnce{cleanup style for fit node}{\zx@cleanupStyleFitNode}%
+ \zxExecuteAtRegionRelativeAndOrigin{\zx@nbRows}{\zx@nbColumns}{%
+ \zxGetVariable{command to run to create inner nodes}%
+ }%
+ \zxExecuteAtEndPicture{%
+ % We cannot use fit directly as it misplace the text. According to the doc, we should place the text using another intermediate node:
+ \scantokens{%
+ \zxGetVariable{command to run to create the fit node}%
+ \zxGetVariable{command to run to create the main label}%
+ \zxGetVariable{additional code}%
+ }%
+ }
+}
+
+% the first style is kind of the style that is applied by default to the elements when
+% it makes sense, but for most precise stuff use the second argument that can individually address other
+% elements
+\NewExpandableDocumentCommand{\zxGateMulti}{O{}O{}mmm}{%
+ \zxGenericMulti{
+ command to run to measure node={%
+ \zxBox[%
+ % we disable a here since we do not want to use alias when measuring the node
+ cleanup style for measure node,
+ % Similarly, measuring nodes should not be done here
+ add label advanced/.style 2 args={},
+ % label already exists
+ add label/.style={},
+ #1%
+ ]{#5}%
+ },
+ original content={#5},
+ command to run to create inner nodes={
+ \zxBox[%
+ opacity=0,
+ zx style from variable={before style inner nodes},
+ zx style from variable={style inner nodes},
+ ]{\zxGetVariable{content inner nodes}}
+ },
+ command to run to create the fit node={%
+ \node[
+ /zx/box load style,
+ /zx/every box,%
+ zx style from variable={cleanup style for fit node},
+ add label advanced/.style 2 args={
+ label={[align=center,inner sep=1.8pt,zxTinyFont,####1]####2},
+ },
+ % label already exists
+ add label/.style={
+ add label advanced={}{####1},
+ },
+ #1,% this can set the alias for instance
+ inner sep=0pt,
+ minimum width=0pt,
+ minimum height=0pt,
+ alias=zxMainNode,%needed to place the main label
+ fit=(\zxGetNameRelativeNode{0}{0})(\zxGetNameRelativeNode{\the\numexpr#3-1\relax}{\the\numexpr#4-1\relax}),
+ zx style from variable={style main node},
+ ]{};%
+ },
+ command to run to create the main label={
+ \node[
+ rectangle,
+ zxNormalFont,
+ execute at begin node=$,
+ execute at end node=$,
+ % alias should be set on the fit node, not here:
+ a/.style={},
+ alias/.style={},
+ % Similarly, measuring nodes should not be done here
+ add label advanced/.style 2 args={},
+ % label already exists
+ add label/.style={},
+ #1,% needed for instance for the block stuff
+ % We disable stuff that should rather be set for the fit node
+ draw=none,
+ fill=none,
+ at=(zxMainNode.center),
+ alias=zxMainNodeText,
+ zx style from variable={style main text node}]{#5};
+ },%
+ minimum height inner nodes={\zxBoxMinimumHeight},
+ minimum width inner nodes={\zxBoxMinimumWidth},
+ number rows={#3},
+ number columns={#4},
+ #2,
+ }
+}
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%% Circuit-related gates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+\tikzset{
+ zx filling style/.style={
+ fill=white
+ },
+ % To change the thickness of wires and boxes at the same time
+ zx thickness wires style/.style={
+ },
+}
+
+\NewExpandableDocumentCommand{\zxCtrl}{O{}m}{%
+ \node[zx main node, circle, inner sep=2pt, fill=black, #1]{};
+}
+
+% white ctrl
+\NewExpandableDocumentCommand{\zxOCtrl}{O{}m}{%
+ \node[zx main node, circle, inner sep=2pt, zx filling style, zx thickness wires style, draw, #1]{};
+}
+
+\NewExpandableDocumentCommand{\zxNot}{O{}m}{%
+ \node[zx main node, circle, inner sep=2.5pt, draw, zx filling style, zx thickness wires style, append after command={(\tikzlastnode.north) edge[zx thickness wires style] (\tikzlastnode.south) (\tikzlastnode.east) edge[zx thickness wires style] (\tikzlastnode.west)}, #1]{};
+}
+
+\NewExpandableDocumentCommand{\zxCross}{O{}m}{%
+ \zxCoordinateMain{}
+ \node[at={(0,0)}, rectangle, inner sep=3pt, append after command={(\tikzlastnode.north east) edge[line cap=round,zx thickness wires style] (\tikzlastnode.south west) (\tikzlastnode.south east) edge[line cap=round,zx thickness wires style] (\tikzlastnode.north west)}, #1]{};
+}
+
+% Loosely inspired by
+% https://tex.stackexchange.com/questions/416055/measurement-meter-quantum-circuit-with-tikz
+% Avoid nesting tikz pictures, more efficient, more configurable
+\newsavebox\zxMeterBox
+\begin{lrbox}{\zxMeterBox}%
+ \begin{tikzpicture}[line width=.5,scale=.5]%
+ \draw[line cap=round] (0,0) to[bend left=50] (1,0);%
+ % \draw[line cap=round,-latex] (.5,-.2) to (.7,.8);
+ \draw[line cap=round,-{Stealth[length=6, round]}] (.5,-.15) to (.9,.75);%
+ %\useasboundingbox (-0.1,-.16) (1.1,.9);
+ \end{tikzpicture}%
+\end{lrbox}
+
+\NewExpandableDocumentCommand{\zxMeter}{O{1}m}{%
+ \pgfmathparse{.8*\zxMeterScale*#1}%
+ \scalebox{\pgfmathresult}{\usebox{\zxMeterBox}}%
+}
+
+% ---------------------------------
+% --- (Circuit/Gate) inputs/outputs
+% ---------------------------------
+% I found no great way to pass the style to the label... but it seems like somehow the font color
+% of the parent node is automatically transferred to the label, so the interface is not too bad
+
+\pgfkeys{
+ /zx/input style/.style={
+ align=center,
+ inner sep=2pt,
+ zxNormalFont,
+ anchor=east,
+ },
+}
+
+\def\zx@call@enlarge@brace#1{
+ \ifnum#1=1%
+ \pgfkeysalso{enlarge brace={\zxDefaultEnlargeBraceOne}}%
+ \else%
+ \pgfkeysalso{enlarge brace={\zxDefaultEnlargeBraceMulti}}%
+ \fi%
+}
+
+\NewExpandableDocumentCommand{\zxInput}{O{}m}{%
+ \zxExecuteAtEndPicture{\node[/zx/input style,#1] at (\zxGetNameRelativeNode{0}{0}){$#2$};}%
+}
+
+\pgfkeys{
+ /zx/output style/.style={
+ align=center,
+ inner sep=2pt,
+ zxNormalFont,
+ anchor=west,
+ },
+}
+
+\NewExpandableDocumentCommand{\zxOutput}{O{}m}{%
+ \zxExecuteAtEndPicture{\node[/zx/output style,#1] at (\zxGetNameRelativeNode{0}{0}){$#2$};}%
+}
+
+\pgfkeys{
+ /zx/input multi style/.style={
+ decorate,
+ decoration={brace, mirror, raise=2pt},
+ },
+ /zx/input multi label style/.style={swap,outer sep=5pt,zxNormalFont},
+}
+
+% https://tex.stackexchange.com/questions/696958/simple-way-to-specify-a-pass-a-style-with-syntax-my-style-foo/697043
+%
+\NewExpandableDocumentCommand{\zxInputMulti}{O{}O{}mm}{%
+ \zxExecuteWhenDrawingArrows{%
+ \zxArrowNow[
+ from=\zxGetNameRelativeNode{0}{0},
+ to=\zxGetNameRelativeNodeStartOne{#3}{1},
+ /zx/input multi style/.try,
+ enlarge brace/.style={
+ start anchor={[yshift=####1]},
+ end anchor={[yshift=-####1]},
+ },
+ /utils/exec={\zx@call@enlarge@brace{#3}},
+ #1,
+ "#4" {/zx/input multi label style, #2},
+ ]{}
+ }%
+}
+
+\pgfkeys{
+ /zx/output multi style/.style={
+ decorate,
+ decoration={brace, raise=2pt},
+ },
+ /zx/output multi label style/.style={outer sep=5pt,zxNormalFont},
+}
+
+% https://tex.stackexchange.com/questions/696958/simple-way-to-specify-a-pass-a-style-with-syntax-my-style-foo/697043
+%
+\def\zxDefaultEnlargeBraceMulti{.75mm}
+\def\zxDefaultEnlargeBraceOne{2mm}
+\NewExpandableDocumentCommand{\zxOutputMulti}{O{}O{}mm}{%
+ \zxExecuteWhenDrawingArrows{%
+ \zxArrowNow[
+ from=\zxGetNameRelativeNode{0}{0},
+ to=\zxGetNameRelativeNodeStartOne{#3}{1},
+ enlarge brace/.style={
+ start anchor={[yshift=####1]},
+ end anchor={[yshift=-####1]},
+ },
+ /utils/exec={\zx@call@enlarge@brace{#3}},
+ /zx/output multi style/.try,
+ #1,
+ "#4" {/zx/output multi label style, #2},
+ ]{}
+ }%
+}
+
+
+\pgfkeys{
+ /zx/gate input multi style/.style={
+ decorate,
+ decoration={brace, raise=2pt},
+ },
+ /zx/gate input multi label style/.style={
+ outer sep=4pt,
+ zxTinyFontAndSpacing
+ },
+}
+
+
+\NewExpandableDocumentCommand{\zxGateInputMulti}{O{}O{}mm}{%
+ \zxExecuteWhenDrawingArrows{%
+ \zxArrowNow[
+ from=\zxGetNameRelativeNode{0}{0}.west,
+ to=\zxGetNameRelativeNodeStartOne{#3}{1}.west,
+ /zx/gate input multi style/.try,
+ enlarge brace/.style={
+ start anchor={[yshift=####1]},
+ end anchor={[yshift=-####1]},
+ },
+ /utils/exec={\zx@call@enlarge@brace{#3}},
+ #1,
+ "#4" {/zx/gate input multi label style, #2},
+ ]{}
+ }%
+}
+
+\pgfkeys{
+ /zx/gate output multi style/.style={
+ decorate,
+ decoration={brace, mirror, raise=2pt},
+ },
+ /zx/gate output multi label style/.style={
+ swap,
+ outer sep=4pt,
+ zxTinyFontAndSpacing
+ },
+}
+
+% https://tex.stackexchange.com/questions/696958/simple-way-to-specify-a-pass-a-style-with-syntax-my-style-foo/697043
+%
+\NewExpandableDocumentCommand{\zxGateOutputMulti}{O{}O{}mm}{%
+ \zxExecuteWhenDrawingArrows{%
+ \zxArrowNow[
+ from=\zxGetNameRelativeNode{0}{0}.east,
+ to=\zxGetNameRelativeNodeStartOne{#3}{1}.east,
+ /zx/gate output multi style/.try,
+ enlarge brace/.style={
+ start anchor={[yshift=####1]},
+ end anchor={[yshift=-####1]},
+ },
+ /utils/exec={\zx@call@enlarge@brace{#3}},
+ #1,
+ "#4" {/zx/gate output multi label style, #2},
+ ]{}
+ }%
+}
+
+
+\pgfkeys{
+ /zx/gate output style/.style={
+ align=center,
+ inner sep=2pt,
+ zxTinyFontAndSpacing,
+ anchor=east,
+ },
+}
+
+\NewExpandableDocumentCommand{\zxGateOutput}{O{}m}{%
+ \zxExecuteAtEndPicture{\node[/zx/gate output style,#1] at (\zxGetNameRelativeNode{0}{0}.east){$#2$};}%
+}
+
+\pgfkeys{
+ /zx/gate input style/.style={
+ align=center,
+ inner sep=2pt,
+ zxTinyFontAndSpacing,
+ anchor=west,
+ },
+}
+
+\NewExpandableDocumentCommand{\zxGateInput}{O{}m}{%
+ \zxExecuteAtEndPicture{\node[/zx/gate input style,#1] at (\zxGetNameRelativeNode{0}{0}.west){$#2$};}%
+}
+
+% --- Same, but reading bottom to top
+
+\pgfkeys{
+ /zx/vertical input style/.style={
+ align=center,
+ inner sep=2pt,
+ zxNormalFont,
+ anchor=north,
+ },
+}
+
+\NewExpandableDocumentCommand{\zxVInput}{O{}m}{%
+ \zxExecuteAtEndPicture{\node[/zx/vertical input style,#1] at (\zxGetNameRelativeNode{0}{0}){$#2$};}%
+}
+
+\pgfkeys{
+ /zx/vertical output style/.style={
+ align=center,
+ inner sep=2pt,
+ zxNormalFont,
+ anchor=south,
+ },
+}
+
+\NewExpandableDocumentCommand{\zxVOutput}{O{}m}{%
+ \zxExecuteAtEndPicture{\node[/zx/vertical output style,#1] at (\zxGetNameRelativeNode{0}{0}){$#2$};}%
+}
+
+\pgfkeys{
+ /zx/vertical input multi style/.style={
+ decorate,
+ decoration={brace, mirror, raise=2pt},
+ },
+ /zx/vertical input multi label style/.style={swap,outer sep=5pt,zxNormalFont},
+}
+
+% https://tex.stackexchange.com/questions/696958/simple-way-to-specify-a-pass-a-style-with-syntax-my-style-foo/697043
+%
+\NewExpandableDocumentCommand{\zxVInputMulti}{O{}O{}mm}{%
+ \zxExecuteWhenDrawingArrows{%
+ \zxArrowNow[
+ from=\zxGetNameRelativeNode{0}{0},
+ to=\zxGetNameRelativeNodeStartOne{1}{2},
+ % to=\zxGetNameRelativeNodeStartOne{1}{#3},
+ /zx/vertical input multi style/.try,
+ enlarge brace/.style={
+ start anchor={[xshift=-####1]},
+ end anchor={[xshift=####1]},
+ },
+ /utils/exec={\zx@call@enlarge@brace{#3}},
+ #1,
+ "#4" {/zx/vertical input multi label style, #2},
+ ]{}
+ }%
+}
+
+\pgfkeys{
+ /zx/vertical output multi style/.style={
+ decorate,
+ decoration={brace, raise=2pt},
+ },
+ /zx/vertical output multi label style/.style={outer sep=5pt,zxNormalFont},
+}
+
+% https://tex.stackexchange.com/questions/696958/simple-way-to-specify-a-pass-a-style-with-syntax-my-style-foo/697043
+%
+\NewExpandableDocumentCommand{\zxVOutputMulti}{O{}O{}mm}{%
+ \zxExecuteWhenDrawingArrows{%
+ \zxArrowNow[
+ from=\zxGetNameRelativeNode{0}{0},
+ to=\zxGetNameRelativeNodeStartOne{1}{#3},
+ /zx/vertical output multi style/.try,
+ enlarge brace/.style={
+ start anchor={[xshift=-####1]},
+ end anchor={[xshift=####1]},
+ },
+ /utils/exec={\zx@call@enlarge@brace{#3}},
+ #1,
+ "#4" {/zx/vertical output multi label style, #2},
+ ]{}
+ }%
+}
+
+
+\pgfkeys{
+ /zx/vertical gate input multi style/.style={
+ decorate,
+ decoration={brace, raise=2pt},
+ },
+ /zx/vertical gate input multi label style/.style={
+ outer sep=4pt,
+ zxTinyFontAndSpacing
+ },
+}
+
+
+\NewExpandableDocumentCommand{\zxVGateInputMulti}{O{}O{}mm}{%
+ \zxExecuteWhenDrawingArrows{%
+ \zxArrowNow[
+ from=\zxGetNameRelativeNode{0}{0}.south,
+ to=\zxGetNameRelativeNodeStartOne{1}{#3}.south,
+ /zx/vertical gate input multi style/.try,
+ enlarge brace/.style={
+ start anchor={[xshift=-####1]},
+ end anchor={[xshift=####1]},
+ },
+ /utils/exec={\zx@call@enlarge@brace{#3}},
+ #1,
+ "#4" {/zx/vertical gate input multi label style, #2},
+ ]{}
+ }%
+}
+
+\pgfkeys{
+ /zx/vertical gate output multi style/.style={
+ decorate,
+ decoration={brace, mirror, raise=2pt},
+ },
+ /zx/vertical gate output multi label style/.style={
+ swap,
+ outer sep=4pt,
+ zxTinyFontAndSpacing
+ },
+}
+
+% https://tex.stackexchange.com/questions/696958/simple-way-to-specify-a-pass-a-style-with-syntax-my-style-foo/697043
+%
+\NewExpandableDocumentCommand{\zxVGateOutputMulti}{O{}O{}mm}{%
+ \zxExecuteWhenDrawingArrows{%
+ \zxArrowNow[
+ from=\zxGetNameRelativeNode{0}{0}.north,
+ to=\zxGetNameRelativeNodeStartOne{1}{#3}.north,
+ /zx/vertical gate output multi style/.try,
+ enlarge brace/.style={
+ start anchor={[xshift=-####1]},
+ end anchor={[xshift=####1]},
+ },
+ /utils/exec={\zx@call@enlarge@brace{#3}},
+ #1,
+ "#4" {/zx/vertical gate output multi label style, #2},
+ ]{}
+ }%
+}
+
+\pgfkeys{
+ /zx/vertical gate output style/.style={
+ align=center,
+ inner sep=2pt,
+ zxTinyFontAndSpacing,
+ anchor=north,
+ },
+}
+
+\NewExpandableDocumentCommand{\zxVGateOutput}{O{}m}{%
+ \zxExecuteAtEndPicture{\node[/zx/vertical gate output style,#1] at (\zxGetNameRelativeNode{0}{0}.north){$#2$};}%
+}
+
+\pgfkeys{
+ /zx/vertical gate input style/.style={
+ align=center,
+ inner sep=2pt,
+ zxTinyFontAndSpacing,
+ anchor=south,
+ },
+}
+
+\NewExpandableDocumentCommand{\zxVGateInput}{O{}m}{%
+ \zxExecuteAtEndPicture{\node[/zx/vertical gate input style,#1] at (\zxGetNameRelativeNode{0}{0}.south){$#2$};}%
+}
+
+%% If people prefer to read from top:
+
+\let\zxTOutput\zxVInput
+\let\zxTInput\zxVOutput
+\let\zxTOutputMulti\zxVInputMulti
+\let\zxTInputMulti\zxVOutputMulti
+\let\zxTGateOutputMulti\zxVGateInputMulti
+\let\zxTGateInputMulti\zxVGateOutputMulti
+\let\zxTGateInput\zxVGateOutput
+\let\zxTGateOutput\zxVGateInput
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%
+%%% Now using a special command for fractions (easier to code, and more customizable)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+
+%%%%% Like \zx but uses \& instead of &. This WAS useful for instance in "align" environments
+%%%%% since \zx{} was given an error (even without using &, changing the catcode was enough to
+%%%%% break the function). However, in recent versions, \zx should work as it in align, and
+%%%%% \begin{ZX}...\end{ZX} seems to always work in align without any issues.
+%%%%% Anyway, if at some points you have troubles, either use
+%%%%% \begin{ZX}[amp] ... \end{ZX} (amp is shortcut for "ampersand replacement=\&") or this function:
+\NewDocumentCommand{\zxAmp}{O{}+m}{%
+ \begin{ZX}[ampersand replacement=\&, #1]%
+ #2%
+ \end{ZX}%
+}
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%% Practical macros to automatically choose appropriate style and arrows
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% /!\ Warning: you should add {} at the end of all macros (except arrows)!
+% Not using that may work for now, but it may break later...
+% TODO: define them only in \zx environment.
+
% A swap on one line... Practical mostly to gain space. Must be used with large nodes tough...
% \NewExpandableDocumentCommand{\OneLineSwap}{}{%
% \ar[r,s,start anchor=south,end anchor=north] \ar[r,s,start anchor=north,end anchor=south]
@@ -1891,7 +4213,7 @@
}
\NewExpandableDocumentCommand{\zxLoopAboveDots}{O{20}O{}m}{%
- \ar[loop,in=90-#1,out=90+#1,looseness=8,min distance=3mm,"\cvdotsCenterMathline" {scale=.6,anchor=north,yshift=-0.25mm},#2]
+ \ar[loop,in=90-#1,out=90+#1,looseness=8,min distance=3mm,"\cvdotsCenterMathline" {zxNormalFont,scale=.6,anchor=north,yshift=-0.25mm},#2]
}
@@ -1899,49 +4221,62 @@
% and vertical, \zxNone-{} is only horizontal space, \zxNone|{} is only vertical space.
\NewExpandableDocumentCommand{\zxNone}{t+t-t|O{}m}{
\IfBooleanTF{#1}{% \zxNone+
- |[zxNone+,#4]| #5%
+ \node[zx main node, zxNone+,#4] {#5};%
}{
\IfBooleanTF{#2}{% \zxNone-
- |[zxNone-,#4]| #5%
+ \node[zx main node, zxNone-,#4] {#5};%
}{
\IfBooleanTF{#3}{% \zxNone
- |[zxNoneI,#4]| #5%
+ \node[zx main node, zxNoneI,#4] {#5};%
}{% \zxNone
- |[zxNone,#4]| #5%
- }
- }
- }
+ \node[zx main node, zxNone,#4] {#5};%
+ }%
+ }%
+ }%
}
% Usage: alias of \zxNone... To bad token can't be easily forwarded to another function.
\NewExpandableDocumentCommand{\zxN}{t+t-t|O{}m}{
\IfBooleanTF{#1}{% \zxNone+
- |[zxNone+,#4]| #5%
+ \node[zx main node, zxNone+,#4] {#5};%
}{
\IfBooleanTF{#2}{% \zxNone-
- |[zxNone-,#4]| #5%
+ \node[zx main node, zxNone-,#4]{#5};%
}{
- \IfBooleanTF{#3}{% \zxNone
- |[zxNoneI,#4]| #5%
+ \IfBooleanTF{#3}{% \zxNone|
+ \node[zx main node, zxNoneI,#4]{#5};%
}{% \zxNone
- |[zxNone,#4]| #5%
- }
- }
- }
+ \node[zx main node, zxNone,#4]{#5};%
+ }%
+ }%
+ }%
}
+
+% Usage: can be used without {}. Wait, actually it MUST be used without {} which is disturbing… to fix
+\def\zxNL{
+ \zxN{} \rar \pgfmatrixnextcell[\zxwCol]%
+}
+
+% Usage: can be used without {}
+\def\zxNR{
+ \pgfmatrixnextcell[\zxwCol] \zxN{} \ar[l]
+}
+
+
+
% Cf \zxNone, but with larger space.
\NewExpandableDocumentCommand{\zxNoneDouble}{t+t-t|O{}m}{
\IfBooleanTF{#1}{% \zxNoneDouble+
- |[zxNoneDouble+,#4]| #5%
+ \node[zx main node, zxNoneDouble+,#4]{#5};%
}{
\IfBooleanTF{#2}{% \zxNoneDouble-
- |[zxNoneDouble-,#4]| #5%
+ \node[zx main node, zxNoneDouble-,#4]{#5};%
}{
\IfBooleanTF{#3}{% \zxNoneDouble
- |[zxNoneDoubleI,#4]| #5%
+ \node[zx main node, zxNoneDoubleI,#4]{#5};%
}{% \zxNoneDouble
- |[zxNoneDouble,#4]| #5%
+ \node[zx main node, zxNoneDouble,#4]{#5};%
}
}
}
@@ -1950,77 +4285,187 @@
%% For maximum styling liberty, the content is given directly to the style.
% It allows the style to put the phase in a label.
\NewExpandableDocumentCommand{\zxZ}{O{}t*t-m}{
- |[zxZ4={#1}{\IfBooleanTF{#3}{-}{}}{\IfBooleanTF{#2}{*}{}}{#4}]| %
+ \node[zx main node, zxZ4={#1}{\IfBooleanTF{#3}{-}{}}{\IfBooleanTF{#2}{*}{}}{#4}] {}; %
}
%% For maximum styling liberty, the content is given directly to the style.
%% It allows the style to put the phase in a label.
\NewExpandableDocumentCommand{\zxX}{O{}t*t-m}{
- |[zxX4={#1}{\IfBooleanTF{#3}{-}{}}{\IfBooleanTF{#2}{*}{}}{#4}]| %
+ \node[zx main node, zxX4={#1}{\IfBooleanTF{#3}{-}{}}{\IfBooleanTF{#2}{*}{}}{#4}]{};%
}
\NewExpandableDocumentCommand{\zxH}{O{}m}{
- |[zxH,#1]| {}%
+ \node[zx main node, zxH,#1]{};%
}
% Use like: \zxFracX{\pi}{4} for positive values or for negative \zxFracX-{\pi}{4}
\NewExpandableDocumentCommand{\zxFracZ}{O{}t-moom}{%
\IfNoValueTF{#5}{% 2 arguments like: \zxFracZ{\pi}{2}
- |[zxFracZ6={#1}{\IfBooleanTF{#2}{\zxMinus}{}}{#3}{#6}{#3}{#6}]| %
+ \node[zx main node, zxFracZ6={#1}{\IfBooleanTF{#2}{\zxMinus}{}}{#3}{#6}{#3}{#6}]{};%
}{% 4 arguments like \zxFracZ{a+b}[(a+b)][(c+d)]{c+d}
- |[zxFracZ6={#1}{\IfBooleanTF{#2}{\zxMinus}{}}{#3}{#6}{#4}{#5}]| %
+ \node[zx main node, zxFracZ6={#1}{\IfBooleanTF{#2}{\zxMinus}{}}{#3}{#6}{#4}{#5}]{};%
}%
}
% Use like: \zxFracX{\pi}{4} for positive values or for negative \zxFracX-{\pi}{4}
\NewExpandableDocumentCommand{\zxFracX}{O{}t-moom}{%
\IfNoValueTF{#5}{% 2 arguments like: \zxFracZ{\pi}{2}
- |[zxFracX6={#1}{\IfBooleanTF{#2}{\zxMinus}{}}{#3}{#6}{#3}{#6}]| %
+ \node[zx main node, zxFracX6={#1}{\IfBooleanTF{#2}{\zxMinus}{}}{#3}{#6}{#3}{#6}]{};%
}{% 4 arguments like \zxFracZ{a+b}[(a+b)][(c+d)]{c+d}
- |[zxFracX6={#1}{\IfBooleanTF{#2}{\zxMinus}{}}{#3}{#6}{#4}{#5}]| %
+ \node[zx main node, zxFracX6={#1}{\IfBooleanTF{#2}{\zxMinus}{}}{#3}{#6}{#4}{#5}]{};%
}%
}
\NewExpandableDocumentCommand{\zxEmptyDiagram}{}{
- |[zxEmptyDiagram]| {}%
+ \node[zx main node, zxEmptyDiagram]{};%
}
-% Quantikz has a bug which adds space automatically.
-% https://tex.stackexchange.com/questions/618330
-% Fixing that by copying the original (unpatched) functions, and reusing them later.
-% Warning: you must load this package **before** quantikz otherwise the fix will not work.
-\let\tikzcd@@originalCopyZx\tikzcd@
-\let\endtikzcd@originalCopyZx\endtikzcd
-%%%%% Main environment \begin{ZX}...\end{ZX}
-\NewDocumentEnvironment{ZX}{O{}}{%
- \bgroup%
- \fontsize{10}{12}\selectfont% Normalize the font size to have consistent drawings everywhere.
- % Add a switch in case someone really wants the current tikzcd version:
- \ifdefined\doNotPatchQuantikz% Do not patch tikzcd.
- \else% Restore locally original tikzcd.
- \let\tikzcd@\tikzcd@@originalCopyZx%
- \let\endtikzcd\endtikzcd@originalCopyZx%
- \fi%
- \pgfsetlayers{background,edgelayer,nodelayer,main,box,labellayer,foreground}% Layers are defined locally to avoid to disturb other drawings
- \begin{tikzcd}[%
- /zx/defaultEnv,%
- #1]%
- }{\end{tikzcd}\egroup}
-
-%%%%% Shortcut macro \zx{...} equivalent to \begin{ZX}...\end{ZX}
-\newcommand\zx{%
- \begingroup% To avoid ampersand issues https://tex.stackexchange.com/a/611535/116348
- \NewDocumentCommand{\tmpZX}{O{}+m}{%
- \endgroup%
- \begin{ZX}[##1]%
- ##2%
- \end{ZX}%
+% % Example: \leftManyDots{n}
+% Useful to put on the left of a node like "n \vdots", linked to the next node. Example: \leftManyDots{n}.
+% First optional argument is scale of text, second is scale of =.
+\NewExpandableDocumentCommand{\leftManyDots}{O{1}O{\zxScaleDots}m}{%
+ \node[zx main node, zxNone+,inner xsep=0pt]{\scalebox{#1}{$#3$\,}\makebox[0pt][l]{\scalebox{#2}{$\cvdotsCenterMathline$}}}; \ar[r,-N.,start anchor=north east] \ar[r,-N',start anchor=south east] \pgfmatrixnextcell[\zxwCol]%
+}
+
+% Useful to link two nodes and put a vdots in between.
+\NewExpandableDocumentCommand{\middleManyDots}{}{%
+ \ar[r,3 vdots] \ar[o',r] \ar[o.,r]%
+}
+
+% Like \leftManyDots but on the right. Do *not* create a new node, like in |[zxShortZ]| \alpha \rightManyDots{m}
+\NewExpandableDocumentCommand{\rightManyDots}{O{1}O{\zxScaleDots}m}{%
+ \ar[r,N'-,end anchor=north west] \ar[r,N.-,end anchor=south west] \pgfmatrixnextcell[\zxwCol] \node[zx main node, zxNone+,inner xsep=0pt]{\makebox[0pt][r]{\scalebox{#2}{$\cvdotsCenterMathline$}}\scalebox{#1}{\,$#3$}};
+}
+
+% Shortcut for frequent wires
+\NewExpandableDocumentCommand{\zxDoubleO}{O{}m}{%
+ \ar[r,o.,#1] \ar[r,o',#1]
+}
+
+% Version going down
+\NewExpandableDocumentCommand{\zxDoubleOD}{O{}m}{%
+ \ar[r,o-,#1] \ar[r,-o,#1]
+}
+
+\NewExpandableDocumentCommand{\zxTtripleO}{O{}m}{%
+ \rar \ar[r,o.,#1] \ar[r,o',#1]
+}
+
+\NewExpandableDocumentCommand{\zxTripleOD}{O{}m}{%
+ \rar \ar[r,-.,#1] \ar[r,o-,#1]
+}
+
+
+\NewExpandableDocumentCommand{\zxOneOverSqrtTwo}{O{}m}{%
+ \zxZ{} \rar[#1] \ar[r,o.,#1] \ar[r,o',#1] \pgfmatrixnextcell \zxX{}
+}
+
+\NewExpandableDocumentCommand{\zxSqrtTwo}{O{}m}{%
+ \zxZ{} \rar[#1] \pgfmatrixnextcell \zxX{}
+}
+
+
+%% Need AfterEndPreamble otherwise there is an error when using tikzexternalize.
+\AfterEndPreamble{
+ \zxSaveDiagram{\zxCteOneOverSqrtTwo}{\zxZ{} \rar \ar[r,o.] \ar[r,o'] \pgfmatrixnextcell \zxX{}}
+ \zxSaveDiagram{\zxCteSqrtTwo}{\zxZ{} \rar \pgfmatrixnextcell \zxX{}}
+}
+
+%% Useful to give name to box
+%% \namedBox{(node1)(node2)}{text}
+%% \namedBox[additional style][color]{(node1)(node2)}[additional label options]{optional position:text}
+%% \begin{ZX}[
+%% execute at end picture={
+%% \zxNamedBox{(measZ)(measZ)}{right:Bell measure}
+%% }
+%% ]
+%% \zxN{} \dar[C] \ar[rrr] & & & \zxN{} \\
+%% \zxN{} \ar[rr] &&\zxX[a=measX]{x\pi} \dar[C-]\\
+%% & \zxX{r\pi} \rar& \zxZ[a=measZ]{z\pi}
+%% \end{ZX}
+
+%% Helper
+%% https://tex.stackexchange.com/questions/523579/tikz-fit-inner-sep-seperate-values-for-all-4-directions
+% \tikzset{fit margins/.style={
+% /tikz/afit/.cd,
+% #1,
+% /tikz/.cd,
+% inner xsep=\pgfkeysvalueof{/tikz/afit/left}+\pgfkeysvalueof{/tikz/afit/right},
+% inner ysep=\pgfkeysvalueof{/tikz/afit/top}+\pgfkeysvalueof{/tikz/afit/bottom},
+% xshift=-\pgfkeysvalueof{/tikz/afit/left}+\pgfkeysvalueof{/tikz/afit/right},
+% yshift=-\pgfkeysvalueof{/tikz/afit/bottom}+\pgfkeysvalueof{/tikz/afit/top},
+% afit/.cd,
+% left/.initial=1pt,right/.initial=1pt,bottom/.initial=1pt,top/.initial=1pt
+% }}
+
+\tikzset{
+ fit margins/.style={
+ /tikz/afit/.cd,#1,
+ /tikz/.cd,
+ inner xsep=\pgfkeysvalueof{/tikz/afit/left}+\pgfkeysvalueof{/tikz/afit/right},
+ inner ysep=\pgfkeysvalueof{/tikz/afit/top}+\pgfkeysvalueof{/tikz/afit/bottom},
+ %/utils/exec={\message{Last xishft is \pgfkeysvalueof{/tikz/afit/last xshift} and \pgfkeysvalueof{/tikz/afit/last yshift}}},
+ xshift/.evaluated=-\pgfkeysvalueof{/tikz/afit/last xshift}
+ -\pgfkeysvalueof{/tikz/afit/left}+\pgfkeysvalueof{/tikz/afit/right},
+ yshift/.evaluated=-\pgfkeysvalueof{/tikz/afit/last yshift}
+ -\pgfkeysvalueof{/tikz/afit/bottom}+\pgfkeysvalueof{/tikz/afit/top},
+ /tikz/afit/last xshift/.evaluated=-\pgfkeysvalueof{/tikz/afit/left}+\pgfkeysvalueof{/tikz/afit/right},
+ /tikz/afit/last yshift/.evaluated=-\pgfkeysvalueof{/tikz/afit/bottom}+\pgfkeysvalueof{/tikz/afit/top},
+ },
+ afit/.cd,
+ % used to save the last xshift done by fit margins, so that applying it twice does not shift twice
+ % since xshift=2cm,xshift=2cm is like xshift=4cm
+ last xshift/.initial=0pt,
+ last yshift/.initial=0pt,
+ % actual values
+ left/.initial=1pt,
+ right/.initial=1pt,
+ bottom/.initial=1pt,
+ top/.initial=1pt,
+ horizontal/.style={
+ left=#1,
+ right=#1,
+ },
+ vertical/.style={
+ top=#1,
+ bottom=#1,
+ },
+ all/.style={
+ horizontal=#1,
+ vertical=#1,
+ },
+ /tikz/.cd
+}
+
+\NewExpandableDocumentCommand{\zxNamedBox}{O{}O{blue}mO{}m}{
+ \node[l/.style={fit margins={all=1mm}},inner sep=2pt, node on layer=background, rounded corners, draw=#2,dashed, fill={#2!50!white}, opacity=.5, fit=#3,label={[#4]#5},#1]{};
+}
+
+% Cont is for container, equivalent of zxNamedBox but inside the matrix directly
+\NewExpandableDocumentCommand{\zxCont}{O{}O{blue}mmO{}O{}m}{%
+ \zxExecuteAtEndPicture{%
+ \zxNamedBox[zx subnode=wrapper,#1][#2]{(\zxGetNameRelativeNode{0}{0})(\zxGetNameRelativeNode{\numexpr #3-1\relax}{\numexpr #4-1\relax})#6}[#5]{#7}%
+ }%
+}
+
+% Cont is for container, equivalent of zxNamedBox but inside the matrix directly
+\NewExpandableDocumentCommand{\zxGroupGates}{O{}mmO{}O{}m}{%
+ \zxCont[fill=none,rounded corners=0pt,solid,opacity=1,zx thickness wires style,draw=black,rectangle,
+ fit margins={all=.5mm},
+ #1]{#2}{#3}[#4][#5]{#6}
+}
+
+% Cont is for container, equivalent of zxNamedBox but inside the matrix directly
+% this is the version where you specify the name of the node and not the relative pos
+\NewExpandableDocumentCommand{\zxContName}{O{}O{blue}mO{}m}{%
+ \zxExecuteAtEndPicture{%
+ \zxNamedBox[#1][#2]{(\zxGetNameRelativeNode{0}{0})#3}[#4]{#5}%
}%
- \catcode`&=13%
- \tmpZX%
}
+
+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Old code that tried to automatically find if zxShort or zxLong should be used...
%%% Now using a special command for fractions (easier to code, and more customizable)
@@ -2050,3 +4495,4 @@
}%
}%
}
+
diff --git a/graphics/pgf/contrib/zx-calculus/zx-calculus.pdf b/graphics/pgf/contrib/zx-calculus/zx-calculus.pdf
index 77f0646ac8..762c10a208 100644
--- a/graphics/pgf/contrib/zx-calculus/zx-calculus.pdf
+++ b/graphics/pgf/contrib/zx-calculus/zx-calculus.pdf
Binary files differ
diff --git a/graphics/pgf/contrib/zx-calculus/zx-calculus.sty b/graphics/pgf/contrib/zx-calculus/zx-calculus.sty
index cb6a983c1f..4cb629b513 100644
--- a/graphics/pgf/contrib/zx-calculus/zx-calculus.sty
+++ b/graphics/pgf/contrib/zx-calculus/zx-calculus.sty
@@ -2,8 +2,9 @@
% Written by Léo Colisson. Report bugs on https://github.com/leo-colisson/zx-calculus/issues
% Published under the MIT license.
\NeedsTeXFormat{LaTeX2e}
-\ProvidesPackage{zx-calculus}[2021/10/22 A package to typeset ZX calculus in directly in LaTeX, based on tikz/tikzcd.]
+\ProvidesPackage{zx-calculus}[v2.0 A package to typeset ZX calculus and circuits directly in LaTeX, based on tikz/tikzcd.]
\RequirePackage{tikz}
+\RequirePackage{tikz-cd}
\usetikzlibrary{zx-calculus} % See library in "tikzlibraryzx.code.tex".
diff --git a/graphics/pgf/contrib/zx-calculus/zx-calculus.tex b/graphics/pgf/contrib/zx-calculus/zx-calculus.tex
index c10f420285..5531da1e9c 100644
--- a/graphics/pgf/contrib/zx-calculus/zx-calculus.tex
+++ b/graphics/pgf/contrib/zx-calculus/zx-calculus.tex
@@ -1,15 +1,20 @@
-\documentclass[a4paper]{ltxdoc}
-
+\documentclass[a4paper,doc2]{ltxdoc} % doc2 is needed to force the old version, or links get colored in a weird red way even with hidelinks. https://github.com/latex3/latex2e/issues/822
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Packages
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Warning: if you compile and get:
+%% ERROR: Argument of \tikz@lib@matrix@with@options has an extra }.
+%% make sure to fix catcodes around it as | is given a different meaning in ltxdoc.
\usepackage{amsmath}
\usepackage[margin=3cm]{geometry}
\usepackage{calc}
+\usepackage{braket}
\usepackage{tikz}
\usetikzlibrary{shadows,fit}
+\usetikzlibrary{snakes}
+\usetikzlibrary{nfold} % needs very recent CTAN > 2023, or manually copy the .tex files
% \usetikzlibrary fails because file is not in current directory, lazy to setup TEXINPUTS
\makeatletter
\usetikzlibrary{zx-calculus}
@@ -18,10 +23,54 @@
\input{pgfmanual-en-macros.tex} % Is supposed to be included in recent TeX distributions, but I get errors...
\usepackage{makeidx} % Produces an index of commands.
\makeindex % Useful or not index will be created
+\usepackage{alertmessage} % For warning, info...
\usepackage[hidelinks]{hyperref}
\newcommand{\mylink}[2]{\href{#1}{#2}\footnote{\url{#1}}}
\usepackage{verbatim}
\usepackage{cleveref}
+\usepackage{mathtools}
+\usepackage{listings}
+\usepackage [
+n,
+lambda,
+advantage,
+operators,
+sets,
+adversary,
+landau,
+probability,
+notions,
+logic,
+ff,
+mm,
+primitives,
+events,
+complexity,
+asymptotics,
+keys
+] {cryptocode}
+
+%%%% Bibliography
+% I want to have separate references for appendix and main body
+% https://tex.stackexchange.com/questions/98660/
+\usepackage[style=trad-alpha,
+ sortcites=true,
+ doi=false,
+ url=false,
+ giveninits=true, % Bob Foo --> B. Foo
+ isbn=false,
+ url=false,
+ eprint=false,
+ sortcites=false, % \cite{B,A,C}: [A,B,C] --> [B,A,C]
+]{biblatex}
+\renewcommand{\multicitedelim}{, } % [ABC96; DEF12] -> [ABC96, DEF12]
+% [unknown_ref] => [??]
+% https://tex.stackexchange.com/a/352573
+\makeatletter
+\protected\def\abx@missing#1{\textbf{??}}
+\makeatother
+\renewcommand*{\bibfont}{\normalfont\small} % BibLatex font seems bigger than Bibtex?
+\addbibresource{biblio.bib}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Documentation
@@ -38,7 +87,7 @@
{\Large\bfseries ZX-calculus with \tikzname}
\vspace{1em}
- {Version 2021/10/22}\\[3mm]
+ {Léo Colisson \quad Version 2.0}\\[3mm]
{\href{https://github.com/leo-colisson/zx-calculus}{\texttt{github.com/leo-colisson/zx-calculus}}}
\end{center}
@@ -46,7 +95,7 @@
\section{Introduction}
-This library (based on the great \tikzname{} and \tikzname-cd packages) allows you to typeset ZX-calculus directly in \LaTeX{}. It comes with a default---but highly customizable---style:
+This library (based on the great \tikzname{} and \tikzname-cd packages) allows you to typeset ZX-calculus and diagrams for diagrammatic reasoning~\cite{CK17_PicturingQuantumProcesses,van20_ZXcalculusWorkingQuantum} directly in \LaTeX{}. It comes with a default---but highly customizable---style:
\begin{codeexample}[]
\begin{ZX}
\zxZ{\alpha} \arrow[r] & \zxFracX-{\pi}{4}
@@ -60,6 +109,69 @@ Even if this has not yet been tested a lot, you can also use a ``phase in label'
\end{ZX}
\end{codeexample}
+Since 24/02/2023, we also provide ways to easily create new, highly customizable shapes, with text, anchors, sub-nodes, rotations, and more:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+% Define a reusable node
+\zxNewNodeFromPic{MyDivider}[][zx create anchors={\zxVirtualCenterWest, \zxVirtualCenterEast},
+ every node/.append style={transform shape}
+ ]{
+ \node[regular polygon, regular polygon sides=3,shape border rotate=90,%shape border rotate=90,
+ draw=black,fill=gray!50, inner sep=1.6pt, rounded corners=0.8mm,zx main node] {};
+ \coordinate(\zxVirtualCenterEast) at (.2mm,0); % Used to start lines on the side of the shape
+ \coordinate(\zxVirtualCenterWest) at (-1mm,0);
+}
+% Use the node
+\begin{ZX}
+ & [2mm] & [3mm] \zxN{} \\[\zxZeroRow]
+ \zxZ[B]{} \rar[Bn'=n+m, wc] & \zxMyDivider{}
+ \rar[<',ru,Bn'Args={n}{pos=.7}]
+ \rar[Bn.Args={m}{pos=.7},<.,rd] &\\[\zxZeroRow]
+ & & \zxN{}
+\end{ZX}
+\end{codeexample}
+}
+
+Since 2023-09-27, you can also do advanced operations on multi-gate elements or use our default style:
+\begin{codeexample}[]
+\begin{ZX}[circuit, thick lines]
+ \rar & \zxGate{H} \rar & \zxGateMulti{2}{3}{H} & & \rar & \\
+ \rar & \zxGate{H} \rar & & & \rar &
+\end{ZX}
+\end{codeexample}
+
+and create more traditional circuits:
+
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+\begin{ZX}[circuit, thick lines]
+ \zxInput{\ket{\psi}} \rar & \zxBox{H} \rar & \zxCtrl{} \dar \rar & \zxCross{} \dar \rar
+ & \zxBox[add label={Measure}]{\zxMeter{}} \ar[dr,classical,--|] \\
+ \ar[r] & \zxOCtrl{} \rar \ar[u] & \zxNot{} \rar & \zxCross{} \ar[rr]
+ & & \zxBox{H} \rar & \zxOutput{\ket{\phi}}
+\end{ZX}
+\end{codeexample}
+
+\begin{codeexample}[width=0pt]
+\begin{ZX}[circuit]
+ \ar[rr] & & [\zxZeroCol] \zxCtrl{} \dar \ar[rr] & [\zxZeroCol] & \\
+ \rar \zxInputMulti{2}{\ket{\psi}} & \zxGateMulti{3}{3}{U} \zxGateInputMulti{2}{x}
+ & & \rar \zxGateOutputMulti{2}{x \oplus y} & \zxOutputMulti{2}{\text{Output}} \\
+ \rar &
+ & & \rar & \\
+ \rar \zxInput{\ket{0}} & \zxGateInput{y}
+ & & \rar \zxGateOutput{y \oplus 1} & \zxOutput{\ket{1}}
+\end{ZX}
+\end{codeexample}
+
+\begin{codeexample}[width=0cm]
+ \begin{ZX}[circuit]
+ \ar[rr] && \zxCtrl{} \ar[dl, end subnode=wrapper] \ar[rr] && \\
+ \rar & \zxCtrl{} \dar \rar \zxGroupGates{2}{3}{below:\textsc{swap}} & \zxNot{} \dar \rar & \zxCtrl{} \dar \rar & \\
+ \rar & \zxNot{} \rar & \zxCtrl{} \rar & \zxNot{} \rar &
+ \end{ZX}
+\end{codeexample}
+}
The goal is to provide an alternative to the great |tikzit| package: we wanted a solution that does not require the creation of an additional file, the use of an external software, and which automatically adapts the width of columns and rows depending on the content of the nodes (in |tikzit| one needs to manually tune the position of each node, especially when dealing with large nodes). Our library also provides a default style and tries to separate the content from the style: that way it should be easy to globally change the styling of a given project without redesigning all diagrams. However, it should be fairly easy to combine tikzit and this library: when some diagrams are easier to design in tikzit, then it should be possible to directly load the style of this library inside tikzit.
@@ -84,13 +196,19 @@ If this library is not yet packaged into CTAN (which is very likely in 2021), yo
\section{Quickstart}
-You can create a diagram either with |\zx[options]{matrix}| or with:
+You can create a diagram either with |\zx[options]{matrix}|, |\zxAmp[options]{matrix}| or with:
\begin{verse}
|\begin{ZX}[options]|\\
| matrix|\\
|\end{ZX}|
\end{verse}
-The matrix is composed of columns separated by |&| and rows separated by |\\|. This matrix is basically a \tikzname{} matrix of nodes (even better, a |tikz-cd| matrix, so you can use all the machinary of |tikz-cd|), so cells can be created using \verb#|tikz style| content#. However, the users does not usually need to use this syntax since many nodes like |\zxZ{spider phase}| have been created for them (including |\zxN{}| which is an empty node):
+The matrix is composed of rows separated by |\\| and columns separated by |&| (except in |\zxAmp| where columns are separated with |\&|).
+
+% \alertwarning{ % Can't use |...| or \verb|...| in this environment :'(
+% Due to \LaTeX{} restrictions, \texttt{\&} can sometimes cause some troubles. \texttt{\textbackslash{}zxAmp} is always guaranteed to work (just make sure to use \texttt{\textbackslash{}\&} instead of \texttt{\&}). See \cref{subsec:addDiagram} for more details.
+% }
+
+This matrix is basically a \tikzname{} matrix of nodes (even better, a |tikz-cd| matrix, so you can use all the machinary of |tikz-cd|), so cells can be created using \verb#|[tikz style]| content#. However, the users does not usually need to use this syntax since many nodes like |\zxZ{spider phase}| have been created for them (including |\zxN{}| which is an empty node):
\begin{codeexample}[width=0pt]
\begin{ZX}
@@ -109,14 +227,39 @@ To link the nodes, you should use |\arrow[options]| (|\ar[options]| for short) a
& & \zxX-{\alpha}
\end{ZX}
\end{codeexample}
-See how the alignment of your matrix helps reading it: in emacs |M-x align| is your friend. You may also encounter some shortcuts, like |\rar| instead of |\ar[r]|. Since straight lines are boring, we created many styles that you can just add in the options. For instance, a measured Bell-pair can be created using the |C| style (note also how the |*| argument forces the node to be tighter):
+See how the alignment of your matrix helps reading it: in emacs |M-x align| is your friend (or even better, if you are tired of selecting the lines to align, bind \mylink{https://tex.stackexchange.com/a/64566/116348}{this \texttt{align-environment} function} to some shortcuts, like |C-<tab>| and you will just have to do a single key-press to align your matrix).
+
+You may also encounter some shortcuts, like |\rar| instead of |\ar[r]|. Since straight lines are boring, we created many styles that you can just add in the options. For instance, a measured Bell-pair can be created using the |C| style (note also how the |*| argument forces the node to be tighter), as the name of the style tries to mimic the shape of the wire:
\begin{codeexample}[]
\begin{ZX}
\zxZ*{a \pi} \ar[d,C]\\
\zxZ*{b \pi}
\end{ZX}
\end{codeexample}
-The name of the style usually tries to graphically represent the shape of a node (here it looks like a |C|). We also introduce many other styles, like |N| for wires that arrive and leave at wide angle (yeah, the |N| is the best letter I could find to fit that shape):
+
+\alertinfo{
+ \textbf{Tips}: on small diagrams, describing the arrow position using relative position like \texttt{rrb} works really nicely, but on big diagrams that you need to rewrite, it can quickly be hard to manage, as moving a node will break all links to it. While it is possible to specify both |from| and |to| in an absolute way, the experience shows that it is easier to work with a ``semi-relative'' addressing, where only the |to| is specified in an absolute setting, while the |from| is automatically derived from the current position of the arrow. You can use \texttt{a=somename} to give a name for a node (\texttt{a} being the short name of alias).}
+
+This way, on non-trivial diagrams, we recommend to format graphs like:
+\begin{codeexample}[]
+\begin{ZX}
+ \zxN{} & \zxZ[a=beta]{\beta} \\
+ \zxZ{\alpha} \ar[to=beta,N] \ar[to=gamma,N] & \\
+ & \zxZ[a=gamma]{\gamma}
+\end{ZX}
+\end{codeexample}
+Note that you can also set |debug mode| to display the name of the nodes for an easier addressing:
+\begin{codeexample}[]
+\begin{ZX}[debug mode]
+ % See how the code stayed unchanged despite changing the position of the nodes
+ \zxN{} & \zxZ[a=beta]{\beta} \\
+ \zxZ{\alpha} \ar[to=beta,N] \ar[to=gamma,N] & \\
+ & \\
+ & & \zxZ[a=gamma]{\gamma}
+\end{ZX}
+\end{codeexample}
+
+We also introduce many other styles, like |N| for wires that arrive and leave at wide angle (yeah, the |N| is the best letter I could find to fit that shape):
\begin{codeexample}[]
\begin{ZX}
\zxN{} & \zxZ{\beta}\\
@@ -124,11 +267,11 @@ The name of the style usually tries to graphically represent the shape of a node
& \zxZ{\gamma}
\end{ZX}
\end{codeexample}
-Or |s| for wires that arrive and leave at sharp angles (the |\zxN{}| is used because it seems that the first cell of a matrix can't be empty):
+Or |s| for wires that arrive and leave at sharp angles\footnote{Note: on older versions, a |\textbackslash zxN\{\}| might be needed on the first cell as it seems that the first cell of a matrix can't be empty… this should be fixed in latest versions.}:
\begin{codeexample}[]
\begin{ZX}
- \zxN{} & \zxZ{\beta}\\
- \zxZ{\alpha} \ar[ru,s] \ar[rd,s] &\\
+ & \zxZ{\beta} \\
+ \zxZ{\alpha} \ar[ru,s] \ar[rd,s] & \\
& \zxZ{\gamma}
\end{ZX}
\end{codeexample}
@@ -146,7 +289,7 @@ Similarly |o'| is a style for wires that have the shape of the top part of the c
\zxZ{\beta}
\end{ZX}
\end{codeexample}
-Note that the position of the embellishments (|'|, |-|, |.|\dots{}) tries to graphically represent the shape of the node. That way |-o| means ``take the left part (position of |-|) or the circle |o|''. Applied to |C|, this gives:
+Note that the position of the embellishments (|'|, |-|, |.|\dots{}) tries to graphically represent the shape of the node. That way |-o| means ``take the left part (position of |-|) of the circle |o|''. Applied to |C|, this gives:
\begin{codeexample}[]
\begin{ZX}
\zxX{} \ar[d,C] \ar[r,C'] & \zxZ{} \ar[d,C-]\\
@@ -160,7 +303,7 @@ You also have styles which automatically add another node in between, for instan
\zxZ{\alpha} \ar[r,o',H] \ar[r,o.,H] &[\zxHCol] \zxZ{\beta}
\end{ZX}
\end{codeexample}
-Note that we used also |&[\zxHCol]| instead of |&| (on the first line). This is useful to add an extra space between the columns to have a nicer look. The same apply for rows (see the |*Row| instead of |*Col|):
+Note that we used also |&[\zxHCol]| instead of |&| (on the first line). This is useful to add an extra space between the columns to have a nicer look. The same applies for rows (see the |*Row| instead of |*Col|):
\begin{codeexample}[]
\begin{ZX}
\zxZ{\alpha} \ar[d,-o,Z] \ar[d,o-,X] \\[\zxSRow]
@@ -182,7 +325,15 @@ The reason for this is that it is hard to always get exactly the good spacing by
\end{codeexample}
-When writing equations, you may also want to change the baseline to align properly your diagrams on a given line like that:
+When writing equations, you may also want to change the baseline to align properly your diagrams on a given line like that (since march 2023):
+\begin{codeexample}[]
+ $\zx[mbr=2]{ % mbr is a shortcut for "math baseline row"
+ \zxX{}\\
+ \zxZ[a=myZ]{}
+ }
+ = \zx{\zxX{} & \zxZ{}}$
+\end{codeexample}
+You can also specify (this works on older versions) a specific node like that (|a=blabla| gives the alias name |blabla| to the node, and configure tools useful for debugging):
\begin{codeexample}[]
$\zx[math baseline=myZ]{
\zxX{}\\
@@ -274,7 +425,7 @@ Now you should know enough to start your first diagrams. The rest of the documen
\end{ZX}
} \ (of course it only helps during the construction).\\
-You will also see how you can customize the styles, and how you can easily extand this library to get any custom diagram:
+You will also see how you can customize the styles, and how you can easily extend this library to get any custom diagram:
{\catcode`\|=12 % Ensures | is not anymore \verb|...|
\begin{codeexample}[width=0pt]
{ % \usetikzlibrary{shadows}
@@ -301,12 +452,13 @@ If you have some questions, suggestions, or bugs, please report them on \texttt{
\section{Usage}
-\subsection{Add a diagram}
+\subsection{Add a diagram}\label{subsec:addDiagram}
\begin{pgfmanualentry}
\extractcommand\zx\opt{\oarg{options}}\marg{your diagram}\@@
\extractenvironement{ZX}\opt{\oarg{options}}\@@
+ \extractcommand\zxAmp\opt{\oarg{options}}\marg{your diagram}\@@
\pgfmanualbody
- You can create a new ZX-diagram either with a command (quicker for inline diagrams) or with an environment. The \meta{options} can be used to locally change the style of the diagram, using the same options as the |{tikz-cd}| environment (from the \mylink{https://www.ctan.org/pkg/tikz-cd}{\texttt{tikz-cd} package}). The \meta{your diagram} argument, or the content of |{ZX}| environment is a \tikzname{} matrix of nodes, exactly like in the |tikz-cd| package: columns are separated using |&|, columns using |\\|, and nodes are created using \verb#|[tikz style]| node content# or with shortcut commands presented later in this document (recommended). Content is typeset in math mode by default, and diagrams can be included in any equation. Wires can be added like in |tikz-cd| (see more below) using |\arrow| or |\ar|: we provide later recommended styles to quickly create different kinds of wires which can change with the configured style.
+ You can create a new ZX-diagram either with a macro (quicker for inline diagrams) or with an environment. All these commands are mostly equivalent, except that in |\zxAmp| columns are separated with |\&| instead of |&| (this was useful before as |&| was not usable in |align| or inside macros. Now it should be fixed.). The \meta{options} can be used to locally change the style of the diagram, using the same options as the |{tikz-cd}| environment (from the \mylink{https://www.ctan.org/pkg/tikz-cd}{\texttt{tikz-cd} package}). The \meta{your diagram} argument, or the content of |{ZX}| environment is a \tikzname{} matrix of nodes, exactly like in the |tikz-cd| package: rows are separated using |\\|, columns using |&| (except for |\zxAmp| where columns are separated using |\&|), and nodes are created using \verb#|[tikz style]| node content# or with shortcut commands presented later in this document (recommended). Wires can be added like in |tikz-cd| (see more below) using |\arrow| or |\ar|: we provide later recommended styles to quickly create different kinds of wires which can change with the configured style. Content is typeset in math mode by default, and diagrams can be included in any equation.
{\catcode`\|=12 % Ensures | is not anymore \verb|...|
% Do not indent not to put space in final code
\begin{codeexample}[]
@@ -320,8 +472,23 @@ and custom diagram: %
}
\end{pgfmanualentry}
-\subsection{Nodes}
+\begin{stylekey}{/zx/defaultEnv/amp}
+ In a previous version (before 2022/02/09), it was not possible to use |&| inside macros and |align| due to \LaTeX{} limitations. However, we found a solution by re-scanning the tokens, so now no special care should be taken in align or macros. But in case you need to deal with an environment having troubles with |&|, either use the |ampersand replacement=\&| option (whose shortcut is |amp|) or |\zxAmp| (in any case, replace |&| with |\&|).
+\begin{codeexample}[vbox]
+An aligned equation:
+\begin{align}
+ \zxAmp{\zxZ{} \arrow[r] \& \zxX{}} &= \begin{ZX}[amp] \zxX{} \arrow[r] \& \zxZ{} \end{ZX}
+\end{align}
+This limitation does not apply anymore:
+\begin{align}
+ \zx{\zxZ{} \arrow[r] & \zxX{}} &= \begin{ZX} \zxX{} \arrow[r] & \zxZ{} \end{ZX}
+\end{align}
+even in macros: {\setlength{\fboxsep}{0pt} \fbox{\zx{\zxZ{} \rar & \zxX{}}}}
+\end{codeexample}
+\end{stylekey}
+\subsection{Nodes}
+\subsubsection{Spiders}
The following commands are useful to create different kinds of nodes. Always add empty arguments like |\example{}| if none are already present, otherwise if you type |\example| we don't guarantee backward compatibility.
\begin{command}{\zxEmptyDiagram{}}
@@ -335,12 +502,14 @@ The following commands are useful to create different kinds of nodes. Always add
\begin{pgfmanualentry}
- \extractcommand\zxNone\opt{+}\opt{-}\marg{text}\@@
- \extractcommand\zxN\opt{+}\opt{-}\marg{text}\@@
+ \extractcommand\zxNone\opt{-\textbar+}\marg{text}\@@
+ \extractcommand\zxN\opt{-\textbar+}\marg{text}\@@
+ \extractcommand\zxNL\@@
+ \extractcommand\zxNR\@@
\pgfmanualbody
- Adds an empty node with |\zxNone{}| (alias |\zxN{}|). The \verb#-|+# decorations are used to add a bit of horizontal (\verb#\zxNone-{}#), vertical (\verb#\zxNone|{}#) and both (\verb#\zxNone+{}#) spacing (I don't know how to add \verb#|# in the documentation of the function).
+ Adds an empty node with |\zxNone{}| (alias |\zxN{}|). The \verb#-|+# decorations are used to add a bit of horizontal (\verb#\zxNone-{}#), vertical (\verb#\zxNone|{}#) and both (\verb#\zxNone+{}#) spacing.
- |\zxNone| is just a coordinate (when possible this node should be preferred over the other versions), but |\zxNone-{}| and \verb#\zxNone|{}# are actually nodes with |inner sep=0| along one direction. For that reason, they still have a tiny height or width (impossible to remove as far as I know). If you don't want to get holes when connecting multiple wires to them, it is therefore necessary to use the |wire centered| style (alias |wc|) (if you are using the |IO| mode, see also the |between none| style).
+ |\zxNone| is just a coordinate (and therefore can't have any text inside, but when possible this node should be preferred over the other versions since it has really zero width), but |\zxNone-{}| and \verb#\zxNone|{}# are actually nodes with |inner sep=0| along one direction. For that reason, they still have a tiny height or width (impossible to remove as far as I know). If you don't want to get holes when connecting multiple wires to them, it is therefore necessary to use |\zxNone{}| or the |wire centered| style (alias |wc|) (if you are using the |IO| mode, see also the |between none| style). But anyway you should mostly use |\zxNone|.
Moreover, you should also add column and row spacing |&[\zxWCol]| and |\\[\zxWRow]| to avoid too shrinked diagrams when only wires are involved.
\begin{codeexample}[width=3cm]
@@ -357,7 +526,24 @@ Compare \begin{ZX}
\zxN{} \rar &[\zxwCol] \zxZ{} \rar &[\zxwCol] \zxN{}
\end{ZX}
\end{codeexample}
-Note also that when the top left cell is empty, you can get an error at the compilation (no idea why) |Single ampersand used with wrong catcode|. To prevent that, you can add a none node at this position:
+This kind of code is so common that there is an alias for it: |\zxNL| and |\zxNR| automatically add a |\zxN{}| node, configure the column space (for this reason don't add an additional |&|, and be aware that emacs won't align them properly. Note also that the space will only be taken into account if it is on the first line) and add a straight arrow. The |L/R| part of the name is just to specify if the node is on the right or left of the diagram to put the column and arrow on the right side:
+\begin{codeexample}[]
+\zx{\zxNL \zxX{} \zxNR}
+\end{codeexample}
+Note that these two alias can be used without |{}|. But they are the only ones.
+
+The \verb!\zxN|{text}! and \verb!\zxN-{text}! may be useful to display some texts:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[]
+ \begin{ZX}[content fixed baseline]
+ & \zxN|{\dots} \dar \\
+ \zxZ{\theta_i} \rar & \zxZ{} \dar \rar & \zxZ{-(\delta_i+\theta_i+r\pi)}\rar & \zxH{} \rar & \zxX{a\pi} \\
+ & \zxN|{\dots} \\
+ \end{ZX}
+\end{codeexample}
+}
+
+When the top left cell is empty, you may get an error at the compilation |Single ampersand used with wrong catcode| (this error should be fixed in latest releases) or |<symbol> allowed only in math mode| (not sure why). To solve this issue, you can add an empty node on the very first cell:
\begin{codeexample}[]
\begin{ZX}
\zxN{} &[\zxwCol] \zxN{} \ar[d]\\[\zxwRow]
@@ -365,11 +551,12 @@ Note also that when the top left cell is empty, you can get an error at the comp
\end{ZX}
\end{codeexample}
\end{pgfmanualentry}
-You may also get this error when |&| has already a different meaning, for instance in |align|, in that case you may change the |&| character into |\&| using |[ampersand replacement=\&]|:
+
+You may also get the error |Single ampersand used with wrong catcode| when |&| has already a different meaning, for instance in |align|, in that case you may change the |&| character into |\&| using |[ampersand replacement=\&]|. Note however that in recent versions ($\geq$ 2022/02/09) this should not happen anymore.
\begin{codeexample}[vbox]
\begin{align}
\begin{ZX}[ampersand replacement=\&]
- \zxN{} \rar \&[\zxwCol] \zxN{}
+ \zxN{} \rar \&[\zxWCol] \zxN{}
\end{ZX}
&= \begin{ZX}[ampersand replacement=\&]
\zxN{} \rar \&[\zxwCol] \zxZ{} \rar \&[\zxwCol] \zxN{}
@@ -380,17 +567,19 @@ You may also get this error when |&| has already a different meaning, for instan
\end{align}
\end{codeexample}
-\begin{command}{\zxNoneDouble\opt{+-}\marg{text}}
- Like |\zxNone|, but the spacing for \verb#+-|# is large enough to fake two lines in only one. Not extremely useful (or one needs to play with |start anchor=south,end anchor=north|).
+\begin{command}{\zxNoneDouble\opt{-\textbar+}\marg{text}}
+ Like |\zxNone|, but the spacing for \verb#-|+# is large enough to fake two lines in only one. Not extremely useful (or one needs to play with |start anchor=south,end anchor=north|).
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
\begin{codeexample}[width=3cm]
\begin{ZX}
\zxNoneDouble|{} \ar[r,s,start anchor=north,end anchor=south] \ar[r,s,start anchor=south,end anchor=north] &[\zxWCol] \zxNoneDouble|{}
\end{ZX}
\end{codeexample}
+}
\end{command}
\begin{command}{\zxFracZ\opt{-}\marg{numerator}\opt{\oarg{numerator with parens}\oarg{denominator with parens}}\marg{denominator}}
- Adds a Z node with a fraction, use the minus decorator to add a small minus in front (the default minus is very big).
+ Adds a Z node with a fraction, use the minus decorator to add a small minus in front (a normal minus would be too big, but you can configure the symbol).
\begin{codeexample}[width=3cm]
\begin{ZX}
\zxFracZ{\pi}{2} & \zxFracZ-{\pi}{2}
@@ -398,7 +587,7 @@ You may also get this error when |&| has already a different meaning, for instan
\end{codeexample}
The optional arguments are useful when the numerator or the denominator need parens when they are written inline (in that case optional arguments must be specified): it will prove useful when using a style that writes the fraction inline, for instance the default style for labels:
\begin{codeexample}[]
-Compare
+Compare %
\begin{ZX}
\zxFracZ{a+b}[(a+b)][(c+d)]{c+d}
\end{ZX} with %
@@ -421,7 +610,7 @@ Compare
Adds a Z node. \meta{other styles} are optional \tikzname{} arguments (the same as the one provided to |tikz-cd|) They should be use with care, and if possible moved to the style directly to keep a consistent look across the paper.
\begin{codeexample}[width=3cm]
\begin{ZX}
- \zxZ{} & \zxZ{\alpha} & \zxZ{\alpha + \beta} & \zxZ[text=red]{(a \oplus b)\pi}
+ \zxZ{} & \zxZ{\alpha} & \zxZ{\alpha + \beta} & \zxZ[fill=blue!50!white,text=red]{(a \oplus b)\pi}
\end{ZX}
\end{codeexample}
The optional |-| optional argument is to add a minus sign (customizable, see |\zxMinusInShort|) in front of a very short expression and try to keep a circular shape. This is recommended notably for single letter expressions.
@@ -484,7 +673,7 @@ The |*| optional argument is to force a condensed style, no matter what is the t
\end{command}
\begin{command}{\middleManyDots{}}
- Shortcut to add a dots and a text next to it. It automatically adds the new column, see more examples below.
+ Shortcut to add a dots and a text next to it, see more examples below.
\begin{codeexample}[width=3cm]
\begin{ZX}
\zxX{\alpha} \middleManyDots{} & \zxX{\beta}
@@ -518,24 +707,76 @@ The |*| optional argument is to force a condensed style, no matter what is the t
\end{ZX}
\end{codeexample}
-\subsection{Phase in label style}
+
+\begin{pgfmanualentry}
+ \makeatletter
+ \def\extrakeytext{style, }
+ \extractkey/zx/styles/rounded style/content vertically centered\@nil%
+ \extractkey/zx/styles/rounded style/content fixed baseline\@nil%
+ \extractkey/zx/styles/rounded style preload/content vertically centered\@nil%
+ \extractkey/zx/styles/rounded style preload/content fixed baseline\@nil%
+ \extractkey/zx/styles/rounded style preload/content fixed also frac\@nil%
+ \makeatother
+ \pgfmanualbody
+ By default the content of the nodes are vertically centered. This can be nice to have as much space as possible around the text, but when using several nodes with letters having different height or depth, the baseline of each node won't be aligned (this is particularly visible on nodes with very high text, like |b'|):
+\begin{codeexample}[width=0pt]
+\begin{ZX}
+ \zxX[a=start]{\alpha} & \zxX{\beta} & \zxX{a} & \zxX{b} & \zxX*{a\pi} & \zxX*{b\pi}
+ & \zxX*{b'\pi} & \zxZ*{'b\pi} & \zxZ{(a \oplus b )\pi} & \zxFracX-{\pi}{4}
+ & \zxFracZ{\pi}{4} & \zxZ-{\delta} & \zxZ[a=end]-{\gamma}
+ \ar[from=start,to=end,on layer=background]
+\end{ZX}
+\end{codeexample}
+Using |content fixed baseline|, it is however possible to fix the height and depth of the text to make sure the baselines are aligned (|content vertically centered| is use to come back to the default behavior). When used as a ZX option, it avoids setting this on fractions since it renders poorly. Use |content fixed baseline also frac| if you also want to fix the baseline of all fractions as well (this last style is useful only as a ZX option, since |content fixed baseline| works on all nodes).
+\begin{codeexample}[width=0pt]
+\begin{ZX}[content fixed baseline]
+ \zxX[a=start]{\alpha} & \zxX{\beta} & \zxX{a} & \zxX{b} & \zxX*{a\pi} & \zxX*{b\pi}
+ & \zxX*{b'\pi} & \zxZ*{'b\pi} & \zxZ{(a \oplus b )\pi} & \zxFracX-{\pi}{4}
+ & \zxFracZ{\pi}{4} & \zxZ-{\delta} & \zxZ[a=end]-{\gamma}
+ \ar[from=start,to=end,on layer=background]
+\end{ZX}
+\end{codeexample}
+Note however that the height is really hardcoded (not sure how to avoid that) and is quite small (otherwise nodes quickly become too large), so too large content may overlay on top of the node (this is visible on the |'b\pi| node). You can use this style either on a per-picture basis (it's what we just did), on a per-node basis (just use it in the options of the node), or globally:
+\begin{codeexample}[width=0pt]
+\tikzset{
+ /zx/user overlay/.style={
+ content fixed baseline,
+ },
+}
+\begin{ZX}
+ \zxX[a=start]{\alpha} & \zxX{\beta} & \zxX{a} & \zxX{b} & \zxX*{a\pi} & \zxX*{b\pi}
+ & \zxX*{b'\pi} & \zxZ*{'b\pi} & \zxZ{(a \oplus b )\pi} & \zxFracX-{\pi}{4}
+ & \zxFracZ{\pi}{4} & \zxZ-{\delta} & \zxZ[a=end]-{\gamma}
+ \ar[from=start,to=end,on layer=background]
+\end{ZX}
+\end{codeexample}
+It can also be practical to combine it with |small minus|:
+\begin{codeexample}[]
+\begin{ZX}
+ \zxZ-{\delta_j} & \zxZ[content fixed baseline]-{\delta_j} &
+ \zxZ[small minus]-{\delta_j} & \zxZ[content fixed baseline,small minus]-{\delta_j}
+\end{ZX}
+\end{codeexample}
+\end{pgfmanualentry}
+
+\subsubsection{Phase in label style}
We also provide styles to place the phase on a label next to an empty node (not yet very well tested):
\begin{pgfmanualentry}
\makeatletter
\def\extrakeytext{style, }
- \extractkey/zx/styles rounded style/phase in content\@nil%
- \extractkey/zx/styles rounded style/phase in label=style (default {})\@nil%
- \extractkey/zx/styles rounded style/pil=style (default {})\@nil%
- \extractkey/zx/styles rounded style/phase in label above=style (default {})\@nil%
- \extractkey/zx/styles rounded style/pila=style (default {})\@nil%
- \extractkey/zx/styles rounded style/phase in label below=style (default {})\@nil%
- \extractkey/zx/styles rounded style/pilb=style (default {})\@nil%
- \extractkey/zx/styles rounded style/phase in label right=style (default {})\@nil%
- \extractkey/zx/styles rounded style/pilr=style (default {})\@nil%
- \extractkey/zx/styles rounded style/phase in label left=style (default {})\@nil%
- \extractkey/zx/styles rounded style/pill=style (default {})\@nil%
+ \extractkey/zx/styles/rounded style/phase in content\@nil%
+ \extractkey/zx/styles/rounded style/phase in label=style (default {})\@nil%
+ \extractkey/zx/styles/rounded style/pil=style (default {})\@nil%
+ \extractkey/zx/styles/rounded style/phase in label above=style (default {})\@nil%
+ \extractkey/zx/styles/rounded style/pila=style (default {})\@nil%
+ \extractkey/zx/styles/rounded style/phase in label below=style (default {})\@nil%
+ \extractkey/zx/styles/rounded style/pilb=style (default {})\@nil%
+ \extractkey/zx/styles/rounded style/phase in label right=style (default {})\@nil%
+ \extractkey/zx/styles/rounded style/pilr=style (default {})\@nil%
+ \extractkey/zx/styles/rounded style/phase in label left=style (default {})\@nil%
+ \extractkey/zx/styles/rounded style/pill=style (default {})\@nil%
\makeatother
\pgfmanualbody
The above styles are useful to place a spider phase in a label outside the node. They can either be put on the style of a node to modify a single node at a time:
@@ -551,16 +792,14 @@ We also provide styles to place the phase on a label next to an empty node (not
\end{codeexample}
\noindent or globally:
\begin{codeexample}[]
-{
- \tikzset{
- /zx/user post preparation labels/.style={
- phase in label={label position=-45, text=purple,fill=none}
- }
- }
- \zx{
- \zxFracX-{\pi}{2}
+\tikzset{
+ /zx/user overlay/.style={
+ phase in label={label position=-45, text=purple,fill=none}
}
}
+\zx{
+ \zxFracX-{\pi}{2}
+}
\end{codeexample}
Note that we must use |user post preparation labels| and not |/zx/user overlay nodes| because this will be run after all the machinery for labels has been setup.
@@ -600,6 +839,17 @@ For fractions, you can configure how you want the label text to be displayed, ei
Note that in |\zxFracZ{a+b}[(a+b)][(c+d)]{c+d}| the optional arguments are useful to put parens appropriately when the fraction is written inline.
\end{pgfmanualentry}
+\begin{stylekey}{/zx/defaultEnvdebug mode}
+ If this macro is defined, debug mode is active. See below how it can be useful (here is a quick example).
+\begin{codeexample}[width=3cm]
+\begin{ZX}[debug mode]
+ \rar[B] & [\zxwCol] \zxDivider[a=divTop]{} & \\
+ & & \zxZ[a=Ztopleft]{}
+ \ar[from=divTop, to=Ztopleft]
+\end{ZX}
+\end{codeexample}
+\end{stylekey}
+
\begin{command}{\zxDebugMode{}}
If this macro is defined, debug mode is active. See below how it can be useful.
\end{command}
@@ -649,7 +899,7 @@ Also, if you find your diagram a bit ``too high'', check that you did not forget
\begin{codeexample}[width=3cm]
Compare $\begin{ZX}
\zxZ{} \rar[o'] \rar[o.] & \zxX{}\\
- \zxZ{} \rar[o'] \rar[o.] \rar & \zxX{}\\ %% <--- remove last |\\|
+ \zxZ{} \rar[o'] \rar[o.] \rar & \zxX{}\\ %% <--- remove last \\
\end{ZX} = \zx{\zxEmptyDiagram}$ with $\begin{ZX}
\zxZ{} \rar[o'] \rar[o.] & \zxX{}\\
\zxZ{} \rar[o'] \rar[o.] \rar & \zxX{}
@@ -657,6 +907,739 @@ Also, if you find your diagram a bit ``too high'', check that you did not forget
\end{codeexample}
\end{stylekey}
+\begin{pgfmanualentry}
+ \def\extrakeytext{style, }
+ \makeatletter% should not be letter for \@@... strange
+ \extractkey/zx/defaultEnv/math baseline row=row to center (default {1})\@nil%
+ \extractkey/zx/defaultEnv/mbr=row to center (default {1})\@nil%
+ \makeatother
+ You can also choose directly a line to center on: for instance to center on the first line, use: |math baseline row=1|, or, equivalently |mbr=1| or directly |mbr|:
+\begin{codeexample}[width=0pt]
+ $\begin{ZX}[mbr]
+ \zxN{} \rar[B] & [\zxwCol] \zxMatrix{A} \rar[B] &[\zxwCol] \zxN{}
+ \end{ZX} = A$
+\end{codeexample}
+Since 2023/10/03 you can also use a float value to specify that you want to set the center between two lines:
+\begin{codeexample}[width=0pt]
+ Compare $G = \begin{ZX}[circuit]
+ \rar & \zxGate{G} \rar & \zxGate{H} \rar & \\
+ \ar[rrr] & & &
+ \end{ZX}$ with $G = \begin{ZX}[circuit,mbr=1.5]
+ \rar & \zxGate{G} \rar & \zxGate{H} \rar & \\
+ \ar[rrr] & & &
+ \end{ZX}$.
+\end{codeexample}
+\end{pgfmanualentry}
+
+\subsubsection{Ground}
+
+\textbf{NB}: this functionality, based on custom nodes (\cref{subsec:customNodes}) was added on 13/03/2023.
+
+\begin{pgfmanualentry}
+ \def\extrakeytext{style, }
+ \extractcommand\zxGround\oarg{picture style}\opt{.}\opt{-}\opt{'}\marg{}\@@
+ \extractcommand\zxGroundScale\@@
+ \pgfmanualbody
+The ground symbol can be used to denote a discarding operation… but is also useful to compute the norm of a state or denote a measurement by first copying the state and discarding one copy. This way, a measurement in the computational basis can be represented as:
+\begin{codeexample}[width=0pt]
+ \begin{ZX}
+ & [\zxwCol] & [\zxwCol] \zxN{} \rar & \zxN{} \\
+ \zxN{} \rar & \zxZ{} \ar[ur,<'] \ar[dr,<'] & \\[\zxZeroRow]
+ & & \zxGround{}
+ \end{ZX}
+\end{codeexample}
+You can also change the direction using the alternative names:
+\begin{codeexample}[]
+ \begin{ZX}
+ \zxGround-{}\rar & \zxGround{} \\
+ \zxGround'{}\dar\\
+ \zxGround.{}
+ \end{ZX}
+\end{codeexample}
+Internally, the ground symbol is drawn using a |pic|, so you can customize it as any other pic:
+\begin{codeexample}[]
+ \begin{ZX}
+ \zxN{} \rar &[\zxwCol] \zxGround[scale=1.5,red,rotate=45]{}
+ \end{ZX}
+\end{codeexample}
+Note that you can also redefine |\def\zxGroundScale{1.8}| to change the default scale on a whole document.
+Moreover, by default the |pic| takes some space (this way it will not overlap with the next symbol, or the text below/after), but you want sometimes to make it |overlay|, for instance to preserve the symmetry with an empty wire (then, you might need to add some column space |&[yourspace]| or row space |\\[yourspace]| to avoid overlap with text around it):
+\begin{codeexample}[width=0pt]
+ Compare
+ \begin{ZX}
+ & [\zxwCol] & [\zxwCol] \zxN{} \rar & \zxN{} \\
+ \zxN{} \rar & \zxZ{} \ar[ur,<'] \ar[dr,<'] & \\
+ & & \zxGround[overlay]{}
+ \end{ZX}
+ with
+ \begin{ZX}
+ & [\zxwCol] & [\zxwCol] \zxN{} \rar & \zxN{} \\
+ \zxN{} \rar & \zxZ{} \ar[ur,<'] \ar[dr,<'] & \\
+ & & \zxGround{}
+ \end{ZX}
+\end{codeexample}
+\end{pgfmanualentry}
+
+\subsubsection{Scalable ZX}
+
+We provide some notations coming from the scalable ZX calculus~\cite{CHP19_SZXcalculusScalableGraphical}.
+
+\begin{pgfmanualentry}
+ \def\extrakeytext{style, }
+ \extractcommand\zxDivider\oarg{picture style}\oarg{picture style}\opt{.}\opt{-}\opt{'}\marg{}\@@
+ \pgfmanualbody
+ Dividers can be used to split (or gather) groups of wires. The |.|,|-|,|'| modifiers are used, respectively, to denote the bottom/right/top versions:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+We provide some pre-defined symbols in both horizontal: %
+\begin{ZX}
+ \zxZ[B]{} \rar[Bn'=n+m, wc] &[\zxwCol] \zxDivider{}
+ \rar[o',Bn'Args={n}{}]
+ \rar[o.,Bn.Args={m}{}] &[\zxWCol] \zxDivider-{} \rar[B,wc] & \zxZ[B]{}
+\end{ZX}
+ and vertical mode:
+\begin{ZX}
+ \zxZ[B]{} \dar[Bn=n+m, wc] \\[\zxwRow]
+ \zxDivider'{} \dar[-o,BnArgs={n}{}] \dar[o-,Bn-Args={m}{}] \\[\zxWRow]
+ \zxDivider.{} \dar[B,wc]\\
+ \zxZ[B]{}
+\end{ZX}
+\end{codeexample}
+}
+\end{pgfmanualentry}
+
+
+\begin{pgfmanualentry}
+ \def\extrakeytext{style, }
+ \extractcommand\zxMatrix\oarg{pic style}\oarg{node style}\opt{.}\opt{-}\opt{'}\opt{/}\opt{*}\opt{\_\{text in pmatrix\}}\marg{matrix name}\@@
+ \pgfmanualbody
+ Matrices are represented using arrows: |matrix name| is the content of the label of the node:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[]
+\begin{ZX}
+ \zxN{} \rar & \zxMatrix{A} \rar & \zxN{}
+\end{ZX}
+\end{codeexample}
+}
+The |*| option is used to reverse the direction of the arrow, typically for the transpose (note how we can give an alias (with |a| in |node style|) to combine with |math baseline|, or its quicker variants |mbr=nb line to center on| to properly vertically align the node):
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+We define %
+$\begin{ZX}[mbr]
+ \zxN{} \rar[B] & \zxMatrix*{A} \rar[B] & \zxN{}
+\end{ZX} \coloneqq
+\begin{ZX}[mbr=2]
+ & [\zxWCol] \zxN{} \ar[B,dr,s] & [\zxWCol] \zxN{} \\[\zxZeroCol+.3mm]
+\ar[B,dr,s] & \zxMatrix{A} \ar[B,u,C] \ar[B,d,C-] & \\
+ & & \zxN{} \\
+\end{ZX}$.
+\end{codeexample}
+}
+The position of the label can be changed with |-| is in horizontal wires, and in vertical wires we use |'| and |.| (putting the label respectively on right and left).
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+\begin{ZX}
+ \zxN{} \rar & \zxMatrix{} \rar & \zxMatrix{A} \rar & \zxMatrix*{A} \rar
+ & \zxMatrix-{A} \rar & \zxMatrix-*{A} \rar & \zxN{}
+\end{ZX}
+\end{codeexample}
+}
+Similarly in horizontal wires:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[]
+\begin{ZX}
+ \zxN{} \dar \\
+ \zxMatrix'{} \dar \\
+ \zxMatrix.{A} \dar \\
+ \zxMatrix'*{A} \dar \\
+ \zxMatrix'{A} \dar \\
+ \zxMatrix.*{A} \dar \\
+ \zxN{}
+\end{ZX}
+\end{codeexample}
+}
+If you want to change the position of the label to a more advanced position (e.g.\ with an angle), the simpler solution is to add |yourAngle:| in front of the label (see tikz labels for more details):
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[]
+\begin{ZX}
+ \zxZ{} \rar & \zxMatrix{45:A} \rar & \zxN{}
+\end{ZX}
+\end{codeexample}
+}
+Note that it might be useful to put the label as an overlay using |/| (i.e. it is not counted in the bounding box of the cell, and might overlap with content around) in order to reduce space if we know there is nothing on the nearby cell: (we can also manually change the row/colum sep with negative values… but it might be better to avoid this kind of manual tweaks):
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[]
+Compare %
+\begin{ZX}
+ \zxZ{} \rar \dar & \zxMatrix-{A} \rar & \zxN{} \\
+ \zxX{}
+\end{ZX} with %
+\begin{ZX}
+ \zxZ{} \rar \dar & \zxMatrix-/{A} \rar & \zxN{} \\
+ \zxX{}
+\end{ZX}
+\end{codeexample}
+}
+It is also useful to put a |pmatrix| inside. While it is possible to write the full |pmatrix|, we can use the |_{}| embelishment to automatically wrap the text with |\begin{bmatrix} \end{bmatrix}|:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+This %
+\begin{ZX}[mbr]
+ \zxN{} \rar & \zxMatrix_{A & B \\ C & D}{} \rar & \zxN{}
+\end{ZX} %
+is a shortcut for %
+\begin{ZX}[math baseline row=1]
+ \zxN{} \rar & \zxMatrix{\begin{bmatrix} A & B \\ C & D \end{bmatrix}} \rar & \zxN{}
+\end{ZX}
+\end{codeexample}
+}
+Note that it seems that some environments do not play well with the way we handle |&| (our changes were needed to make them compatible with |align|, and to provide an easy interface with the |external| library… but it seems to not fit well with all environments, e.g.\ arrays). In that case you should use |\begin{ZXNoExt}| together with |[ampersand replacement=\&]| (of course, use |\&| instead of |&| in the rest of the matrix):
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+$\begin{ZXNoExt}[ampersand replacement=\&]
+ \zxN{} \rar \& \zxMatrix{
+ \begin{bmatrix}
+ \begin{array}{c|c}
+ A & B \\
+ \hline
+ C & D
+ \end{array}
+ \end{bmatrix}} \rar \& \zxN{}
+\end{ZXNoExt}$
+\end{codeexample}
+}
+Here is a demo to check if the true north etc anchors are placed correctly:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+\begin{ZX}
+ \zxH{} \ar[to=Gll,C'] \ar[to=Gll,C.] & \zxMatrix[a=Gll]'{G}
+\end{ZX} %
+\begin{ZX}
+ \zxH{} \ar[to=Gll,C'] \ar[to=Gll,C.] & \zxMatrix[a=Gll]'*{G}
+\end{ZX} %
+\begin{ZX}
+ \zxH{} \ar[to=Gll,C'] \ar[to=Gll,C.] & \zxMatrix[a=Gll].{G}
+\end{ZX} %
+\begin{ZX}
+ \zxH{} \ar[to=Gll,C'] \ar[to=Gll,C.] & \zxMatrix[a=Gll].*{G}
+\end{ZX} %
+\begin{ZX}
+ \zxH{} \ar[to=Gll,C] \ar[to=Gll,C-] \\
+ \zxMatrix[a=Gll]{G}
+\end{ZX} %
+\begin{ZX} %
+ \zxH{} \ar[to=Gll,C] \ar[to=Gll,C-] \\
+ \zxMatrix[a=Gll]*{G}
+\end{ZX} %
+\begin{ZX}
+ \zxH{} \ar[to=Gll,C-] \ar[to=Gll,C] \\
+ \zxMatrix[a=Gll]-{G}
+\end{ZX} %
+\begin{ZX}
+ \zxH{} \ar[to=Gll,C] \ar[to=Gll,C-] \\
+ \zxMatrix[a=Gll]-*{G}
+\end{ZX}
+\end{codeexample}
+}
+
+
+\end{pgfmanualentry}
+
+\begin{pgfmanualentry}
+ \def\extrakeytext{style, }
+ \makeatletter% should not be letter for \@@... strange
+ \extractkey/zx/picCustomStyleMatrixMainNode\@nil%
+ \extractkey/zx/picCustomStyleMatrixLabel\@nil%
+ \extractkey/zx/picCustomStyleBeforeUserMatrix\@nil%
+ \extractkey/zx/picCustomStyleAterUserMatrix\@nil%
+ \extractkey/zx/picCustomStyleLastPicMatrix\@nil%
+ \makeatother
+ \pgfmanualbody
+If you would like to override some settings, note that you can use all customization options provided by our custom node system (\cref{subsec:customNodes}). In particular, you can use |pic style| to change the options of the pic used to draw the node, including scale, rotation…, |node style| to style the parent node of the pic (less used, mostly to give alias names to the shape). We additionally provide special styles to configure the nodes more precisely: |/zx/picCustomStyleMatrixMainNode| and |/zx/picCustomStyleMatrixLabel| to configure more specifically the :
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+\begin{ZX}
+ \zxN{} \rar & \zxMatrix{A} \rar &
+ \zxMatrix[
+ scale=2,
+ /zx/picCustomStyleMatrixMainNode/.style={fill=blue!50},
+ /zx/picCustomStyleMatrixLabel/.style={red}]{A}
+ \rar & \zxN{}
+\end{ZX}
+\end{codeexample}
+}
+You can also set globally the styles like |/zx/picCustomStyleBeforeUserMatrix| (automatically provided, see details in \cref{subsec:customNodes}) to automatically add a style to your picture :
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+\tikzset{
+ /zx/picCustomStyleBeforeUserMatrix/.style={
+ scale=2,
+ /zx/picCustomStyleMatrixMainNode/.style={fill=blue!50},
+ /zx/picCustomStyleMatrixLabel/.style={red,circle,draw,inner sep=1pt},
+ % \zxCustomPicAdditionalPic can be any tikz code to run after the creation of the pic:
+ /utils/exec={\def\zxCustomPicAdditionalPic{%
+ % the main node has empty name, so .center is the center of the main node
+ \node[draw,circle,inner sep=2pt,fill=pink] at (.center) {};%
+ }%
+ },
+ },
+}
+\begin{ZX}
+ \zxZ{} \rar & \zxMatrix{A} \rar & \zxMatrix*{B} \rar & \zxN{}
+\end{ZX}
+\end{codeexample}
+}
+\end{pgfmanualentry}
+
+\subsubsection{Circuit-related}
+
+Since 2023-09-17, we provide a number of options to typeset circuits.
+
+\begin{pgfmanualentry}
+ \def\extrakeytext{style, }
+ \extractcommand\zxBox\opt{\oarg{style}}\marg{box text}\@@
+ \extractcommand\zxGate\opt{\oarg{style}}\marg{box text}\@@
+ \makeatletter
+ \def\extrakeytext{style, }
+ \extractkey/zx/every box=style\@nil%
+ \extractkey/zx/boxes=\marg{style to add}\@nil%
+ \makeatother
+ \pgfmanualbody
+ (both commands are alias) You can add simple gates using |\zxGate{X}| (the content is typeset in math mode by default), possibly adding additional styling to the main box using the optional argument or |/zx/every box/.style={your replacement style}| or |/zx/boxes={your style to add}|:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[]
+\begin{ZX}
+ \zxBox{G} \rar[B] & [\zxwCol] \zxN{} \\
+ \zxBox[fill=green]{G_A} \rar[B] & [\zxwCol] \zxN{}
+\end{ZX}
+\end{codeexample}
+}
+\begin{codeexample}[width=0pt]
+\begin{ZX}[circuit, thick lines]
+ \rar & \zxGate[add label={below:\text{Hadamard}}]{H} \rar &
+\end{ZX}
+\end{codeexample}
+Note that you can also use matrices inside:
+\begin{codeexample}[width=0pt]
+\begin{ZX}[circuit]
+ \rar & \zxGate{
+ \begin{pmatrix}
+ a & b\\
+ c & d
+ \end{pmatrix}
+ } \rar & \zxGate{f} \rar &
+\end{ZX}
+\end{codeexample}
+\end{pgfmanualentry}
+
+\begin{pgfmanualentry}
+ \extractcommand\zxDefaultColumnSepCircuit\@@
+ \extractcommand\zxDefaultRowSepCircuit\@@
+ \makeatletter
+ \def\extrakeytext{style, }
+ \extractkey/zx/defaultEnv/circuit\@nil%
+ \makeatother
+ \pgfmanualbody
+ This style enables the circuit mode, which is simply changing the default spacing between lines and columns. Compare:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[]
+\begin{ZX}
+ \rar & \zxGate{H} \rar & \zxGateMulti{2}{3}{H} & & \rar & \\
+ \rar & \zxGate{H} \rar & & & \rar &
+\end{ZX}
+\end{codeexample}
+}
+with
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[]
+\begin{ZX}[circuit]
+ \rar & \zxGate{H} \rar & \zxGateMulti{2}{3}{H} & & \rar & \\
+ \rar & \zxGate{H} \rar & & & \rar &
+\end{ZX}
+\end{codeexample}
+}
+You can customize the default spacing with |\def\zxDefaultColumnSepCircuit{4mm}| and |\def\zxDefaultRowSepCircuit{4mm}|.
+\end{pgfmanualentry}
+
+\begin{pgfmanualentry}
+ \def\extrakeytext{style, }
+ \extractcommand\zxGateMulti\opt{\oarg{style fit node}}\opt{\oarg{advanced styling}}\marg{number rows}\marg{number columns}\marg{box text}\@@
+ \makeatletter
+ \def\extrakeytext{style, }
+ \extractkey/zx/generic multi/add label=\marg{label}\@nil%
+ \extractkey/zx/generic multi/add label advanced=\marg{style}\marg{label}\@nil%
+ \extractkey/zx/generic multi/content inner nodes=\marg{content inner nodes}\@nil%
+ \extractkey/zx/generic multi/main=\marg{style}\@nil%
+ \extractkey/zx/generic multi/main text=\marg{style}\@nil%
+ \extractkey/zx/generic multi/additional code=\marg{code to add new nodes}\@nil%
+ \extractkey/zx/generic multi/fit content=\opt{\marg{additional row margin}\marg{additional column margin}\marg{minimum height inner nodes}\marg{minimum width inner nodes}}\@nil%
+ \extractkey/zx/generic multi/safe fit\@nil%
+ \makeatother
+ \pgfmanualbody
+ Create a multi-line/row gate:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[]
+\begin{ZX}[circuit]
+ \rar & \zxGate{H} \rar & \zxGateMulti{2}{3}{H} & & \rar & \\
+ \rar & \zxGate{H} \rar & & & \rar &
+\end{ZX}
+\end{codeexample}
+}
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[]
+ \begin{ZX}
+ \rar & \zxBox{H} \rar & \zxGateMulti{1}{3}{H} \dar & & \rar & \zxBox{H} & & \\
+ & & \zxBox{H} \rar & \zxBox{H} & \zxBox{H} & & &
+ \end{ZX}
+\end{codeexample}
+}
+Note that the column will adapt to fit the content if it is too long:
+\begin{codeexample}[]
+\begin{ZX}[circuit]
+ \rar & \zxGateMulti{1}{2}{HHHHHHHHHH} & \rar & \\
+ \zxGate{H} & \zxGate{H} & \zxGate{H} & \zxGate{H} &
+\end{ZX}
+\end{codeexample}
+You can also customize the style of a gate in a simple way using the first argument (the style will only be applied to the fitting box and to the box when computing its dimensions, but not to the content itself that is added in a separate node, see below for more fine-tuned configuration):
+\begin{codeexample}[]
+\begin{ZX}[circuit]
+A & B & C & D & E & & \\
+\zxBox{H} \rar & \zxGateMulti[a=secondGate]{2}{3}{H} & & \rar & \zxBox{X} & & \\
+\zxBox{H} \rar & & & & \zxBox{X} \lar & & \\
+\zxBox{H} \rar \ar[dr,bend right] & \zxBox{H} \rar[to=secondGate] & & & & & \\
+ & \zxGateMulti[,fill=orange!50!white]{1}{2}{H} & &
+\end{ZX}
+\end{codeexample}
+You can also customize its behavior more precisely using the second optional argument using the above listed styles. |main| and |main text| allows you to change the style of the main node and the main text:
+\begin{codeexample}[]
+\begin{ZX}[circuit]
+A & B & C & D & E & & \\
+\zxBox{H} \rar & \zxGateMulti[a=secondGate]{2}{3}{H} & & \rar & \zxBox{X} & & \\
+\zxBox{H} \rar & & & & \zxBox{X} \lar & & \\
+\zxBox{H} \rar \ar[dr,bend right] & \zxBox{H} \rar[to=secondGate] & & & & & \\
+ & \zxGateMulti[][main={fill=orange!50!white}, main text={red}]{1}{2}{H} & &
+\end{ZX}
+\end{codeexample}
+while |additional code| allows you to write arbitrary code after the creation of the main node (|zxMainNode| and |zxMainNodeText| are the alias of the main node and text node):
+\begin{codeexample}[]
+\begin{ZX}[circuit]
+ \zxBox{H} \rar & \zxGateMulti[][
+ main={fill=orange!50!white},
+ main text={red},
+ additional code={
+ \node[
+ circle,
+ inner sep=2pt,
+ fill=red,
+ at={($(zxMainNode.east)+(0mm,1.5mm)$)},
+ zx subnode={redCircle}
+ ]
+ {};
+ }%
+ ]{1}{2}{H} & \rar[start subnode={redCircle}, to=lastH, C-] & \\
+ \zxBox[a=lastH]{H} &
+\end{ZX}
+\end{codeexample}
+
+The |add label| and |add label advanced| allows you to add labels:
+\begin{codeexample}[width=0pt]
+\begin{ZX}[circuit]
+ \rar & \zxGateMulti[add label={Bell \\measurement}]{2}{1}{\zxMeter{}} \rar[classical] & \\
+ \rar & \rar[cl] &
+\end{ZX}
+\end{codeexample}
+Internally, in order to place the matrix, we place a number of inner nodes in the region of the matrix. You can customize them using |content inner nodes| and |style inner nodes|. This can be practical if you want to force the node to take less space for instance (but the content might go outside of the node):
+\begin{codeexample}[width=0pt]
+ \begin{ZX}[circuit]
+ & & & & & & & \\
+ & \zxGate{H} \rar & \zxGateMulti[][
+ content inner nodes={},
+ main={opacity=.5},
+ style inner nodes={
+ red,
+ minimum width=2pt,
+ minimum height=2pt,
+ test/.style={fill=#1,opacity=.7}, test=red
+ }]{2}{3}{HHHH} & & & & & \\
+ & & & & & & &
+ \end{ZX}
+\end{codeexample}
+
+By default, we run |fit content/.default={0mm}{0mm}{\zxBoxMinimumHeight}{\zxBoxMinimumWidth}| which works by evaluating the width of the content, and by automatically setting the size of the inner nodes so that the content fits nicely at the end (it takes the default column sep of the matrix, so it will not see custom adjustment of the column size with |&[1cm]|), with a minimum size. You can also call instead |safe fit| in the second argument, that will just set all inner nodes to be equal to the size of the content (which might not be optimal in term of space). While it is faster and works well with nodes of small size, it gives weird results on large nodes:
+Compare
+\begin{codeexample}[width=0pt]
+\begin{ZX}[circuit]
+ & A & B & C & D & E & & \\
+ & \zxBox{H} \rar & \zxGateMulti{1}{3}{HHHH} & & \rar & \zxBox{H} & & \\
+ & & \zxBox{H} & \zxBox{H} & \zxBox{H} & & & \\
+ & & & & & & & \\
+ & & & & & & & \\
+\end{ZX}
+\end{codeexample}
+with
+\begin{codeexample}[width=0pt]
+\begin{ZX}[circuit]
+ & A & B & C & D & E & & \\
+ & \zxBox{H} \rar & \zxGateMulti[][safe fit]{1}{3}{HHHH} & & \rar & \zxBox{H} & & \\
+ & & \zxBox{H} & \zxBox{H} & \zxBox{H} & & & \\
+ & & & & & & & \\
+ & & & & & & & \\
+\end{ZX}
+\end{codeexample}
+Note that if time is an issue for you, see the section on externalization \cref{sec:externalization}.
+\end{pgfmanualentry}
+
+%{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{pgfmanualentry}
+ \def\extrakeytext{style, }
+ \extractcommand\zxElt\opt{\oarg{style}}\marg{box text}\@@
+ \extractcommand\zxCtrl\opt{\oarg{style}}\marg{}\@@
+ \extractcommand\zxOCtrl\opt{\oarg{style}}\marg{}\@@
+ \extractcommand\zxNot\opt{\oarg{style}}\marg{}\@@
+ \extractcommand\zxCross\opt{\oarg{style}}\marg{}\@@
+ \extractcommand\zxMeter\opt{\oarg{scale}}\marg{}\@@
+ \makeatletter
+ \def\extrakeytext{style, }
+ \extractkey/zx/wires definition/classical\@nil%
+ \extractkey/zx/wires definition/cl\@nil%
+ \extractkey/zx/wires definition/=--\textbar\@nil%
+ \extractkey/zx/wires definition/=\textbar--\@nil%
+ \makeatother
+ \pgfmanualbody
+ |\zxElt| is like |\zxGate| but without any border (useful to add spacing around elements like |\ket{\psi}|, but you might prefer |\zxInput| that does not reserve any space in the matrix for the content and allows an easier align of wires), and the other commands just create the corresponding symbols that you can link together as you want as usual using |\ar| (note that |\zxMeter{}| is node a node but just an icon, so place it yourself inside |\zxGate| or |\zxGateMulti|). The style are wire styles, and are useful to print classical wires (|cl| is an alias for |classical|) and wires bent with a 90 degrees angle. Note that I could not write the right name in the doc, you should remove the equal sign like in \texttt{--\textbar}.
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+\begin{ZX}[circuit]
+ \zxElt{\ket{\psi}} \rar & \zxBox{H} \rar & \zxCtrl{} \dar \rar & \zxCross{} \dar \rar
+ & \zxBox[add label={Measure}]{\zxMeter{}} \ar[dr,classical,--|] \\
+ \ar[r] & \zxOCtrl{} \rar \ar[u] & \zxNot{} \rar & \zxCross{} \ar[rr]
+ & & \zxBox{H} \rar &
+\end{ZX}
+\end{codeexample}
+}
+\end{pgfmanualentry}
+
+\begin{pgfmanualentry}
+ \def\extrakeytext{style, }
+ \extractcommand\zxInput\opt{\oarg{style}}\marg{text}\@@
+ \extractcommand\zxInputMulti\opt{\oarg{style}}\opt{\oarg{label style}}\marg{nb rows}\marg{text}\@@
+ \extractcommand\zxOutput\opt{\oarg{style}}\marg{text}\@@
+ \extractcommand\zxOutputMulti\opt{\oarg{style}}\opt{\oarg{label style}}\marg{nb rows}\marg{text}\@@
+ \extractcommand\zxGateInput\opt{\oarg{style}}\marg{text}\@@
+ \extractcommand\zxGateInputMulti\opt{\oarg{style}}\opt{\oarg{label style}}\marg{nb rows}\marg{text}\@@
+ \extractcommand\zxGateOutput\opt{\oarg{style}}\marg{text}\@@
+ \extractcommand\zxGateOutputMulti\opt{\oarg{style}}\opt{\oarg{label style}}\marg{nb rows}\marg{text}\@@
+ \makeatletter
+ \def\extrakeytext{style, }
+ \extractkey/zx/enlarge brace=\marg{+ or - distance}\@nil%
+ \extractkey/zx/input style=\marg{style}\@nil%
+ \extractkey/zx/output style=\marg{style}\@nil%
+ \extractkey/zx/input multi style=\marg{style}\@nil%
+ \extractkey/zx/output multi style=\marg{style}\@nil%
+ \extractkey/zx/input multi label style=\marg{style}\@nil%
+ \extractkey/zx/output multi label style=\marg{style}\@nil%
+ \extractkey/zx/gate input style=\marg{style}\@nil%
+ \extractkey/zx/gate output style=\marg{style}\@nil%
+ \extractkey/zx/gate input multi style=\marg{style}\@nil%
+ \extractkey/zx/gate output multi style=\marg{style}\@nil%
+ \extractkey/zx/gate input multi label style=\marg{style}\@nil%
+ \extractkey/zx/gate output multi label style=\marg{style}\@nil%
+ \makeatother
+ \pgfmanualbody
+
+Use these functions in order to label the input or outputs of circuits (you can also label any diagram made with this library) or gates (the variant you want to use should be clear from the name. You can customize the arrow and label using the optional arguments or globally using the corresponding style (note that the style for the gate inputs was inspired by the great Quantikz package). The command should be located on the row where the brace should start (either in the cell containing the wire or inside the gate directly):
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[]
+\begin{ZX}[circuit]
+ \rar \zxInputMulti[blue]{2}{\ket{\psi}} & \zxGateMulti{3}{2}{U} \zxGateInputMulti{2}{x}
+ & \rar \zxGateOutputMulti{2}{x \oplus y} & \zxOutputMulti[red][green]{2}{\text{Output}} \\
+ \rar &
+ & \rar & \\
+ \rar \zxInput{\ket{0}} & \zxGateInput{y}
+ & \rar \zxGateOutput{y \oplus 1} & \zxOutput{\ket{1}}
+\end{ZX}
+\end{codeexample}
+}
+
+You can enlarge or reduce the distance of the braces (set by default to |\zxDefaultEnlargeBraceOne| for braces on single wires, and |\zxDefaultEnlargeBraceMulti| for braces on multiple wires) using |enlarge brace|:
+\begin{codeexample}[width=0pt]
+\begin{ZX}
+ \zxBox[a=A]{A} \rar & \zxOutputMulti{1}{\parbox{2.2cm}{\raggedright\tiny
+ This is the default spacing for one multi-output}} \\
+ \zxBox{B} \rar & \zxOutputMulti{2}{\parbox{2.2cm}{\raggedright\tiny
+ This is the default spacing for multiple outputs}} \\
+ \zxBox[a=B]{B} \rar & \\
+ \zxBox[a=A]{A} \rar & \zxOutputMulti[enlarge brace=1mm]{1}{\parbox{2.2cm}{\raggedright\tiny
+ You can increase or decrease the spacing}} \\
+ \zxBox{B} \rar & \zxOutputMulti[enlarge brace=-\zxDefaultEnlargeBraceMulti]{2}{\parbox{2.2cm}{
+ \raggedright\tiny You can increase or decrease the spacing}} \\
+ \zxBox[a=B]{B} \rar & \\
+\end{ZX}
+\end{codeexample}
+
+You can prefix the above commands with |V| (for vertical) when reading from bottom to top (the associated style starts with |vertical|):
+
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+\begin{ZX}[circuit]
+ \dar \zxVOutputMulti{2}{\text{Output}} & \dar & \dar \zxVOutput{\ket{1}} \\
+ \zxGateMulti{2}{3}{U} \zxVGateOutputMulti{2}{x \oplus y} & & \zxVGateOutput{y \oplus 1} \\
+ \dar \zxVGateInputMulti{2}{x} & \dar & \dar \zxVGateInput{y} \\
+ \zxVInputMulti{2}{\ket{\psi}} & & \zxVInput{\ket{0}}
+\end{ZX}
+\end{codeexample}
+}
+
+You can also use |\zxT| (for Top) instead of |\zxV| if you prefer the convention where inputs are located at the top of the diagram):
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+\begin{ZX}[circuit]
+ \dar \zxTInputMulti{2}{\ket{\psi}} & \dar & \dar \zxTInput{\ket{0}} \\
+ \zxGateMulti{2}{3}{U} \zxTGateInputMulti{2}{x} & & \zxTGateInput{y} \\
+ \dar \zxTGateOutputMulti{2}{x\oplus y} & \dar & \dar \zxTGateOutput{y \oplus 1} \\
+ \zxTOutputMulti{2}{\text{Output}} & & \zxTOutput{\ket{1}}
+\end{ZX}
+\end{codeexample}
+}
+Note that these labels are not taken into account when computing the width of the gate box, so you might need to manually adapt their width of the column, for instance by setting the content of an individual cell like:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+\begin{ZX}[circuit]
+ \dar \zxTInputMulti{2}{\ket{\psi}} & \dar & \dar \zxTInput{\ket{0}} \\
+ \zxGateMulti{2}{3}{U} \zxTGateInputMulti{2}{x} & & \zxTGateInput{y} \\
+ \dar \zxTGateOutputMulti{2}{x\oplus y} & \dar
+ %% We replace the cell with a larger cell:
+ & \zxGate[zxTinyFontAndSpacing]{\phantom{y \oplus 1 \oplus x}};
+ %% This is useful or the cell will be replaced by another cell during the fit:
+ \zxMainNodeAlreadySet{} \dar \zxTGateOutput{y \oplus 1 \oplus x} \\
+ \zxTOutputMulti{2}{\text{Output}} & & \zxTOutput{\ket{1}}
+\end{ZX}
+\end{codeexample}
+}
+\end{pgfmanualentry}
+
+\begin{pgfmanualentry}
+ \def\extrakeytext{style, }
+ \extractcommand\zxSlice\opt{\oarg{style label}}\opt{\oarg{style line}}\opt{position percent}\marg{text}\@@
+ \extractcommand\zxVSlice\opt{\oarg{style label}}\opt{\oarg{style line}}\opt{position percent}\marg{text}\@@
+ \makeatletter
+ \def\extrakeytext{style, }
+ \extractkey/zx/slice label style=\marg{style}\@nil%
+ \extractkey/zx/slice line style=\marg{style}\@nil%
+ \extractkey/zx/vertical slice label style=\marg{style}\@nil%
+ \extractkey/zx/vertical slice line style=\marg{style}\@nil%
+ \makeatother
+ \pgfmanualbody
+
+ You can add a slice in your diagram or circuit using |\zxSlice{text}| at the corresponding column:
+\begin{codeexample}[width=0pt]
+ \begin{ZX}[circuit]
+ \rar & \zxGate{X} \zxSlice{1} \rar & \zxGate{Y} \zxSlice{Part\\2} \rar & \zxGate{\zxMeter{}} \\
+ \rar & \zxGate{H} \rar & \zxGate{Y} \rar &
+ \end{ZX}
+\end{codeexample}
+We also provide a style |rotated=angle| to rotate the label (the default angle is 30 degrees):
+\begin{codeexample}[width=0pt]
+\begin{ZX}[circuit]
+ \rar & \zxGate{X} \zxSlice[rotated]{First part} \rar
+ & \zxGate{Y} \zxSlice[rotated]{Second part} \rar & \zxGate{\zxMeter{}} \\
+ \rar & \zxGate{H} \rar & \zxGate{Y} \rar &
+\end{ZX}
+\end{codeexample}
+You can change the position using the 3rd optional argument (default to .5):
+\begin{codeexample}[width=0pt]
+ \begin{ZX}[circuit]
+ \rar & \zxGate{X} \zxSlice[][][.2]{1} \rar & \zxGate{Y} \zxSlice[][][.8]{Part\\2} \rar & \zxGate{\zxMeter{}} \\
+ \rar & \zxGate{H} \rar & \zxGate{Y} \rar &
+ \end{ZX}
+\end{codeexample}
+You can also customize it as you want using the two optional arguments (for the label first and for the line after):
+\begin{codeexample}[width=0pt]
+ \begin{ZX}[circuit]
+ \rar
+ & \zxGate{Y} \rar
+ \zxSlice[rotate=90,anchor=east,pos=1,blue][solid,blue,decorate,decoration={snake}]{Why not \\below?}
+ & \zxGate{\zxMeter{}} \\
+ \rar & \zxGate{H} \rar & \zxGate{Y} \rar &
+\end{ZX}
+\end{codeexample}
+Finally, the |\zxVSlice| version works similarly, but for vertical slices (make sure to insert it \textbf{before} the newline):
+\begin{codeexample}[width=0pt]
+ \begin{ZX}[circuit]
+ \zxElt{\text{Alice}} &[\zxZeroCol] \rar & \zxGate{X} \rar & \zxGate{Y} \rar & \zxGate{\zxMeter{}}
+ \zxVSlice{No communication}\\
+ \zxElt{\text{Bob}} & \rar & \zxGate{H} \rar & \zxGate{Y} \rar &
+ \end{ZX}
+\end{codeexample}
+You can configure it as before, for instance to obtain this fancy effect:
+\begin{codeexample}[width=0pt]
+ \begin{ZX}[circuit]
+ \rar & \zxCtrl{} \rar \dar & \zxGate{Y} \rar & \zxGate{\zxMeter{}}
+ \zxVSlice[][
+ black,
+ double distance=4pt,
+ double,
+ solid,
+ decorate,
+ decoration={snake,segment length=2cm},
+ % Also funny:
+ % decoration={random steps,segment length=.2cm},
+ on layer=foreground
+ ]{Repeat $n$ times}\\[3mm]
+ \rar & \zxCtrl{} \dar \rar & \zxGate{Y} \rar & \zxGate{\zxMeter{}}\\
+ \rar & \zxGate{X} \rar & \zxGate{Y} \rar & \zxGate{\zxMeter{}}
+ \end{ZX}
+\end{codeexample}
+\end{pgfmanualentry}
+
+\begin{pgfmanualentry}
+ \makeatletter
+ \def\extrakeytext{style, }
+ \extractkey/tikz/zx filling style=\marg{your style} (default {fill=white})\@nil%
+ \makeatother
+ \pgfmanualbody
+We can also disable or set any custom filling using this style:
+\begin{codeexample}[width=0pt]
+\begin{ZX}[circuit,/tikz/zx filling style/.style={}]
+ \zxInput{\ket{\psi}} \rar & \zxBox{H} \rar & \zxCtrl{} \dar \rar & \zxCross{} \dar \rar
+ & \zxBox[add label={Measure}]{\zxMeter{}} \ar[dr,classical,--|] \\
+ \ar[r] & \zxOCtrl{} \rar \ar[u] & \zxNot{} \rar & \zxCross{} \ar[rr]
+ & & \zxBox{H} \rar & \zxOutput{\ket{\phi}}
+\end{ZX}
+\end{codeexample}
+\end{pgfmanualentry}
+
+
+\begin{pgfmanualentry}
+ \makeatletter
+ \def\extrakeytext{style, }
+ \extractkey/tikz/every node/block\@nil%
+ \makeatother
+This is useful if you wish to typeset a block that must be wrapped inside a minipage-like environment (actually we use varwidth):
+\begin{codeexample}[width=0pt]
+\begin{ZX}[circuit]
+ \rar & \zxGate[block]{
+ \procedureblock[linenumbering]{$\indcpa_\enc^\adv(\secpar)$}{
+ b \sample \bin\\
+ (\pk,\sk)\sample \kgen(\secparam)
+ }
+ } \rar & \zxGate{f} \rar &
+\end{ZX}
+\end{codeexample}
+\begin{codeexample}[width=0pt]
+\begin{ZX}[circuit, zx column sep=6mm]
+ \rar["k"] & \zxGateMulti[block]{2}{3}{
+ \procedureblock[linenumbering]{$\mathsf{Enc}(k,m)$}{
+ \pclinecomment{This is the standard one-time pad:} \\
+ \pcreturn k \oplus m
+ }
+ } & & \rar["c"] & \zxGate{\mathcal{A}} \rar["\tilde{m}"] & \\
+ \rar["m"]&& & & &
+\end{ZX}
+\end{codeexample}
+\end{pgfmanualentry}
+
+
\subsection{Wires}
\subsubsection{Creating wires and debug mode}
@@ -664,8 +1647,9 @@ Also, if you find your diagram a bit ``too high'', check that you did not forget
\begin{pgfmanualentry}
\extractcommand\arrow\opt{\oarg{options}}\@@
\extractcommand\ar\opt{\oarg{options}}\@@
+ \extractcommand\zxWire\marg{options}\@@
\pgfmanualbody
- These synonym commands (actually coming from |tikz-cd|) are used to draw wires between nodes. We refer to |tikz-cd| for an in-depth documentation, but what is important for our purpose is that the direction of the wires can be specified in the \meta{options} using a string of letters |r| (right), |l| (left), |u| (up), |d| (down). It's also possible to specify a node alias as a source or destination as shown below.
+ These synonym commands (actually coming from |tikz-cd|, except for the last |\zxWire| that is introduced in this library in 2023-10-03 for readability, note that |\zxWire| additionally adds by default a |r| to go right) are used to draw wires between nodes. We refer to |tikz-cd| for an in-depth documentation, but what is important for our purpose is that the direction of the wires can be specified in the \meta{options} using a string of letters |r| (right), |l| (left), |u| (up), |d| (down). It's also possible to specify a node alias as a source or destination as shown below.
\begin{codeexample}[]
\zx{\zxZ{} \ar[r] & \zxX{}} = \zx{\zxX{} \arrow[rd] \\ & \zxZ{}}
\end{codeexample}
@@ -682,6 +1666,13 @@ Also, if you find your diagram a bit ``too high'', check that you did not forget
\end{ZX}
\end{codeexample}
}
+The |\zxWire| can be used as follows:
+\begin{codeexample}[width=0pt]
+\begin{ZX}[circuit, row sep={.6cm,between origins}]
+\zxWire{} & \zxCross{} \zxWire{} \zxWire{d} & \\
+\zxWire{} & \zxCross{} \zxWire{} &
+\end{ZX}
+\end{codeexample}
\end{pgfmanualentry}
As explained in |tikz-cd|, there are further shortened forms:
@@ -775,12 +1766,133 @@ In that setting, it is often useful to enable the debug mode via |\def\zxDebugMo
}
\end{codeexample}
+\begin{pgfmanualentry}
+ \def\extrakeytext{style, }
+ \makeatletter% should not be letter for \@@... strange
+ \extractkey/zx/wires definition/3d above\@nil%
+ \makeatother
+ \pgfmanualbody
+This style is useful to fake a 3D effect to put a wire above another one like \begin{ZX}[]
+ \zxN{} \ar[d,C] \ar[rd,s] & [\zxWCol] \zxN{} \dar[C-] \\[\zxWRow]
+ \zxN{} \ar[ru,s,3d above] & \zxN{}
+\end{ZX} using:
+\begin{codeexample}[width=0pt]
+\begin{ZX}[]
+ \zxN{} \ar[d,C] \ar[rd,s] & [\zxWCol] \zxN{} \dar[C-] \\[\zxWRow]
+ \zxN{} \ar[ru,s,3d above,very thick] & \zxN{}
+\end{ZX}
+\end{codeexample}
+\end{pgfmanualentry}
+
+\begin{pgfmanualentry}
+ \def\extrakeytext{style, }
+ \makeatletter% should not be letter for \@@... strange
+ \extractkey/zx/defaultEnv/thick lines\@nil%
+ \extractkey/tikz/zx thickness wires style=your style\@nil%
+ \makeatother
+When designing circuits, you might prefer a thicker line style, following the style of Quantikz. This is not enabled by default since for ZX diagrams we want to maintain an important difference between this version and the bold version, but you can enable it with |thick lines|, that internally sets the style |zx thickness wires style| to |thick, line cap=round|.
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+Compare \begin{ZX}[circuit, thick lines]
+ \zxInput{\ket{\psi}} \rar & \zxBox{H} \rar & \zxCtrl{} \dar \rar & \zxCross{} \dar \rar
+ & \zxBox[add label={Measure}]{\zxMeter{}} \ar[dr,classical,--|] \\
+ \ar[r] & \zxOCtrl{} \rar \ar[u] & \zxNot{} \rar & \zxCross{} \ar[rr]
+ & & \zxBox{H} \rar & \zxOutput{\ket{\phi}}
+\end{ZX} with \begin{ZX}[circuit]
+ \zxInput{\ket{\psi}} \rar & \zxBox{H} \rar & \zxCtrl{} \dar \rar & \zxCross{} \dar \rar
+ & \zxBox[add label={Measure}]{\zxMeter{}} \ar[dr,classical,--|] \\
+ \ar[r] & \zxOCtrl{} \rar \ar[u] & \zxNot{} \rar & \zxCross{} \ar[rr]
+ & & \zxBox{H} \rar & \zxOutput{\ket{\phi}}
+\end{ZX}
+\end{codeexample}
+}
+\end{pgfmanualentry}
+
\subsubsection{Wire styles (new generation)}
We give now a list of wire styles provided in this library (|/zx/wires definition/| is an automatically loaded style). We recommend using them instead of manual styling to ensure they are the same document-wise, but they can of course be customized to your need. Note that the name of the styles are supposed (ahah, I do my best with what ASCII provides) to graphically represent the action of the style, and some characters are added to precise the shape: typically |'| means top, |.| bottom, |X-| is right to X (or should arrive with angle 0), |-X| is left to X (or should leave with angle zero). These shapes are usually designed to work when the starting node is left most (or above of both nodes have the same column). But they may work both way for some of them.
Note that the first version of that library (which appeared one week before this new version\dots{} hopefully backward compatibility won't be too much of a problem) was using |in=| and |out=| to create these styles. However, it turns out to be not very reliable since the shape of the wire was changing (sometimes importantly) depending on the position of the nodes. This new version should be more reliable, but the older styles are still available by using |IO, nameOfWirestyle| (read more in \cref{subsub:IOwires}).
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{pgfmanualentry}
+ \makeatletter
+ \def\extrakeytext{style, }
+ % not sure how to do it in a cleaner way without manually defining everything
+ \pgfmanualentryheadline{{\ttfamily\declare{/zx/wires definition/|--}}\hfill(style, no default)}%
+ \pgfmanualpdflabel[\catcode`\|=12 ]{|--}{}
+ % the space after \textt is important or we get two different sections
+ % the 2 is just a random char since | does not work (the syntax is "stuff to group@actual text to print" as
+ % I understand)
+ \index{zx@\texttt {/zx/}!wires definition@\texttt {wires definition/}!2--@\texttt {\protect\pgfmanualbar--}}
+ \pgfmanualentryheadline{{\ttfamily\declare{/zx/wires definition/--|}}\hfill(style, no default)}%
+ \pgfmanualpdflabel[\catcode`\|=12 ]{--|}{}
+ % the space after \textt is important or we get two different sections
+ % the 2 is just a random char since | does not work (the syntax is "stuff to group@actual text to print" as
+ % I understand)
+ \index{zx@\texttt {/zx/}!wires definition@\texttt {wires definition/}!--2@\texttt {--\protect\pgfmanualbar}}
+ \makeatother
+ \pgfmanualbody
+ This gives a wire bent with a 90 degrees angle (respectively starting horizontally then vertically, or first vertically then horizontally).
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+\begin{ZX}[circuit]
+ \zxElt{\ket{\psi}} \rar & \zxBox{H} \rar & \zxCtrl{} \dar \rar & \zxCross{} \dar \rar
+ & \zxBox[add label={Measure}]{\zxMeter{}} \ar[dr,classical,--|] \\
+ \ar[r] & \zxOCtrl{} \rar \ar[u] & \zxNot{} \rar & \zxCross{} \ar[rr]
+ & & \zxBox{H} \rar &
+\end{ZX}
+\end{codeexample}
+}
+\end{pgfmanualentry}
+}
+
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+ % I can't find a cleaner solution than manually calling pdflabel, pgfmanualentryheadline etc due to the |
+ % character
+\begin{pgfmanualentry}
+ \makeatletter
+ \def\extrakeytext{style, }\catcode`\|=12
+ \pgfmanualentryheadline{{\ttfamily\declare{/zx/wires definition/horizontal |--}}\hfill(style, no default)}%
+ \pgfmanualpdflabel[\catcode`\|=12 ]{horizontal |--}{}
+ % the space after \textt is important or we get two different sections
+ % the 2 is just a random char since | does not work (the syntax is "stuff to group@actual text to print" as
+ % I understand)
+ \index{zx@\texttt {/zx/}!wires definition@\texttt {wires definition/}!horizontal 2--@\texttt {horizontal \protect\pgfmanualbar--}}
+ \pgfmanualentryheadline{{\ttfamily\declare{/zx/wires definition/horizontal --|}}\hfill(style, no default)}%
+ \pgfmanualpdflabel[\catcode`\|=12 ]{horizontal --|}{}
+ \index{zx@\texttt {/zx/}!wires definition@\texttt {wires definition/}!horizontal --2@\texttt {horizontal --\protect\pgfmanualbar}}
+ \pgfmanualentryheadline{{\ttfamily\declare{/zx/wires definition/vertical |--}}\hfill(style, no default)}%
+ \pgfmanualpdflabel[\catcode`\|=12 ]{vertical |--}{}
+ % the space after \textt is important or we get two different sections
+ % the 2 is just a random char since | does not work (the syntax is "stuff to group@actual text to print" as
+ % I understand)
+ \index{zx@\texttt {/zx/}!wires definition@\texttt {wires definition/}!vertical 2--@\texttt {vertical \protect\pgfmanualbar--}}
+ \pgfmanualentryheadline{{\ttfamily\declare{/zx/wires definition/vertical --|}}\hfill(style, no default)}%
+ \pgfmanualpdflabel[\catcode`\|=12 ]{vertical --|}{}
+ \index{zx@\texttt {/zx/}!wires definition@\texttt {wires definition/}!vertical --2@\texttt {vertical --\protect\pgfmanualbar}}
+ \makeatother
+ \pgfmanualbody
+Like \texttt{--\textbar} \texttt{\textbar--} except that it only keeps the horizontal/vertical part. This is mostly useful when you want an horizontal/vertical wire starting/ending at a point without having to bother about shifting the other point to maintain horizontality:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+\begin{ZX}
+ \rar[horizontal |--, end subnode=A] \rar[horizontal |--, end subnode=B] &
+ \node[circle,fill=blue,zx subnode=A,yshift=2mm]{a}; \node[circle,fill=green,zx subnode=B,yshift=-2mm]{b};
+ \rar[horizontal --|, start subnode=A] \rar[horizontal --|, start subnode=B] &
+\end{ZX} and %
+\begin{ZX}
+ \dar[vertical --|, end subnode=A]
+ \dar[vertical --|, end subnode=B] \\
+ \node[circle,fill=blue,zx subnode=A,xshift=-2mm]{a};
+ \node[circle,fill=green,zx subnode=B,xshift=2mm]{b};
+ \dar[vertical |--, start subnode=A] \dar[vertical |--, start subnode=B] \\
+\end{ZX}
+\end{codeexample}
+}
+\end{pgfmanualentry}
+}
+
\begin{pgfmanualentry}
\makeatletter
\def\extrakeytext{style, }
@@ -827,6 +1939,26 @@ The \meta{radius ratio} parameter can be used to turn the circle into an ellipse
\zxZ{} \ar[r,C.=2] & \zxX{}
\end{ZX}.
\end{codeexample}
+
+Note that you can customize like for other nodes the direction of the wire using something like |\ar[d, C, end anchor=south]| or |\ar[d, C, end subnode=mySubnode]|. For more advanced users, you can create your own gates and specify directly inside the gate where the |C|-like shapes should connect to. The algorithm followed is:
+\begin{itemize}
+\item First, it tries to connect to the center of a |true west|, |true east|, |true north|, |true south| subnode (depending on the variation of |C|).
+\item Then, it tries to connect to a |true west|, |true east|, |true north|, |true south| \textbf{anchor}
+\item Otherwise, it falls back to the |west|, |east|, |north|, |south| anchors.
+\end{itemize}
+
+\begin{codeexample}[width=0pt]
+\NewExpandableDocumentCommand{\myWeirdGate}{}{
+ \zxBox[a=foo]{D}
+ \node[circle,fill=green,zx subnode=true west,inner sep=2pt,at=(foo.south west)]{};
+}
+
+\begin{ZX}
+ A \dar[C] \\
+ \myWeirdGate
+\end{ZX}
+\end{codeexample}
+
\end{pgfmanualentry}
@@ -906,7 +2038,7 @@ When the nodes are too far appart, the default angle of |30| may produce strange
\extractkey/zx/wires definition/no fake center\@nil%
\makeatother
\pgfmanualbody
- Usually each wire should properly use these functions, so the end user should not need that too often (during a first reading, you can skip this paragraph). We added 4 anchors to nodes: |fake center north|, |fake center south|, |fake center east| and |fake center west|. These anchors are used to determine the starting point of the wires depending on the direction of the wire (I tried to use more complex methods to ensure the wires would start on the boundary, but \mylink{https://tex.stackexchange.com/questions/619274}{they all fail}). Because some nodes may not have these anchors, we can't directly set |start anchor=fake center north, on layer=edgelayer| (but the user can do that if they are using only nodes with these anchors) or the code may fail on some nodes. For that reason, we check that these anchors exist while drawing our wires (which, at the best of my knowledge, can only be done while drawing the path). The |start/end fake center *| code is responsible to configure that properly (|start real center| will use the real center), and |left to right| (and similar) just configure both the |start| and |end| point to ensure the node starts at the appropriate anchor. However this won't work for style not defined in this library: in case you are sure that these anchors exists and want to use your own wire styles, you can then set the anchors manually and use |on layer=edgelayer|, or use |force left to right| (and similar) which will automatically do that for the |start| and |end| points.
+ Usually each wire should properly use these functions, so the end user should not need that too often (during a first reading, you can skip this paragraph). We added 4 anchors to nodes: |fake center north|, |fake center south|, |fake center east| and |fake center west|. These anchors are used to determine the starting point of the wires depending on the direction of the wire. Because some nodes may not have these anchors, we can't directly set |start anchor=fake center north, on layer=edgelayer| (but the user can do that if they are using only nodes with these anchors) or the code may fail on some nodes. For that reason, we check that these anchors exist while drawing our wires (which, at the best of my knowledge, can only be done while drawing the path). The |start/end fake center *| code is responsible to configure that properly (|start real center| will use the real center), and |left to right| (and similar) just configure both the |start| and |end| point to ensure the node starts at the appropriate anchor. However this won't work for style not defined in this library: in case you are sure that these anchors exists and want to use your own wire styles, you can then set the anchors manually and use |on layer=edgelayer|, or use |force left to right| (and similar) which will automatically do that for the |start| and |end| points.
\begin{codeexample}[]
\begin{ZX}
\zxX{\alpha+\beta} \ar[r,o',no fake center] & \zxZ{\alpha+\beta}\\
@@ -977,7 +2109,7 @@ When the nodes are too far appart, the default angle of |30| may produce strange
\extractkey/zx/wires definition/S.-=-andL config (default \{defaultS',default-S,symmetry\})\@nil%
\makeatother
\pgfmanualbody
- |s| and |S| are used to create a s-like wire, to have nicer diagonal lines between nodes. Other versions are soften versions (the input and output angles are not as sharp. Adding |'| or |.| specifies if the wire is going up-right or down-right, however as of today if it mostly used for backward compatibility since, for instance, |-s'| is the same as |-s| (but some styles may want to do a difference later). The only exception is for |s|/|s'|/|s.|: |s| has a sharper output angle than |s'| and |s.| (which are both equals).
+ |s| and |S| are used to create a s-like wire (|s| is smoother than |S| that arrives and leave horizontally), to have nicer diagonal lines between nodes. Other versions are soften versions (the input and output angles are not as sharp. Adding |'| or |.| specifies if the wire is going up-right or down-right, however as of today if it mostly used for backward compatibility since, for instance, |-s'| is the same as |-s| (but some styles may want to do a difference later). The only exception is for |s|/|s'|/|s.|: |s| has a sharper output angle than |s'| and |s.| (which are both equals).
\begin{codeexample}[width=3cm]
\begin{ZX}
\zxX{\alpha} \ar[s,rd] \\
@@ -1317,6 +2449,20 @@ Note that it's possible to automatically start wires on the border of the node,
\makeatother
\pgfmanualbody
To create a bezier wire. These styles are not really meant to be used for the final user because they are long to type and would not be changed document-wise when the style is changed, but most styles are based on these styles. For the |bezier 4 *| versions, the two first arguments are the relative position of the first anchor (|x| and |y| position), the next two of the second anchor. In the |bezier *| versions, the value of |1-| will be the relative |x| position of the first point, |1L| the relative position of the second, and |2-| and |2L| will be for the second point (the advantage of this is that it is also possible to specify angles using |1al={angle}{length}|\dots{} as explained in the |-andL| syle). They are said to be relative in the sense that |{0}{0}| is the coordinate of the first point, and |{1}{1}| the second point. The |bezier x| and |bezier 4 y| are useful when the node are supposed to be horizontally or vertically aligned: the distance are now expressed as a fraction of the horizontal (respectively vertical) distance between the two nodes. Using relative coordinates has the advantage that if the nodes positions are moved, the aspect of the wire does not change (it is just squeezed), while this is not true with |in|/|out| wires which preserves angles but not shapes.
+Note that all arrows that are based on the |bezier| style (most of the keys: |o|-like, |N|-like, |<|-like, |s|-like) can try to connect to subnodes or anchors called |fake center {east/north/west/south}| in order to start the wire in between the real center and an |east/...| coordinate (note that some variations can use another anchor, for instance |<'| will set the end anchor to |west| by default). Since adding manually an anchor to a node can be quite tedious, it is often easier to create a subnode, using either |zx subnode=name of subnode| or |\zxCoordinateSubnode{name of subnode}|. For instance, we show how to create a node such that bezier arriving from right will be connected to the south east part of the node while bezier leaving from the left will start at the north east anchor:
+\begin{codeexample}[width=0pt]
+\NewExpandableDocumentCommand{\myWeirdNode}{m}{%
+ \node[zx main node,alias=tmp,fill=pink,rounded corners,inner sep=2pt]{A};
+ % will be used by bezier curves to know how to connect:
+ \zxCoordinateSubnode[at={(tmp.north east)}]{fake center east}
+ \zxCoordinateSubnode[at={(tmp.south west)}]{fake center west}
+}
+
+\begin{ZX}
+ \myWeirdNode{A} \ar[rd, s] \ar[C,dr] & & \myWeirdNode{B} \\
+ & \zxZ{a \oplus b \oplus c \oplus d} \ar[ru, s] &
+\end{ZX}
+\end{codeexample}
\end{pgfmanualentry}
@@ -1402,7 +2548,7 @@ Note that the |IO| version cannot really be used when nodes are not aligned (usi
Normal \begin{ZX}
\zxX{\alpha} \ar[dr,C]\\
& \zxNone{}
- \end{ZX}, and |IO| \begin{ZX}
+ \end{ZX}, and IO \begin{ZX}
\zxX{\alpha} \ar[dr,IO,C]\\
& \zxNone{}
\end{ZX}
@@ -1638,6 +2784,928 @@ A swapped Bell pair is %
\end{codeexample}
\end{pgfmanualentry}
+\begin{pgfmanualentry}
+ \makeatletter
+ \def\extrakeytext{style, }
+ \extractkey/zx/wires definition/bold\@nil%
+ \extractkey/zx/wires definition/B\@nil%
+ \extractkey/zx/wires definition/non bold\@nil%
+ \extractkey/zx/wires definition/NB\@nil%
+ \extractkey/zx/wires definition/boldn\@nil%
+ \extractkey/zx/wires definition/boldn-\@nil%
+ \extractkey/zx/wires definition/boldn'\@nil%
+ \extractkey/zx/wires definition/boldn.\@nil%
+ \extractkey/zx/wires definition/Bn=message (default n)\@nil%
+ \extractkey/zx/wires definition/Bn-=message (default n)\@nil%
+ \extractkey/zx/wires definition/Bn'=message (default n)\@nil%
+ \extractkey/zx/wires definition/Bn.=message (default n)\@nil%
+ \extractkey/zx/wires definition/BnArgs=\{message\}\{style\} (default \{n\}\{\})\@nil%
+ \extractkey/zx/wires definition/Bn-Args=\{message\}\{style\} (default \{n\}\{\})\@nil%
+ \extractkey/zx/wires definition/Bn'Args=\{message\}\{style\} (default \{n\}\{\})\@nil%
+ \extractkey/zx/wires definition/Bn.Args=\{message\}\{style\} (default \{n\}\{\})\@nil%
+ \makeatother
+ \pgfmanualbody
+ Creates a bold (or non-bold) wire (|B| and |NB| being short aliases). The versions with a |n| at the end adds a $n$ on the right/left/above/below (for the respective symbols empty, |-|, |'|, |.|), that you can overwrite by providing an option:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+\begin{ZX}
+ \zxX[bold]{} \rar[Bn',o'] \rar[Bn.=m,o.] &[\zxwCol] \zxZ{} \rar &[\zxwCol] \zxN{}
+\end{ZX}
+\end{codeexample}
+}
+Finally, the last variations with args like |BnArgs| allows you to provide an additional label style, notably arguments like |pos=.7| to change the position of the line in the path (when the lines are drawn from the middle of the nodes, which is the case for many styles by default for efficiency reasons, the middle of the path may appear poorly centered: using |pos| is one method to center it back, see also \cref{subsec:wiresInsideOutside}).
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+\begin{ZX}
+ \zxX[bold]{} \rar[<.,Bn.Args={n}{pos=.6},dr] &[\zxwCol] \\
+ & \zxN{}
+\end{ZX}
+\end{codeexample}
+}
+Note that |bold| and its alias |B| can also be used as an argument to the |ZX| environment to turn all spiders and wires in bold:
+\begin{codeexample}[width=0pt]
+\begin{ZX}[bold]
+ \zxX{} \rar[o'] \rar[o.] & \zxZ{} \rar &[\zxwCol] \zxN{}
+\end{ZX}
+\end{codeexample}
+You might also want to combine it with the |non bold| option to temporarily set a wire non-bold:
+\begin{codeexample}[width=0pt]
+\begin{ZX}[bold]
+ \zxX{} \rar[o'] \rar[o.] & \zxZ{} \rar[non bold] &[\zxwCol] \zxN{}
+\end{ZX}
+\end{codeexample}
+\end{pgfmanualentry}
+
+\begin{pgfmanualentry}
+ \makeatletter
+ \def\extrakeytext{style, }
+ \extractkey/zx/styles/rounded style/wires bold\@nil%
+ \extractkey/zx/styles/rounded style/Bw\@nil%
+ \extractkey/zx/styles/rounded style/BBw\@nil%
+ \makeatother
+ \pgfmanualbody
+ If you set |wires bold| (alias |Bw|) to a node, all wired connected to that node will be bold. |BBw| additionally turn the current node bold.
+\begin{codeexample}[width=0pt]
+\begin{ZX}
+ \zxX{} \rar[o'] \rar[o.] & \zxZ[BBw]{} \rar &[\zxwCol] \zxN{}
+\end{ZX}
+\end{codeexample}
+\end{pgfmanualentry}
+
+
+\subsection{Custom nodes}\label{subsec:customNodes}
+
+\textbf{NB}: a number of functionalities needed in this section were added on 24/02/2023 and 03/10/2023, so be sure to have the latest version.
+
+\subsubsection{Creating your own node: method 1}
+
+Technically, you can create any tikz style to create custom nodes like:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+ \begin{ZX}
+ \zxN{} \rar & |[draw,fill=blue!50,draw=blue,inner sep=3mm]| \text{my custom node}
+ \end{ZX}
+\end{codeexample}
+}
+possibly using |\tikzset| and/or |\NewExpandableDocumentCommand| to avoid repetitions:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+ \tikzset{
+ my custom node/.style={
+ draw,fill=blue!50,draw=blue,inner sep=3mm
+ },
+ }
+ \NewExpandableDocumentCommand{\myCustomNode}{m}{|[my custom node]| \text{#1}}
+ \begin{ZX}
+ \zxN{} \rar & \myCustomNode{Hey}
+ \end{ZX}
+\end{codeexample}
+}
+
+\begin{pgfmanualentry}
+ \def\extrakeytext{style, }
+ \extractcommand\zxCoordinateSubnode\opt{\oarg{style}}\marg{name of subnode}\@@
+ \extractcommand\zxCoordinateMain\opt{\oarg{style}}\marg{}\@@
+ \makeatletter% should not be letter for \@@... strange
+ \extractkey/tikz/zx main node\@nil%
+ \extractkey/tikz/zx subnode=\marg{name of subnode}\@nil%
+ \extractkey/tikz/zx at origin\@nil%
+ \extractkey/tikz/start subnode=\marg{name of subnode}\@nil%
+ \extractkey/tikz/end subnode=\marg{name of subnode}\@nil%
+ \makeatother
+ \pgfmanualbody%
+
+However, we recommend users to use the |\node[zx main node,zx at origin, ...]{...};| syntax rather than:
+\begin{verbatim}
+|[...]| ...
+\end{verbatim}
+for multiple reasons: first, it will be more robust (for instance you need the |\node| syntax if you plan to insert this in |zxExecuteAtEndPicture| or in a regular tikz picture which is not contained in a matrix), but you also have more freedom since you can create nodes having multiples subnodes, anchors etc.
+You should note the |zx main node| that is needed to give a name to the current node so that |\arrow| can find it, otherwise you will get an error saying that the node does not exists when you try to link to it, and |zx at origin| that will just do |at={(0,0)}| (which is the default position anyway) but that might be useful later in order to easily place a node outside of a matrix. We also provide |\zxCoordinateMain| as the equivalent of |zx main node| for coordinates since they would not accept a name via a style.
+
+Subnodes are a kind of generalization of anchors: you can define an existing node as a subnode with |zx subnode=your subnode| and link from/to this node using |start subnode=your subnode| and |end subnode=your subnode|:
+
+\begin{codeexample}[width=0pt]
+\NewExpandableDocumentCommand{\zxMyDoubleNode}{O{}m}{
+ \node[fill=blue!20, zx main node, inner sep=3mm,alias=zxtmp,#1] {\text{#2}};
+ \node[circle,fill=red!70, inner sep=.8mm,zx subnode=redNode] at ([shift={(0mm,1.5mm)}]zxtmp.west) {};
+ \node[circle,fill=orange!70, inner sep=.8mm,zx subnode=orangeNode] at ([shift={(0mm,-1.5mm)}]zxtmp.west) {};
+ \node[circle,fill=green!70, inner sep=.8mm,zx subnode=greenNode] at ([shift={(0mm,-1.5mm)}]zxtmp.east) {};
+}
+\begin{ZX}
+ A \rar[end subnode=redNode] \rar[end subnode=orangeNode]
+ & [5mm] \zxMyDoubleNode{Hey} \dar \rar[start subnode=greenNode,end subnode=orangeNode]
+ & \zxMyDoubleNode[fill=pink]{Hey}\\
+ B \ar[ru, end subnode=orangeNode] &
+\end{ZX}
+\end{codeexample}
+Node that you can also set some special subnodes called |fake center {north,south,east,west}| in order to help bezier-based wires to find where to start, and |true {north,south,east,west}| to say to |C| where to start (see the corresponding section for more details). Since we often want to specify coordinates here to be precise, you can use |\zxCoordinateSubnode| to place the coordinate at the right place.
+\end{pgfmanualentry}
+
+
+\subsubsection{Method 2: using pic}
+
+We also provide a second approach to create custom nodes (the syntax is actually very close) based on |pic|. This has pro and cons compared to the above approach: it is a bit more complicated and involve more dark magic under the hood, but only creates a single node, provides reusable styles that might be easier to integrate in a tikz picture, and we also provide some automatic way to deal with rotations, scaling etc... Historically, this was created before we realized that cells could contain multiple nodes and that it was possible to use subnodes to anchors, but now that subnodes have been introduced both approaches are relatively close. Nonetheless, all tricks introduced here can be used with the first method, except that anchors should be replaced with subnodes.
+
+\begin{pgfmanualentry}
+ \def\extrakeytext{style, }
+ \extractcommand\zxNewNodeFromPic\marg{name new node}\oarg{style before user}\oarg{style after user}\marg{code}\@@
+ \makeatletter% should not be letter for \@@... strange
+ \extractkey/tikz/zx create anchors=\marg{list, of, coordinates, to, turn, in, anchor}\@nil%
+ \extractkey/tikz/invert top bottom\@nil%
+ \extractkey/tikz/start subnode=\marg{name of subnode}\@nil%
+ \extractkey/tikz/stop subnode=\marg{name of subnode}\@nil%
+ \makeatother
+ \pgfmanualbody
+ |\zxNewNodeFromPic{Name}[style before][style after]{code}| is used to create a new command with name |\zxName|. |code| is the code to draw the node (that you would use in a |\pic| environment, and that will be centered on |(0,0)|):
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+ \zxNewNodeFromPic{MyNode}{
+ \node[draw,fill=blue!50,draw=blue,inner sep=3mm, zx main node, alias=mynode] at (0,0) {};
+ \node[draw,fill=red!50,draw=blue,inner sep=1mm] at (mynode.north east) {};
+ }
+ \begin{ZX}
+ \zxN{} \rar & \zxMyNode{} \rar & \zxMyNode{}
+ \end{ZX}
+\end{codeexample}
+}
+Note how giving |zx main node| to a node makes it the target of arrows (note that you should make sure that your picture has at least one main node if you want features like |debug mode| to work). Without this, the lines would go to the coordinate |(0,0)|, and go through all the nodes:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+ \zxNewNodeFromPic{MyNode}{
+ \node[draw,fill=blue!50,draw=blue,inner sep=3mm, alias=mynode] at (0,0) {};
+ \node[draw,fill=red!50,draw=blue,inner sep=1mm] at (mynode.north east) {};
+ }
+ \begin{ZX}
+ \zxN{} \rar & \zxMyNode{}
+ \end{ZX}
+\end{codeexample}
+}
+Note that sometimes, one might want to draw lines to a fixed point, while leaving the line below the object (for instance if you use a |rounded corners| option and try to enter by the corner, tikz will actually stop before which is not beautiful). A simple solution is to use |wc| (short for |wire centered|) on the arrow, and it will automatically move the path on a layer behind (see also |wcs| and |wce| to configure only the starting or ending points, and some other nodes also use this, notably most styles based on |bezier|, like |s|):
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+\zxNewNodeFromPic{MyDivider}{
+ \node[regular polygon, regular polygon sides=3, shape border rotate=90,
+ draw=black,fill=gray!50, inner sep=1.6pt, rounded corners=0.8mm,zx main node] {};
+}
+Compare %
+\begin{ZX}
+ \zxZ{} \rar[very thick] &\zxMyDivider{} \rar[very thick] & \zxN{}
+\end{ZX} %
+and %
+\begin{ZX}
+ \zxZ{} \rar[very thick,wce] &\zxMyDivider{} \rar[very thick] & \zxN{}
+\end{ZX}
+\end{codeexample}
+}
+Note that I'm working on a better solutions to move nodes on different layers, or automatically see which anchor to choose depending on the custom node… but it's not that \mylink{https://tex.stackexchange.com/questions/618823/node-on-layer-style-in-tikz-matrix-tikzcd}{easy}.
+
+We can similarly put the |zx main node| on the other node to point to the other node by default:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+ \zxNewNodeFromPic{MyNode}{
+ \node[draw,fill=blue!50,draw=blue,inner sep=3mm, alias=mynode] at (0,0) {};
+ \node[draw,fill=red!50,draw=blue,inner sep=1mm, zx main node] at (mynode.north east) {};
+ }
+ \begin{ZX}
+ A \rar[end anchor=center,on layer=main] & \zxMyNode{} \rar & B & \zxMyNode{} & \zxMyNode{}
+ \end{ZX}
+\end{codeexample}
+}
+
+\paragraph{Add margin around nodes.} You might want to add empty paths to increase the ``margin'' around your picture, or |overlay| some nodes if you don't want them to be counted when computing the bounding box. For simplicity, we provide a command |\zxExtendBoundingBox| that extends the current bounding box. This command takes as argument a list of arguments like |left|, |right|, |top|, |bottom|, |horizontal|, |vertical|, |extend|, where each argument takes a distance and extends to the corresponding direction (|extend| extends in all directions). For instance, below we increase the box by 1cm horizontally and by 3mm on each side on the y axis:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+ \zxNewNodeFromPic{MyNode}{
+ \node[draw,fill=blue!50,draw=blue,inner sep=3mm, zx main node] at (0,0) {};
+ \zxExtendBoundingBox{horizontal=1cm, vertical=3mm}
+ }
+ \begin{ZX}
+ A \rar & \zxMyNode{} \rar & B\\
+ \end{ZX}
+\end{codeexample}
+}
+
+\paragraph{Give text as argument.} It is also possible to pass text as an argument by simply adding |\tikzpictext| where you want the text to appear, and calling then |\zxMyNode{your text}|:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+ \zxNewNodeFromPic{MyNode}{
+ \node[draw,fill=blue!50,draw=blue,inner sep=3mm, zx main node, alias=mynode] at (0,0) {\tikzpictext};
+ \node[draw,fill=red!50,draw=blue,inner sep=1mm] at (mynode.north east) {};
+ }
+ \begin{ZX}
+ \zxMyNode{Hello} & \zxMyNode{do you see} & \zxMyNode{the text} & ?
+ \end{ZX}
+\end{codeexample}
+}
+
+\paragraph{Pass arbitrary arguments.} You can actually pass virtually any argument(s) by using the optional argument of the created |\zxMyNode| (that is just an additional argument to the pic options, inserted before \emph{style after user}, but after \emph{style before user} that we can use to create additional arguments with default values using the tikz/pgf power):
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+% Requires \usetikzlibrary {shapes.geometric} for the star shape
+\zxNewNodeFromPic{MyStar}[
+ nb spikes/.store in=\myNbSides, % When users type nb spikes=42, this puts 42 into \myNbSides
+ nb spikes=5, % <- Default value
+]{
+ \node[star, star points=\myNbSides, minimum size=6mm, draw, fill=red] at (0,0) {};
+}
+\begin{ZX}
+ \text{Default:} & \zxMyStar{} & \text{More !} & \zxMyStar[nb spikes=8]{} & \zxMyStar[nb spikes=12]{}
+\end{ZX}
+\end{codeexample}
+}
+
+\paragraph{Overriding existing parameters.}
+
+You might want to override a custom node, for instance because this custom node was provided by an external library (e.g.\ the ground and scalable ZX symbols are made using custom-nodes, and you might want to customize them). We provide for that a series of styles: if |XXXX| is the name on the node (e.g.\ |Ground|), the |/zx/picCustomStyleBeforeUserXXXX| style is sent to the picture style before loading the options of the user, |/zx/picCustomStyleAfterUserXXXX| is loaded after the input of the user, |/zx/picCustomStyleLastPicXXXX| is loaded as the last argument to the picture (after the default style). You can also set the command |\zxCustomPicAdditionalPic| to any code to draw at the end of the picture:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+\tikzset{
+ /zx/picCustomStyleBeforeUserMatrix/.style={
+ scale=2,
+ % \zxCustomPicAdditionalPic can be any tikz code to run after the creation of the pic:
+ /utils/exec={\def\zxCustomPicAdditionalPic{%
+ % the main node has empty name, so .center is the center of the main node
+ \node[draw,circle,inner sep=2pt,fill=pink] at (.center) {};%
+ }%
+ },
+ },
+}
+\begin{ZX}
+ \zxZ{} \rar & \zxMatrix{A} \rar & \zxMatrix*{B} \rar & \zxN{}
+\end{ZX}
+\end{codeexample}
+}
+
+When designing your own custom nodes, you can also put:\\
+|NameOfYourStyle/.append style={}, NameOfYourStyle,|\\
+where you want to allow users to load |NameOfYourStyle| (|NameOfYourStyle/.append style={}| is used to create the style if it does not exist).
+
+If you want to change a create a new node style without overriding a style, you can of course create your own command that sets the parameters for you:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+\tikzset{
+ /zx/picCustomStyleBeforeUserMatrix/.style={
+ scale=2,
+ % \zxCustomPicAdditionalPic can be any tikz code to run after the creation of the pic:
+ /utils/exec={\def\zxCustomPicAdditionalPic{%
+ % the main node has empty name, so .center is the center of the main node
+ \node[draw,circle,inner sep=2pt,fill=pink] at (.center) {};%
+ }%
+ },
+ },
+}
+\begin{ZX}
+ \zxZ{} \rar & \zxMatrix{A} \rar & \zxMatrix*{B} \rar & \zxN{}
+\end{ZX}
+\end{codeexample}
+}
+
+\paragraph{Local style.}
+
+Sometimes, you might want to define styles that are available only locally: for instance, you might prefer to type |main={fill=green}| instead of:\\
+|/zx/picCustomStyleBoxMainNode/.append style={fill=green}|\\
+Nothing prevents you from doing so directly in the default style. Just, make sure to use, e.g.\ |####1|, if you want to call an argument (internally we use nested styles and functions):
+
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+\zxNewNodeFromPic{MyBox}[
+ main/.style={
+ /zx/picCustomStyleMyBoxMainNode/.append style={####1},
+ },
+]{%
+ \node[draw, inner sep=1.3mm, rectangle, zx main node, execute at begin node=$, execute at end node=$,
+ /zx/picCustomStyleMyBoxMainNode/.append style={}, % Make sure it exists to avoid errors
+ /zx/picCustomStyleMyBoxMainNode,
+ ]{\tikzpictext};%
+}
+
+\begin{ZX}
+ \zxMyBox{G} \rar[B] & [\zxwCol] \zxN{}\\
+ \zxMyBox[main={fill=green}]{G} \rar[B] & [\zxwCol] \zxN{}
+\end{ZX}
+\end{codeexample}
+}
+
+\paragraph{Rotations.} Note that often, we want to rotate the nodes. The automatically generated macro to add new nodes comes with multiple flavors by adding the usual symbols |-|,|'|,|.|: by default, |\myNode-| will ``rotate'' by 180 degrees the pic, |\myNode'| will rotate it by 270 degrees to fake a node put ``above'', and |\myNode.| will rotate it by 90 degrees to fake a node put below. Importantly, by default tikz rotates/scales the coordinates, but \textbf{not the nodes or text}, so you might want to specify \textbf{transform shape} on each node you want to rotate and scale according to the parent transform, or using the |every node/.append style={transform shape}| (\textbf{WARNING}: make sure to use |append| or otherwise |zx main node| you not work and you will not be able to give a name to a node) option to apply it on all nodes:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+ \zxNewNodeFromPic{MyTriangle}[
+ % To also rotate/scale the node, otherwise only it's coordinate is rotated
+ every node/.append style={transform shape},
+ % Just to show how to quickly scale a node by default, to quickly update the size of a whole picture:
+ scale=1.3
+ ]{
+ \node[regular polygon, regular polygon sides=3, shape border rotate=90, draw=black,fill=blue!50, inner sep=1mm,rounded corners, zx main node] {};
+ }
+ \begin{ZX}
+ \zxMyTriangle{} \rar & \zxMyTriangle-{} & \zxMyTriangle'{} \dar \\
+ & & \zxMyTriangle.{}
+ \end{ZX}
+\end{codeexample}
+}
+Note however that you can customize how rotations is applied. By default, the |'-.| variants updates |\zxCurrentRotationMode| to the rotation angle (from 0 to 90,180,270), and do |rotate=\zxCurrentRotationMode|. You can however easily change that behavior, by first undoing this rotation (in the \emph{style before user}) with |rotate=-\zxCurrentRotationMode| and do any action you like depending on the value of |\zxCurrentRotationMode|. Here is a nice use-case: if you rotate a node with |transform shape|, it will also rotate the text inside:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+ \zxNewNodeFromPic{MyTriangle}[
+ every node/.append style={transform shape},
+ ]{
+ \node[regular polygon, regular polygon sides=3, shape border rotate=90, draw=black,fill=blue!50, font=\footnotesize,inner sep=1pt,rounded corners, zx main node] {\tikzpictext};
+ }
+ \begin{ZX}
+ \zxMyTriangle{A} \rar & \zxMyTriangle-{A} & \zxMyTriangle'{A} \dar \\
+ & & \zxMyTriangle.{A} \\
+ \end{ZX}
+\end{codeexample}
+}
+To avoid that issue, we will undo the default rotation, and apply on the node of interest a rotation with |shape border rotate| (that rotates the border but not the text inside):
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+ \zxNewNodeFromPic{MyTriangle}[
+ % We undo the default rotation:
+ rotate=-\zxCurrentRotationMode,
+ ]{
+ \node[
+ regular polygon, regular polygon sides=3, draw=black,fill=blue!50, font=\footnotesize,
+ inner sep=1pt,rounded corners, zx main node,
+ shape border rotate=90+\zxCurrentRotationMode, % Rotates the shape but not the text
+ ] {\tikzpictext};
+ }
+ \begin{ZX}
+ \zxMyTriangle{A} \rar & \zxMyTriangle-{A} & \zxMyTriangle'{A} \dar \\
+ & & \zxMyTriangle.{A} \\
+ \end{ZX}
+\end{codeexample}
+}
+Note that one might want to exchange |\zxMyNode|/|\zxMyNode-| or |\zxMyNode'|/|\zxMyNode.| (for instance, it might be more natural to denote |'| in place of |.| and |.| in place |'|, since these symbols visually represent the top/bottom place of the node). In that case, you just need to apply the style |invert top bottom| or |invert right left| in your \emph{style before user} and it will invert them automatically.
+
+\paragraph{Add anchors to node.} We can automatically (and easily) add multiple anchors to our nodes (the |fake center east/…| anchors are used for instance by shapes like |\ar[<']| to see where the node should start from, while the |true north/…| anchors are used to notify where is the true north after the rotation (after rotating a node, the east might actually be on the north etc), which is for instance used by shapes like |C'|): just add coordinates with the name of the desired anchor in your graph (say |anchorA| and |anchorB|), and in \emph{style \textbf{after} user} add this list of anchor like: |zx create anchors={anchorA,anchorB}| (actually this list is expanded using the |\foreach| syntax so you can use more advanced syntax like |anchor1,anchor...,anchor10| to avoid repeating the 10 names of the anchor). For instance, we can do this way:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+ \zxNewNodeFromPic{MyStar}[][
+ % Note that this is the SECOND optional argument!
+ zx create anchors={anchorA,anchorB},
+ ]{
+ \node[star, minimum size=6mm, draw, alias=mystar, fill=red, zx main node] at (0,0) {};
+ \coordinate (anchorA) at (mystar.outer point 1);
+ \coordinate (anchorB) at (mystar.outer point 2);
+ }
+ \begin{ZX}
+ A \rar \rar[->,end anchor=anchorA,bend left] \rar[->,end anchor=anchorB,bend left] &[5mm] \zxMyStar{}
+ \end{ZX}
+\end{codeexample}
+}
+The ZX library typically uses some special anchors like |fake center east/…| and |true east/…| to determine where some wires should start (not all kinds of wires follow this convention, for instance |<'| uses |fake center| since the wire is supposed to leave close to the center, while |C| follows |true west| since the wire is supposed to leave from the west). Because the north anchor is not anymore in the north after applying a rotation, we provide also |\zxVirtualCenterWest| (same for |East|, |North|, |South|) that will ``counter balance'' the rotation, to ensure the real north anchor is always in the north, by renaming the anchors appropriately. This way, by using these ``virtual anchors'', you only need to place your anchor when the shape is not rotated, and it should automatically rotate the anchors appropriately when needed (see remarks regarding |every node/.append style={transform shape}|):
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+% Define a reusable node
+ \zxNewNodeFromPic{MyDivider}[][zx create anchors={\zxVirtualCenterWest, \zxVirtualCenterEast},
+ every node/.append style={transform shape}
+ ]{
+ \node[regular polygon, regular polygon sides=3,shape border rotate=90,%shape border rotate=90,
+ draw=black,fill=gray!50, inner sep=1.6pt, rounded corners=0.8mm,zx main node] {};
+ \coordinate(\zxVirtualCenterEast) at (.2mm,0); % Used to start lines on the side of the shape
+ \coordinate(\zxVirtualCenterWest) at (-1mm,0);
+}
+% Use the node horizontally
+\begin{ZX}
+ \zxZ[B]{} \rar[Bn'=n+m, wc] & \zxMyDivider{}
+ \rar[o',Bn'Args={n}{}]
+ \rar[o.,Bn.Args={m}{}] &[\zxWCol] \zxMyDivider-{} \rar[B,wc] & \zxZ[B]{}
+\end{ZX}
+% Use the node vertically
+\begin{ZX}
+ \zxZ[B]{} \dar[Bn=n+m, wc] \\
+ \zxMyDivider'{} \dar[-o,BnArgs={n}{}] \dar[o-,Bn-Args={m}{}] \\[\zxWRow]
+ \zxMyDivider.{} \dar[B,wc]\\
+ \zxZ[B]{}
+\end{ZX}
+\end{codeexample}
+}
+
+You can even dynamically add anchors depending on the input of the user. For instance, if the user can choose the number of spikes of the star, you might want to create as many anchors as there are spikes:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+\zxNewNodeFromPic{MyStar}[
+ nb spikes/.store in=\myNbSides,
+ nb spikes=5,
+ every node/.append style={transform shape},
+ ][
+ % zx create anchors is parsed ultimately by \foreach so we can use lists like
+ % this to create anchors spike-1, spike-2...
+ zx create anchors/.expanded={spike-1,spike-...,spike-\myNbSides},
+ ]{%
+ \node[star, fill=red, star points=\myNbSides, minimum size=1cm, draw, alias=mystar]
+ at (0,0) {\tikzpictext};
+ % We need to place coordinates where we want to final anchors to be.
+ \foreach \i in {1,...,\myNbSides}{
+ \coordinate (spike-\i) at (mystar.outer point \i);
+ }%
+}
+\begin{ZX}
+ B \foreach \i in {1,...,8}{\expanded{\noexpand\rar[->,end anchor=spike-\i,bend left]}} &[5cm] \zxMyStar[nb spikes=8]{?!?}
+\end{ZX}
+\end{codeexample}
+}
+
+Note that this library uses some anchors called |fake center {east,west,north,south}|, to indicate for some curve style where the line should start and stop (|\ar| alone does not use any anchor, and not all curves use them: |S| for instance does not use it, while |s| does: in any case, you can force it for any curve with |force left to right| and alike, see the corresponding documentation Note also that in this mode the curve is drawn by default below the shapes, but this can be changed, see the corresponding section for details).
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+\zxNewNodeFromPic{MyNode}[][zx create anchors/.expanded={fake center west}]{
+ \node[draw,fill=blue!50,draw=blue,inner sep=3mm, zx main node, alias=mynode] at (0,0) {};
+ \node[draw,fill=red!50,draw=blue,inner sep=1mm] at (mynode.north east) {};
+ \coordinate(fake center west) at (mynode.north east);
+}
+\begin{ZX}
+ \zxZ{} \ar[rd,s] & \\
+ A \rar & \zxMyNode{}
+\end{ZX}
+\end{codeexample}
+}
+
+\paragraph{Link to a sub-node.} Sometimes, we might prefer to draw a link to a node instead of an anchor (an anchor can only be a single coordinate). To that end, just name your nodes as usual, and use |start subnode| or |end subnode| to do the link
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\begin{codeexample}[width=0pt]
+ \zxNewNodeFromPic{MyDoubleNode}{
+ \node[fill=blue!20, zx main node, inner sep=3mm] at (0,0) {};
+ \node[circle,fill=red!70, inner sep=.8mm,name=redNode] at (0,1.5mm) {};
+ \node[circle,fill=orange!70, inner sep=.8mm, name=orangeNode] at (0,-1.5mm) {};
+ }
+ \begin{ZX}
+ A \rar[end subnode=redNode] \rar[end subnode=orangeNode] &[5mm] \zxMyDoubleNode{}\\
+ B \ar[ru, end subnode=orangeNode]
+ \end{ZX}
+\end{codeexample}
+}
+
+Note that you can also combine it with |to| and |alias|:
+{\catcode`\|=12 % Ensures | is not anymore \verb|...|
+\zxNewNodeFromPic{MyDoubleNode}{
+ \node[fill=blue!20, zx main node, inner sep=3mm] at (0,0) {};
+ \node[circle,fill=red!70, inner sep=.8mm,name=redNode] at (0,1.5mm) {};
+ \node[circle,fill=orange!70, inner sep=.8mm, name=orangeNode] at (0,-1.5mm) {};
+}
+\begin{ZX}
+ \zxZ{} \ar[to=buttons, end subnode=orangeNode] \\
+ \zxX{} \rar & \zxMyDoubleNode[a=buttons]{} \rar &
+\end{ZX}
+}
+
+\end{pgfmanualentry}
+
+
+
+
+\subsubsection{Create your own multi-column/row gate}
+
+We provide since 2023/09/23 a number of functions in order to deal with gates spawning multiple rows or columns, including to create your own multi-columns/rows gates. We present first the individual functions, and show after how to combine them to create more advanced styles. Note that the following define commands, but you can easily insert them in a style using:
+\begin{verbatim}
+/utils/exec={\yourCommands}
+\end{verbatim}
+or by creating a new style with |my style/.code={\yourCommand}|.
+
+\begin{pgfmanualentry}
+ \extractcommand\zxGetNameAbsoluteNode\marg{row}\marg{column}\@@
+ \pgfmanualbody%
+ Function to get the name of a cell using its absolute coordinate in the matrix (start at 1):
+\begin{codeexample}[]
+\begin{ZX}[
+ execute at end picture={
+ \node[draw, rounded corners, fill=orange,
+ node on layer=background,
+ fit=(\zxGetNameAbsoluteNode{1}{1})(\zxGetNameAbsoluteNode{1}{2})
+ ]{};
+ }]
+ A & B
+\end{ZX}
+\end{codeexample}
+\end{pgfmanualentry}
+
+\begin{pgfmanualentry}
+ \extractcommand\zxExecuteAtEndPicture\marg{code}\@@
+ \extractcommand\zxOriginalRow\@@
+ \extractcommand\zxOriginalCol\@@
+ \extractcommand\zxGetNameRelativeNode\marg{relative row}\marg{relative column}\@@
+ \extractcommand\zxGetNameRelativeNodeStartOne\marg{relative row}\marg{relative column}\@@
+ \pgfmanualbody%
+ |execute at end picture| is first annoying to use, but it also runs after the definition of the wires, meaning that it is not possible to point to nodes defined in that portion of the code. To solve these issues, we define |\zxExecuteAtEndPicture{your code}| that you can insert inside a node. Note that in |your code| you can use |\zxOriginalRow| and |\zxOriginalCol| that will contain the position of the column and row where you inserted that command, and |\zxGetNameRelativeNode| will allow you to get the name of the neighbour nodes by specifying the difference of columns and the difference of lines. Note that these variables and commands are usable in |\zxExecuteAtCellRelative| and |\zxExecuteAtCellAbsolute| as well.
+\begin{codeexample}[]
+\NewExpandableDocumentCommand{\myFitWithBelowNeighbour}{}{
+ \zxExecuteAtEndPicture{%
+ \node[draw, rounded corners, fill=orange,
+ node on layer=background,
+ fit=(\zxGetNameRelativeNode{0}{0})(\zxGetNameRelativeNode{1}{0})
+ ]{};
+ }%
+}
+\begin{ZX}
+ A & B & C & D \\
+ A & B \myFitWithBelowNeighbour & C & D \\
+ A & B & C & D \\
+\end{ZX}
+\end{codeexample}
+The |zxGetNameRelativeNodeStartOne| variant index elements from $1$ instead of $0$.
+\end{pgfmanualentry}
+
+\begin{pgfmanualentry}
+ \def\extrakeytext{style, }
+ \extractcommand\zxExecuteAtCellAbsolute\marg{row}\marg{column}\marg{code}\@@
+ \extractcommand\zxExecuteAtCellRelative\marg{relative row}\marg{relative column}\marg{code}\@@
+ \extractcommand\zxExecuteAtRegionRelative\marg{relative row}\marg{relative column}\marg{code}\@@
+ \pgfmanualbody%
+ Often, just adding some nodes at the end of the picture is not enough: you might want to add other nodes automatically in the matrix. For instance, if you want to implement yourself a gate spawning multiple rows, a simple way to achieve that would be to add invisible boxes inside the matrix and use them to fit the final component. You can place nodes where you want using something like this (note that you should use |zx main node| that is basically a shortcut for:
+\begin{verbatim}
+\tikzset{name=\zxCurrentDiagram-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn}
+\end{verbatim}
+otherwise |\rar| will not be able to know which node to join: note that it is automatically added in nodes like |\zxX{}|):
+\begin{codeexample}[]
+\NewExpandableDocumentCommand{\mySimpleMultigate}{m}{
+ \zxBox{#1}
+ \zxExecuteAtCellRelative{1}{-1}{\node[zx main node, green]{\text{I am relative}};}
+ \zxExecuteAtCellRelative{0}{1}{\node[zx main node, green]{\text{I am also relative}};}
+ \zxExecuteAtCellAbsolute{2}{4}{\node[zx main node, red]{\text{I am absolute}};}
+}
+\begin{ZX}
+A & B & C \\
+ & \mySimpleMultigate{X} & & \\
+ & & \\
+\end{ZX}
+\end{codeexample}
+(note that the relative version adds it to cells relative to the current cell while the absolute version executes it at the absolute cell coordinate)
+\textbf{Important}: for all these manipulation to work, be sure to only specify coordinates after the main node, either later on the same line or on next rows since previous cells have already been parsed.
+
+You can also do it for a whole region of size $n \times m$ using |\zxExecuteAtRegionRelative{n}{m}{code}| like this (just make sure that the cells exist):
+\begin{codeexample}[]
+\NewExpandableDocumentCommand{\myRegion}{}{
+ \zxExecuteAtRegionRelative{2}{3}{%
+ \zxBox{\text{\tiny Original row: \zxOriginalRow{}, column:\zxOriginalCol{}
+ % We compute the relative position to print it:
+ (rel: \the\numexpr\the\pgfmatrixcurrentrow -\zxOriginalRow\relax
+ x\the\numexpr\the\pgfmatrixcurrentcolumn-\zxOriginalCol\relax).}}}
+}
+\begin{ZX}
+ A & B & C & D & E & F & G \\
+ & & \myRegion & & & & \\
+ & & & & & & \\
+ & & & & & &
+\end{ZX}
+\end{codeexample}
+(note that if you use |\zxExecuteAtRegionRelative| and want to define one alias for the top-left node, you should use |a if origin=alias for the node| instead of |a=alias name for the node| since it would give the alias to the last node instead of the first node). Note that if you execute it multiple times on the same cell, both codes will be executed.
+\end{pgfmanualentry}
+
+\begin{pgfmanualentry}
+ \def\extrakeytext{style, }
+ \extractcommand\zxSetVariable\marg{name variable}\marg{content variable}\@@
+ \extractcommand\zxSetVariableExpandOnce\marg{name variable}\marg{content variable}\@@
+ \extractcommand\zxSetVariableExpand\marg{name variable}\marg{content variable}\@@
+ \extractcommand\zxGetVariable\marg{name variable}\@@
+ \makeatletter% should not be letter for \@@... strange
+ \extractkey/tikz/zx style from variable=\marg{name variable}\@nil%
+ \makeatother
+ \pgfmanualbody%
+ You might want at some point to pass data to the node you placed elsewhere, for instance the style it should take etc. For simple setups, you can directly pass the argument like:
+\begin{codeexample}[]
+ \NewExpandableDocumentCommand{\mySimpleMultigate}{mmmm}{
+ \zxBox{#1}
+ \zxExecuteAtCellRelative{1}{-1}{\node[zx main node, #2]{\text{I am relative}};}
+ \zxExecuteAtCellRelative{0}{1}{\zxBox[zx main node]{\text{I am also relative}}}
+ \zxExecuteAtCellAbsolute{2}{4}{\node[zx main node, #4]{\text{I am absolute}};}
+ }
+ \begin{ZX}
+ & & \\
+ & \mySimpleMultigate{X}{red}{pink}{orange} & & \\
+ & & \\
+ \end{ZX}
+\end{codeexample}
+but for more complicated setups, you might want to use some variables. This can be done using the above commands (set it in the main node, and get it in other nodes) (or you can also directly give it the argument): this should just create a new macro and evaluate it.
+\begin{codeexample}[]
+\NewExpandableDocumentCommand{\mySimpleMultigate}{mmm}{
+ \zxX{#1}
+ \zxSetVariable{my variable}{Hey #2}
+ \zxSetVariable{my style}{#3}
+ \zxExecuteAtCellRelative{1}{-1}{\node[zx style from variable={my style}]{\text{\zxGetVariable{my variable}}};}
+}
+\begin{ZX}
+A & B & C \\
+ & \mySimpleMultigate{\alpha}{Alice}{purple,opacity={.3}} & & \\
+ & & \\
+\end{ZX}
+\end{codeexample}
+The difference between |\zxSetVariable|, |\zxSetVariableExpandOnce| and |\zxSetVariableExpand| is that they respectively don't expand their input like |\gdef|, expand it once, or expand it completely like |\gxdef|. This can be useful in more complex setups, for instance if you store the style/variable in a macro first using pgfkeys:
+\begin{codeexample}[width=0pt]
+\NewExpandableDocumentCommand{\MyGateMulti}{O{}mmm}{
+ % The path; here is useful to help tikzcd to see that it is a node as it tries to search for path and \pgfkeys does not look like a path
+ % If you forget it, you will get something like \node is not defined
+ \path;\pgfkeys{
+ /zx/gateMulti/.cd,
+ content inner nodes/.store in=\myContent,
+ content inner nodes=#4,
+ a/.store in=\zxGateMultiAlias,
+ a=,
+ style inner nodes/.store in=\zxGateMultiStyle,
+ style inner nodes={},
+ #1,
+ }%
+ % Store the content for letter use
+ \zxSetVariableExpandOnce{content inner nodes}{\myContent}
+ \zxSetVariableExpandOnce{style inner nodes}{\zxGateMultiStyle}
+ \zxExecuteAtRegionRelativeAndOrigin{#2}{#3}{%
+ \zxBox[zx main node,
+ % a if origin=\zxGateMultiAlias,
+ draw,
+ zx style from variable={style inner nodes},
+ %/zx/gateMulti/style inner nodes aux
+ ]{\zxGetVariable{content inner nodes}};
+ }%
+}
+
+\begin{ZX}
+ & & & & & & & \\
+ & & \MyGateMulti[style inner nodes={red,test/.style={fill=#1,opacity=.3},test=red}]{2}{3}{H} & & & & & \\
+ & & & & & & & \\
+ & & & & & & & \\
+ & & & & & & & \\
+\end{ZX}
+\end{codeexample}
+\end{pgfmanualentry}
+
+With all of this, we can now create a simple multi-columns/rows gate mechanism (but you certainly want to use the one provided by this library if you actually care about multi-columns/rows gates:
+
+
+\begin{codeexample}[width=0pt]
+ % \mySimpleMultigate{rows}{cols}{content}
+ \NewExpandableDocumentCommand{\mySimpleMultigate}{mmm}{
+ \node[zx main node, inner sep=1mm]{#3};
+ \zxExecuteAtCellRelative{#1}{#2}{%
+ \node[zx main node, inner sep=1mm]{#3};
+ }
+ \zxExecuteAtEndPicture{
+ \node[node on layer=foreground,
+ fill=white, inner sep=0pt, draw,
+ fit=(\zxGetNameRelativeNode{0}{0})(\zxGetNameRelativeNode{#1}{#2}),
+ label={[node on layer=foreground]center:{#3}}]{};
+ }
+ }
+ \begin{ZX}
+A & B & C & D & E & F \\
+\rar & \mySimpleMultigate{2}{3}{X} & & & & \lar \\
+\rar & & & & & \lar \\
+\zxN{} \dar[C] \rar & & & & & \zxN[a=bottomright]{} \lar \\
+\zxN{} \ar[to=bottomright,C-] &
+\end{ZX}
+\end{codeexample}
+
+Note that you can also define subnodes in the final node and point to them. You can either use its alias, or point to any node added via region relative or cell relative, it will automatically find the parent node:
+
+\begin{codeexample}[width=0pt]
+ % \mySimpleMultigate{rows}{cols}{content}
+ \NewExpandableDocumentCommand{\myFancyGate}{O{}mmm}{
+ % a=#1 make sure to add the alias on the first element
+ \node[zx main node, inner sep=1mm, a=#1]{#4};
+ \zxExecuteAtRegionRelative{#2}{#3}{%
+ \node[zx main node, inner sep=1mm]{#4};
+ }%
+ \zxExecuteAtEndPicture{
+ \node[node on layer=foreground,
+ alias=tmp,
+ opacity=.5,
+ fill=white, inner sep=0pt, draw,
+ fit=(\zxGetNameRelativeNode{0}{0})(\zxGetNameRelativeNode{\the\numexpr#2-1\relax}{\the\numexpr#3-1\relax}),
+ label={[node on layer=foreground]center:{#4}}]
+ {};
+ \node[node on layer=foreground, fill=red, inner sep=.9mm, circle, zx subnode=redCircle] at (tmp.south east) {};
+ }
+ }
+ \begin{ZX}
+A & B & C & D & E & F \\
+\rar[end subnode=redCircle, blue, bend right] & \myFancyGate[aliasMyGate]{3}{4}{X} & & & \rar & \\
+\rar[purple] & & & & & \lar \\
+\rar[end subnode=redCircle, pink, bend right] & & & & & \lar \\
+\ar[to=aliasMyGate,red] & \\
+\ar[to=aliasMyGate,end subnode=redCircle,green,bend right] &
+\end{ZX}
+\end{codeexample}
+
+You can also force all nodes pointing to a region-relative or cell-relative to point to a specific anchor:
+
+\begin{pgfmanualentry}
+ \def\extrakeytext{style, }
+ \makeatletter% should not be letter for \@@... strange
+ \extractkey/every node/pre arrow style if start node=\marg{style, to, apply}\@nil%
+ \extractkey/every node/pre arrow style if end node=\marg{style, to, apply}\@nil%
+ \extractkey/every node/post arrow style if start node=\marg{style, to, apply}\@nil%
+ \extractkey/every node/post arrow style if end node=\marg{style, to, apply}\@nil%
+ \makeatother
+ \pgfmanualbody%
+ This will apply the corresponding style to any wire leaving from the current cell or arriving to the current cell depending on the variation (node that you can use these functions in any node, there is no special role played by |zxExecuteAtRegionRelativeAndOrigin| here), |pre| variants being run before the user input (\textbf{WARNING}: at the step, the target of the node is not known!) while |post| variants are run after the user input:
+
+\begin{codeexample}[width=0pt]
+% \myFancyGate[alias]{rows}{cols}{content}
+\NewExpandableDocumentCommand{\myFancyGate}{O{}mmm}{
+ \zxExecuteAtRegionRelativeAndOrigin{#2}{#3}{%
+ \node[zx main node, inner sep=1mm, a if origin=#1,
+ %% These two lines says to connect any line coming/leaving from here to the redCircle subnode
+ post arrow style if start node={start subnode=redCircle},
+ post arrow style if end node={end subnode=redCircle},
+ ]{#4};
+ }%
+ \zxExecuteAtEndPicture{
+ \node[node on layer=foreground,
+ alias=tmp,
+ opacity=.5,
+ fill=white, inner sep=0pt, draw,
+ % The expression "\the\numexpr#3-1\relax" removes 1 to the current column or it will draw too many
+ % columns (size n x m means that we stop at element (n-1) x (m-1) since we start from zero
+ fit=(\zxGetNameRelativeNode{0}{0})(\zxGetNameRelativeNode{\the\numexpr#2-1\relax}{\the\numexpr#3-1\relax}),
+ label={[node on layer=foreground]center:{#4}}]
+ {};
+ \node[node on layer=foreground, fill=red, inner sep=.9mm, circle, zx subnode=redCircle] at (tmp.south east) {};
+ }
+}
+\begin{ZX}
+A & B & C & D & E & F \\
+\rar & \myFancyGate[aliasMyGate]{3}{4}{X} & & & \rar & \\
+\rar[purple] & & & & & \lar \\
+\rar[end subnode=redCircle, pink, bend right] & & & & & \lar \\
+\ar[to=aliasMyGate,red] & \\
+\ar[to=aliasMyGate,end subnode=redCircle,green,bend right]
+\end{ZX}
+\end{codeexample}
+\end{pgfmanualentry}
+
+
+\subsection{Caching pictures via an externalization library}\label{sec:externalization}
+
+The pictures built with this package can easily take maybe 0.5 seconds per picture to be built, which can easily add up to a long compilation time. Caching externalization can save you a lot of time: I went from a tiny draft taking 30 seconds to be built to a built time of 2.5 seconds.
+
+\subsubsection{robust-externalize: recommended}
+
+While \tikzname{} provides an external library, it has many drawbacks that make it unusable in practice. To solve that issue, I created my own library called \mylink{https://github.com/leo-colisson/robust-externalize}{\texttt{robust-externalize}}. It's still very young, but has been working really reliably in my tests (note that a major update occurred in september 2023, so we updated the instruction accordingly).
+
+To use it, first install |robust-externalize| by copy/pasting robust-externalize.sty in your project (unless your \LaTeX{} distribution already has it), make sure you have version 1.1, and load it using:
+\begin{codeexample}[code only]
+\usepackage{robust-externalize}
+\robExtConfigure{
+ % We create a new preset for zx pictures
+ new preset={ZX}{
+ latex, % we inherit from the latex preset
+ % make sure to use the same font as the document, or the equations will not be properly aligned
+ add to latex options={11pt},
+ add to preamble={ % we make sure the zx library is loaded when building cached images
+ \usepackage{amsmath}
+ \usepackage{zx-calculus}
+ },
+ dependencies={}, % Add here any file that must induce a recompilation of your file if it changes.
+ },
+}
+
+% say to cache by default all ZX environments (can be changed later) and \zx{} commands
+\cacheEnvironment{ZX}{ZX}
+\cacheCommand{zx}{ZX}
+
+% You can pass options to robust-externalize via <>
+\begin{ZX}<add to preamble={\def\name{Alice}}>
+ \zxX{\text{\name}}
+\end{ZX}
+\end{codeexample}
+
+Now, just recompile your project: it should cache the pictures. See \mylink{https://github.com/leo-colisson/robust-externalize}{\texttt{robust-externalize}} for more details.
+
+\subsubsection{Tikz external: not recommended}
+
+\textbf{WARNING}: I added some options to use tikz |external| library to save compilation time... And then I realized that tikz |external| was quite close to be unusable in practice as it has many caveats. I ended up coding my own replacement to externalize any operation, and it works much better! See comment in the previous section.
+
+Since 2022/02/08, it is possible to use the tikz |external| library to save compilation time. To load it, you need to add the following tikz libraries:
+\begin{verse}
+ |\usetikzlibrary{external}|\\
+ |\usetikzlibrary{zx-calculus}|\\
+ |\tikzexternalize|\\
+ |\zxConfigureExternalSystemCallAuto|\\
+\end{verse}
+Then, compile with shell-escape, for instance using |pdflatex -shell-escape yourfile.tex|.
+
+\textbf{WARNING}: if |external| is loaded before |zx-calculus|, you don't need to run |\zxConfigureExternalSystemCallAuto|. This command is only useful to ensure the system call used by |external| displays errors appropriately by configuring the interaction mode to match the one used by the parent compilation command. If you prefer to disable this feature to use |external|'s default, define `\def\zxDoNotPatchSystemCall{}` before loading the |zx-calculus| library.
+
+\alertwarning{Note however that this has not yet being extensively tested, and the \texttt{external} library has a few caveats presented below}
+\begin{itemize}
+\item If you change the order of the diagrams, or add a diagram in the middle of the document, all subsequent diagrams will be recompiled. This issue has been reported \mylink{https://github.com/pgf-tikz/pgf/issues/758}{here} and is caused by the fact that the figures are called \texttt{figure0},\dots,\texttt{figureN}. To limit this issue, you can regularly insert \texttt{\textbackslash{}tikzsetfigurename\{nameprefix\}} in your document with different names to avoid a full recompilation of the file (or using groups to change it for a single newly added equation).
+\item The \texttt{external} library uses the main file to recompile each picture, so if your file is large or loads a lot of libraries, it may \mylink{https://tex.stackexchange.com/questions/633175/tikz-externalize-is-much-slower-than-tikz-on-first-run}{take a while to compile a single diagram} (to give an example, this library takes 41 seconds to compile without the externalize library, with the externalize library it takes 14mn for the first run and 3 seconds for the next runs). For this reason, you may want to use \texttt{\textbackslash{}tikzset\{external/export=false\}} or |\tikzexternaldisable| (the latter won't fail if your elements are not parsable by tikz external) in a group to disable temporarily the external library while you are writing your diagram. You may like the |list and make| option of tikz external that produces a Makefile that one can compile separately to build in parallel all pictures.
+\item If you compile once a diagram without any error, and recompile it after inserting an error, you will see an error while compiling. But if you recompile again, the error will disappear and the diagram that lastly succeeded to build will be inserted instead of the newly buggy diagram. This has been reported \mylink{https://github.com/pgf-tikz/pgf/issues/1137}{here}.
+\item Sometimes, |external| cuts some parts of the picture, namely when parts are drawn outside of the bounding box. I've not experienced that with zx diagrams directly (we don't go beyond the bounding box), but the example at the end of this document with the |double copy shadow| has such issues because the shadow is drawn outside of the bounding box. One should therefore disable the externalization (or increase the bounding box) in these cases.
+\item It seems that sometimes the inner sep of some labels in |external| mode defaults to zero (see the CNOT example below), I'm not sure why. Adding explicitly the value of the label fixes this.
+\end{itemize}
+
+\begin{pgfmanualentry}
+ \extractcommand\zxExternalAuto\@@
+ \extractcommand\zxExternalWrap\@@
+ \extractcommand\zxExternalNoWrap\@@
+ \extractcommand\zxExternalNoWrapNoExt\@@
+ \extractcommand\zxExternalWrapForceExt\@@
+ \pgfmanualbody
+ Also, the library |external| forces us to wrap our diagrams into a basically empty tikz-pictures to make it work. The current library will automatically wrap the diagrams when the |external| library is enabled, but you can customize how diagrams are wrapped manually: |\zxExternalAuto| (default) will wrap it automatically if |external| is enabled, |\zxExternalWrap| will always wrap it, |\zxExternalNoWrap| will never wrap it (you will get errors if you use |external|), |\zxExternalNoWrapNoExt| will not wrap the figure, but will disable temporary the externalization for diagrams to avoid errors and |\zxExternalWrapForceExt| will wrap the figures and enable tikz |external| locally only for zx-diagrams (using |\tikzexternalenable|). This last option is particularly useful when using |external| while most other environments are not compatible with externalization (like tikzcd, quantikz, blochsphere, maybe cryptocode\dots{}): the idea is to disable tikzexternalize everywhere, except for zx diagrams:
+\begin{verse}
+|\tikzexternalize|\\
+|\tikzexternaldisable|\\
+|\zxExternalWrapForceExt|
+\end{verse}
+\end{pgfmanualentry}
+
+\begin{pgfmanualentry}
+ \extractcommand\zxExternalSuffix\marg{suffix}\@@
+ \pgfmanualbody
+By default, the library adds a suffix |zx| to figures corresponding to zx diagrams (it avoids to recompile diagrams when a normal figure is added in between two zx diagrams). You can change (or remove) this suffix using |\zxExternalSuffix{yoursuffix}|, where the suffix can also be empty.
+\end{pgfmanualentry}
+
+Note that if you get an error:\\
+|Argument of \tikzexternal@laTeX@collect@until@end@tikzpicture has an extra }|\\
+it is likely that you have an element that is not handled by tikz external, like a raw |tikzcd| environment, a |blochsphere| environment\dots{} Either disable temporary tikz external around it:\\
+|{\tikzexternaldisable your code not compatible with external}|\\
+or wrap your element around |\begin{tikzpicture}\node{your figure};\end{tikzpicture}| (people usually don't like nested tikz pictures\dots{} but it often works nicely). In case you also care about the baseline, you may prefer to wrap it using:\\
+|\begin{tikzpicture}[baseline=(mynode.base)]\node(mynode){your figure};\end{tikzpicture}|
+
+\subsection{How to visually group multiple nodes}\label{subsec:decoration}
+
+
+\begin{pgfmanualentry}
+ \def\extrakeytext{style, }
+ \extractcommand\zxCont\oarg{style}\oarg{color}\marg{nb rows}\marg{nb columns}\oarg{label style}\oarg{(other)(nodes)(to)(fit)}\marg{Text of label}\@@
+ \extractcommand\zxGroupGates\oarg{style}\marg{nb rows}\marg{nb columns}\oarg{label style}\oarg{(other)(nodes)(to)(fit)}\marg{Text of label}\@@
+ \extractcommand\zxContName\oarg{style}\oarg{color}\marg{(nodes)(to)(fit)}\oarg{label style}\marg{Text of label}\@@
+ \extractcommand\zxNamedBox\oarg{style}\oarg{color}\marg{(nodes)(to)(fit)}\oarg{label style}\marg{Text of label}\@@
+ \pgfmanualbody
+ These commands are used to highlight a part of a diagram (|Cont| is for ``Container''), or, for |\zxGroupGates|, to group gates together (it is like |Cont| but with a different style), the main difference is that the |Cont| version can be used inside the matrix and will automatically contain the current node (you must then either by specifying the size of the box or the name of the other nodes to fit), while |\zxNamedBox| must be inserted later (so you might not use it much), like:
+\begin{codeexample}[width=0cm]
+ \begin{ZX}
+ \zxN{} \rar & [\zxwCol] \zxZ{} \zxCont{2}{1}{\textsc{cnot}} \dar \rar & [\zxwCol] \zxN{} \\
+ \zxN{} \rar & \zxX{} \rar & [\zxwCol] \zxN{} \\
+ \end{ZX}
+\end{codeexample}
+\begin{codeexample}[width=0cm]
+ \begin{ZX}
+ \zxN{} \rar & [\zxwCol] \zxZ{} \zxContName{(endCnot)}{\textsc{cnot}} \dar \rar & [\zxwCol] \zxN{} \\
+ \zxN{} \rar & \zxX[a=endCnot]{} \rar & [\zxwCol] \zxN{} \\
+ \end{ZX}
+\end{codeexample}
+\begin{codeexample}[width=0cm]
+ \begin{ZX}[
+ % \zxCont offers a more practical interface
+ execute at end picture={
+ \zxNamedBox{(cnot1)(cnot2)}{
+ below:\textsc{cnot}
+ }
+ }
+ ]
+ \zxN{} \rar &[\zxwCol] \zxZ[alias=cnot1]{} \dar \rar &[\zxwCol] \zxN{}\\
+ \zxN{} \rar & \zxX[alias=cnot2]{} \rar &[\zxwCol] \zxN{}\\
+ \end{ZX}
+\end{codeexample}
+
+Note that the |fit| library cannot fit a wire. So if you want to include the wires around a node, the simpler thing might be to manually increase the size of the box in the style. We provide for that an helper command |fit margins={top=1mm,bottom=2mm,right=2.2mm,left=2.2mm}| (the |inner sep| and |shift| commands of tikz are not really practical to move a single border), you can also use |horizontal|, |vertical|, or |all|, and |l| is a shorcut to add larger margins instead of |fit margins={all=1mm}|.
+\begin{codeexample}[width=0cm]
+ \begin{ZX}[
+ execute at end picture={
+ \zxNamedBox[fit margins={right=2.2mm}]{(measX)(measZ)}{
+ below:\footnotesize Bell measurement
+ }
+ \zxNamedBox[fit margins={bottom=2pt,top=2pt,left=2.0mm}][green!80!black]{(bellA)(bellB)}{
+ left:\footnotesize Bell pair:
+ }
+ }
+ ]
+ \zxN[a=bellA]{} \rar \dar[C] & [\zxwCol] \zxX*{x\pi} \rar & \zxZ*{z\pi} \rar & \zxN{} \\[\zxwCol]
+ \zxN[a=bellB]{} \rar & \zxX[a=measX]{x\pi} \dar[C-] & \\
+ \zxN{} \rar & \zxZ[a=measZ]{z\pi}
+ \end{ZX}
+\end{codeexample}
+This will automatically create a subnode |wrapper| pointing to the wrapping node. You can use it to link to that node (note that you should be sure that the wire points to the top left element of the group):
+\begin{codeexample}[width=0cm]
+ \begin{ZX}[circuit]
+ \ar[rr] && \zxCtrl{} \ar[dl, end subnode=wrapper] \ar[rr] && \\
+ \rar & \zxCtrl{} \dar \rar \zxGroupGates{2}{3}{below:\textsc{swap}} & \zxNot{} \dar \rar & \zxCtrl{} \dar \rar & \\
+ \rar & \zxNot{} \rar & \zxCtrl{} \rar & \zxNot{} \rar &
+ \end{ZX}
+\end{codeexample}
+\end{pgfmanualentry}
+
\section{Advanced styling}
\subsection{Overlaying or creating styles}
@@ -1673,6 +3741,20 @@ You can also change it on a per-diagram basis:
The list of keys that can be changed will be given below in |/zx/styles/rounded style/*|.
\end{stylekey}
+\begin{stylekey}{/zx/user overlay}
+ This key will be loaded like it if were inside the options of the picture |\zx[options]{...}|. To avoid always typing |\zx[content vertically centered]{...}|, you can therefore use:
+\begin{codeexample}[width=0pt]
+\tikzset{
+ /zx/user overlay/.style={
+ content vertically centered,
+ },
+}
+\begin{ZX}
+ \zxX{\alpha} & \zxX{\beta} & \zxX{a} & \zxX{b} & \zxX*{a\pi} & \zxX*{b\pi} & \zxX*{b'\pi} & \zxX*{'b\pi} & \zxZ{(a \oplus b )\pi}
+\end{ZX}
+\end{codeexample}
+\end{stylekey}
+
\begin{stylekey}{/zx/default style wires}
Default style for wires. Note that |/zx/wires definition/| is always loaded by default, and we don't add any other style for wires by default. But additional styles may use this functionality.
\end{stylekey}
@@ -1787,8 +3869,20 @@ We present now all the properties that a new node style must have (and that can
This is used to change how the library does the conversion between |\zxFrac| and the actual written text (either in the node content or in the label depending on the function). The first argument is the sign (string |-| for minus, anything else must be written in place of the minus), the second and third argument are the numerator and denominator of the fraction when used in |\frac{}{}| while the last two arguments are the same except that they include the parens which should be added when using an inline version. For instance, one could get a call |\zxConvertToFracInLabel{-}{a+b}{c+d}{(a+b)}{(c+d)}|. See part on labels to see an example of use.
\end{pgfmanualentry}
-\begin{command}{\zxMinusInShort}
- Sign used in |\zxZ-{\alpha}| and |\zxX-{\alpha}|-like patterns. You can redefine it, for instance:
+\begin{pgfmanualentry}
+ \def\extrakeytext{style, }
+ \extractcommand\zxMinusUnchanged\@@
+ \extractcommand\zxMinus\@@
+ \extractcommand\zxMinusInShort\@@
+ \makeatletter% should not be letter for \@@... strange
+ \extractkey/zx/defaultEnv/zx column sep=length\@nil%
+ \extractkey/zx/styles/rounded style preload/small minus\@nil%
+ \extractkey/zx/styles/rounded style preload/big minus\@nil%
+ \extractkey/zx/styles/rounded style/small minus\@nil%
+ \extractkey/zx/styles/rounded style/big minus\@nil%
+ \makeatother
+ \pgfmanualbody
+ |\zxMinus| is the minus sign used in fractions, |\zxMinusInShort| is used in |\zxZ-{\alpha}| and |\zxMinusUnchanged| is a minus sign shorter than $-$. You can redefine them, for instance:
\begin{codeexample}[]
Compare {\def\zxMinusInShort{-}
\zx{\zxZ-{\alpha}}
@@ -1797,7 +3891,20 @@ Compare {\def\zxMinusInShort{-}
\zx{\zxZ-{\alpha}}
}
\end{codeexample}
-\end{command}
+You can also choose to always use a big or a small minus, either on a per-node, per-figure, or document-wise.
+\begin{codeexample}[]
+\begin{ZX}
+ \zxFracZ-{\pi}{4} & \zxZ-{\alpha} & \zxZ-{\delta_i} & \zxZ[small minus]-{\delta_i}
+\end{ZX} Picture-wise %
+\begin{ZX}[small minus]
+ \zxZ-{\alpha} & \zxZ-{\delta_i} & \zxZ-{\delta_i} & \zxFracZ-{\pi}{4}
+\end{ZX} Document-wise %
+\tikzset{/zx/user overlay/.style={small minus}}%
+\begin{ZX}
+ \zxZ-{\alpha} & \zxZ-{\delta_i} & \zxZ[big minus]-{\delta_i} & \zxFracZ[big minus]-{\pi}{4}
+\end{ZX}
+\end{codeexample}
+\end{pgfmanualentry}
\noindent We also define several spacing commands that can be redefined to your needs:
\begin{pgfmanualentry}
@@ -1834,7 +3941,21 @@ Compare {\def\zxMinusInShort{-}
\zxN{} \ar[ru,-N'] & & \zxN{}
\end{ZX}
\end{codeexample}
-Note that you can add multiple of them by separating with commas (see |\pgfmatrixnextcell|'s documentation for more details). For instance to have a column separation of exactly |2mm|, do |&[\zxZeroCol,2mm]| (if you just do |&[2mm]| the column will be |2mm| larger).
+Note that you can add multiple of them by separating with commas (see |\pgfmatrixnextcell|'s documentation for more details). For instance to have a column separation of exactly |2mm|, do |&[\zxZeroCol,2mm]| (if you just do |&[2mm]| the column will be |2mm| larger). This can also be useful to avoid having a huge space when nodes have multiple empty outputs:
+\begin{codeexample}[]
+ Compare:
+ \begin{ZX}
+ \zxN{} & & \zxN{} \\
+ \zxN{} \rar & \zxZ{} \ar[ur,<'] \ar[dr,<'] & \\
+ & & \zxN{} \\
+ \end{ZX}
+ with
+ \begin{ZX}
+ \zxN{} & & \zxN{} \\[\zxZeroRow]
+ \zxN{} \rar & \zxZ{} \ar[ur,<'] \ar[dr,<'] & \\[\zxZeroRow]
+ & & \zxN{}
+ \end{ZX}
+\end{codeexample}
\end{pgfmanualentry}
\begin{pgfmanualentry}
@@ -1858,10 +3979,6 @@ Note that you can add multiple of them by separating with commas (see |\pgfmatri
Default opening angles of |S|, |o| and |v|/|<| wires. Defaults to respectively $30$, $40$ and $45$.
\end{pgfmanualentry}
-\begin{command}{\zxMinus{}}
- The minus sign used in fractions.
-\end{command}
-
\subsection{Wire customization}\label{subsec:wirecustom}
\begin{pgfmanualentry}
@@ -1912,7 +4029,7 @@ By default the lines will be drawn behind the node and the starting and ending p
\zx{\zxZ{\alpha+\beta} \ar[dr,edge above,s] \\
& \zxZ{\alpha+\beta}}
\end{codeexample}
-(you can node the fact that the wire does not start at the center but at a |fake center *| anchor to provide a nicer look)
+(you can note the fact that the wire does not start at the center but at a |fake center *| anchor to provide a nicer look)
\end{pgfmanualentry}
\begin{pgfmanualentry}
@@ -2452,7 +4569,6 @@ Now, we can also globally enable the |ui| style and the intersection only for so
\end{pgfmanualentry}
-
\begin{pgfmanualentry}
\def\extrakeytext{style, }
\extractcommand\zxIntersectionLineBetweenStartEnd\@@
@@ -2506,11 +4622,12 @@ You can see that the constant looks much wider in the second picture, due to the
%% Create a new box
\newsavebox{\myZXbox}
%% Save our small diagram.
-%% Warning: the char '&' cause troubles in functions, so use ampersand replacement
-%% and \& instead:
+%% Warning: on older versions, you needed to use \& instead of &
+%% (the char '&' cause troubles in functions), but I fixed it 2022/02/09
\sbox{\myZXbox}{%
- \zx[ampersand replacement=\&]{ %<-- strange font? this is just an ampersand.
- \zxX{} \rar \ar[r,o'] \ar[r,o.] \& \zxZ{}
+ % add \tikzset{external/optimize=false} if you use tikz "external" library %
+ \zx{ % you may need
+ \zxX{} \rar \ar[r,o'] \ar[r,o.] & \zxZ{}
}%
}
@@ -2520,7 +4637,7 @@ $x = \begin{ZX}[
\node[fit=(start)(end),yshift=-axis_height] {\usebox{\myZXbox}};
},
math baseline=myb]
- &[\zxwCol] \zxFracX-{\pi}{2} & \zxN[a=start]{} & \zxN[a=end]\\
+ &[\zxwCol] \zxFracX-{\pi}{2} & \zxN[a=start]{} & \zxN[a=end]{}\\
\zxN[a=myb]{} \rar & \zxFracZ{\pi}{2} \rar & \zxFracX{\pi}{2} \rar & \zxFracZ{\pi}{2} \rar & \zxN{}
\end{ZX}$
\end{codeexample}
@@ -2534,18 +4651,45 @@ Note that this has the advantage of preserving the baseline of the big drawing.
\extractkey/zx/wires definition/use diagram=\marg{name with \textbackslash}\marg{(nodes)(to)(fit)}\@nil%
\makeatother
\pgfmanualbody
- Use |\zxSaveDiagram| to save and name a diagram (must be done before the diagram you want to insert this diagram into, also \textbf{do not forget the backslash before the name} and \textbf{replace all} |&| \textbf{in the first diagram with} |\&|. Then, |use diagram| to insert it inside a diagram (the second argument is a list of nodes given to the |fit| library):
+ Use |\zxSaveDiagram| to save and name a diagram (must be done before the diagram you want to insert this diagram into, also \textbf{do not forget the backslash before the name} (note that before 2022/09/02, you needed to use |\&| instead of |&|, but this has been fixed after 2022/02/09. In case you really care about backward compatibility, either download the sty file in your folder, or add |ampersand replacement=\&| in the options of the |\zxSaveDiagram| function and use |\&| as before). Then, |use diagram| to insert it inside a diagram (the second argument is a list of nodes given to the |fit| library):
\begin{codeexample}[width=0pt]
-%% v---- note the backslash note the \& ---v
-\zxSaveDiagram{\myZXconstant}{\zxX{} \rar \ar[r,o'] \ar[r,o.] \& \zxZ{}}
+%% v---- note the backslash
+\zxSaveDiagram{\myZXconstant}{\zxX{} \rar \ar[r,o'] \ar[r,o.] & \zxZ{}}
$x = \begin{ZX}[use diagram={\myZXconstant}{(start)(end)}, math baseline=myb]
- &[\zxwCol] \zxFracX-{\pi}{2} & \zxN[a=start]{} & \zxN[a=end]\\
+ &[\zxwCol] \zxFracX-{\pi}{2} & \zxN[a=start]{} & \zxN[a=end]{}\\
\zxN[a=myb]{} \rar & \zxFracZ{\pi}{2} \rar & \zxFracX{\pi}{2} \rar & \zxFracZ{\pi}{2} \rar & \zxN{}
\end{ZX}$
\end{codeexample}
Note that if you need more space to insert the drawing, you can use |\zxN+[a=start,minimum width=2cm]{}| instead of |\zxN|.
\end{pgfmanualentry}
+Sometimes, you may also find useful to stack diagram (for instance because the matrix of the first diagram is not related to the matrix of the second diagram), or position multiple diagrams relative to each others. You can use arrays to do that, but it will not preserve the baseline. Another solution is to put the |ZX| environment inside nodes contained in |tikzpicture| (I know that tikz does not like nesting\dots{} but it works nice for what I tried. I will also try to provide an helper function to do that later). For example here we use it to add the constants below the second diagram:
+\begin{codeexample}[vbox]
+\begin{equation*}
+ \begin{ZX}
+ &[\zxwCol] & &[\zxwCol] \zxN{} \ar[dd,3 vdots] \\[\zxNCol]
+ \zxN{} \rar & \zxZ{\pi} \rar & \zxX{\alpha} \ar[ru,N'-] \ar[rd,N.-] & \\[\zxNCol]
+ & & & \zxN{}
+ \end{ZX} =
+ \begin{tikzpicture}[
+ baseline=(A.base)
+ ]
+ \node[inner sep=0pt](A){%
+ \begin{ZX}
+ &[\zxwCol] & \zxZ{\pi} \ar[dd,3 vdots] \rar &[\zxwCol] \zxN{} \\[\zxNCol]
+ \zxN{} \rar & \zxX-{\alpha} \ar[ru,N'-] \ar[rd,N.-] & \\[\zxNCol]
+ & & \zxZ{\pi} \rar & \zxN{}
+ \end{ZX}
+ };
+ \node[inner sep=0pt,below=\zxDefaultColumnSep of A](B){
+ \begin{ZX}
+ \zxOneOverSqrtTwo{} & \zxX{\alpha} \rar & \zxZ{\pi}
+ \end{ZX}
+ };
+ \end{tikzpicture}
+\end{equation*}
+\end{codeexample}
+
\subsection{Further customization}
You can further customize your drawings using any functionality from \tikzname{} and |tikz-cd| (but it is of course at your own risk). For instance, we can change the separation between rows and/or columns for a whole picture (but prefer to use |zx row sep| as it also updates pre-configured column spaces):
@@ -2558,6 +4702,18 @@ You can further customize your drawings using any functionality from \tikzname{}
\zxN{} \rar & \zxFracZ-{\pi}{4} \ar[ru,('] \ar[rr,o.] & & \zxX{} \ar[rr] & & \zxN{}
\end{ZX}
\end{codeexample}
+You can also use the tikz |between origins| option in order to specify the distance between the center of the rows and not between their borders. This is particularly practical when gates have different heights, or if you want to compare two diagram with different content (you might also want to use something like |mbr=1.5| to set the math baseline between two lines):
+\begin{codeexample}[width=0pt]
+$\begin{ZX}[circuit, row sep={.6cm,between origins}]
+\rar & \zxCross{} \rar \dar & \\
+\rar & \zxCross{} \rar &
+\end{ZX} =
+\begin{ZX}[circuit, row sep={.6cm,between origins}]
+\rar & \zxN{} \ar[rd,s] & \zxN{} \rar & \\
+\rar & \zxN{} \ar[ru,s] & \zxN{} \rar &
+\end{ZX}$
+\end{codeexample}
+
Or we can define our own style to create blocks:
{\catcode`\|=12 % Ensures | is not anymore \verb|...|
\begin{codeexample}[width=0pt]
@@ -2593,7 +4749,7 @@ We can also use for instance |fit|, |alias|, |execute at end picture| and layers
fill=blue!50!white,
opacity=.5,
fit=(cnot1)(cnot2), %% position of the node, thanks fit library
- "\textsc{cnot}" above %% Adds label, thanks quote library
+ "\textsc{cnot}" {above, inner sep=1mm} %% Adds label, thanks quote library. Not sure why, inner sep is set to 0 when using tikz "external" library.
] {};
}
]
@@ -2601,39 +4757,65 @@ We can also use for instance |fit|, |alias|, |execute at end picture| and layers
\zxNone{} \rar & \zxX[alias=cnot2]{} \rar & \zxNone{}\\
\end{ZX}
\end{codeexample}
+Because this code is quite lengthy and useful, we provide in \cref{subsec:decoration} a shorter syntax.
}
-This can also be used to fake multi-columns nodes (I need to check later if I can facilitate this kind of operation from the library directly):
+
+You can also use other libraries, in particular |nfold| can be practical to insert many wires at once (note that you need a recent version since it was introduced in CTAN 2023, or you need to manually install the library):
{\catcode`\|=12 % Ensures | is not anymore \verb|...|
-\begin{codeexample}[width=3cm]
-% \usetikzlibrary{fit}
-\tikzset{
- my box/.style={inner sep=4pt, draw, thick, fill=white,anchor=center},
-}
-\begin{ZX}[
- execute at end picture={
- \node[
- my box,
- node on layer=box, %% Ensure the node is above the wires
- fit=(f1)(f2), %% position of the node, thanks fit library
- label={[node on layer=box]center:$f$},
- ] {};
- }
- ]
- \zxNoneDouble+[alias=f1]{} \rar &[1mm] |[my box]| g \rar & \zxNone{}\\
- \zxNoneDouble+[alias=f2]{} \rar &[1mm] \zxZ{} \rar & \zxNone{}\\
+\begin{codeexample}[width=0pt]
+% \usetikzlibrary{nfold} % needs very recent CTAN > 2023, or manually copy the .tex files
+\begin{ZX}[circuit]
+ \rar[scaling nfold=5]
+ & \zxGate{X} \rar[rd, line join=round, double distance=2pt, scaling nfold=3,--|] & \\
+ & & \zxGate{Y}
\end{ZX}
\end{codeexample}
}
-\section{Futur works}
-There is surely many things to improve in this library, and given how young it is there is surely many undiscovered bugs. So feel free to propose ideas or report bugs \mylink{https://github.com/leo-colisson/zx-calculus/issues}{one the github page}. I also would like to provide externalization to boost compilation time. But |tikz-cd| is not really compatible with externalization, so it would need a bit of work (of course, you can always compile your images in a separate file, but it is cumbersome). See potential solutions here: \mylink{https://tex.stackexchange.com/questions/171931/}{here}. The intersections code is also quite slow, so I would be curious to check if I can optimize it (the first goal was to make it work). I should also work on the compatibility with tikzit (basically just write tikz configuration files that you can just use and document how to use tikzit with it), or even write a dedicated graphical tool (why not based on tikzit itself, or \mylink{https://tikzcd.yichuanshen.de/}{this tool}). I also want to find a nicer way to merge cells (for now I propose to use the |fit| library but it's not very robust against overlays) and to nest ZX diagrams (see ). And of course fix typos in the documentation and write other styles, including notations not specific to ZX-calculus. Feel free to submit Pull Requests to solve that!
+\section{Future works}
+
+There is surely many things to improve in this library, and given how young it is there is surely many undiscovered bugs. So feel free to propose ideas or report bugs \mylink{https://github.com/leo-colisson/zx-calculus/issues}{one the github page}. The intersections code is also quite slow, so I would be curious to check if I can optimize it (the first goal was to make it work). I should also work on the compatibility with tikzit (basically just write tikz configuration files that you can just use and document how to use tikzit with it), or even write a dedicated graphical tool (why not based on tikzit itself, or \mylink{https://tikzcd.yichuanshen.de/}{this tool}). I also want to find a nicer way to merge cells (for now I propose to use the |fit| library but it's not very robust against overlays) and to nest ZX diagrams. And of course fix typos in the documentation and write other styles, including notations not specific to ZX-calculus. Feel free to submit Pull Requests to solve that, or to submit bug reports to explain uncovered use-cases!
\section{Acknowledgement}
-I'm very grateful of course to everybody that worked on these amazing field which made diagramatic quantum computing possible, and to the many StackExchange users that helped me to understand a bit more \LaTeX{} and \tikzname{} (sorry, I don't want to risk an incomplete list, but many thanks to egreg, David Carlisle, cfr, percusse, Andrew Stacey, Henri Menke, SebGlav\dots{}). I also thank Robert Booth for making me realize how my old style was bad, and for giving advices on how to improve it. Thanks to John van de Wetering, whose style has also been a source of inspiration.
+I'm very grateful of course to everybody that worked on these amazing field which made diagramatic quantum computing possible, and to the many StackExchange users that helped me to understand a bit more \LaTeX{} and \tikzname{} (sorry, I don't want to risk an incomplete list, but many thanks to egreg, David Carlisle, cfr, percusse, Andrew Stacey, Henri Menke, SebGlav, Qrrbrbirlbel\dots{}). I also thank Robert Booth for making me realize how my old style was ugly, and for giving advices on how to improve it. Thanks to John van de Wetering and Alastair Kay (author of Quantikz), whose styles have also been a source of inspiration~\cite{van20_ZXcalculusWorkingQuantum}, and to Augusto Stoffel for the great tikzcd package on which this library is built.
+
+\section{Changelog}
+
+\begin{itemize}
+\item 2023/09/26:
+ Many updates in the past months:
+ \begin{itemize}
+ \item Custom nodes are made easy
+ \item Multi-gates nodes and many circuit-related functions
+ \item Added |post arrow style if start node| and other similar commands
+ \item updated the doc to use the latest version of robust-externalize that is much simpler to use now\dots
+ \item Some nodes can also now be usable outside tikzcd, but I've not tried (I should provide more options for this).
+ \item Group gates
+ \item
+ \end{itemize}
+\item 2022/02/09:
+ \begin{itemize}
+ \item Added compatibility with external tikz library
+ \item More robust handling of |&|: align and macros does not need |\&| anymore.
+ \item |\&| in |\zxSaveDiagram| is replaced with |&|. This introduces a small backward incompatibility, but hey, I said it was still subject to changes :-)
+ \end{itemize}
+\end{itemize}
+
+\section{TODO}
+\begin{itemize}
+\item I think that some anchors are not properly configured in stuff like |\zxBox| etc, so a nice sanity check should be done
+\item Clean the code, eventually
+\item Consider subnodes as anchors (fake center etc)
+\item more circuit related stuff
+\item multigate invisible element
+\item curly braces made easy
+\item lstick
+\end{itemize}
\printindex
+\printbibliography[heading=bibintoc]
\end{document}