% Eight examples in the manner of The TeXbook: each adds one idea to the
% one before it, dangerous bends mark skippable depth, one refusal is
% shown on purpose, and the exercises' answers close the chapter.  Every
% object is named in the tensor-network community's own vocabulary
% (arXiv:2011.12127) before its spelling appears.
\section{Tutorial}\label{ch:tutorial}

This chapter is an invitation to learn \pkg{} by doing.  We shall climb a
gentle ladder of eight examples, starting from a single matrix product state
(MPS) and culminating in the expectation value of a two-dimensional PEPS state.
In the spirit of \emph{The \TeX{}book}, each step introduces exactly one new idea
built upon the ones before it.  Along the way, we shall meet the familiar
objects of tensor-network theory---matrix product states, transfer operators,
gauge transformations, 2D PEPS sheets, and double-layer norm
networks---calling each by its standard mathematical name in the quantum
information and condensed matter literature (e.g. arXiv:2011.12127) as it
arrives.

The package loads the diagram language automatically.  The examples use its
current commands and keys throughout.

Every code example is complete: paste it into any document that loads \pkg{}
and it will compile exactly as printed.  As you read each example, look out
for the little ``dangerous bend'' signs (\textdbend) in the margin: they flag
technical subtleties and deeper design insights that you may safely skip on a
first reading.  At the end of each section, you will find short exercises to
test your understanding; their answers await you at the end of the chapter.
(Try to solve them before looking!)

\subsection{A chain of tensors}

Let us begin with the foundation of one-dimensional tensor networks: the
matrix product state (MPS).  Each lattice site carries one tensor $A$, with two
horizontal virtual indices of bond dimension $D$ (or $\chi$) that contract with
adjacent sites, and one vertical physical index of dimension $d$ corresponding
to the local Hilbert space.  Here is a three-site segment:

\begin{tnexample}[
  label={tnex:tut-word},
  formula={(A^{i_1}A^{i_2}A^{i_3})_{\alpha\beta}},
  caption={three sites of a matrix product state},
  index={The horizontal bonds are summed virtual indices.  The two stubs
    are the open matrix indices $\alpha$ and $\beta$; each upward leg is
    one physical index.},
  signature={kernel-boundary|signature=open:e, open:w, phys:n, phys:n, phys:n}]
% Formula: (A^{i_1} A^{i_2} A^{i_3})_{alpha beta}
% Ink: bonds contract; typed ports declare the open indices.
\begin{tenkz}[cols=3]
  \tn[ports={180:virtual:$\alpha$, 0:virtual, 90:physical:$i_1$}]{A} &
  \tn[ports={180:virtual, 0:virtual, 90:physical:$i_2$}]{A} &
  \tn[ports={180:virtual, 0:virtual:$\beta$, 90:physical:$i_3$}]{A}
\end{tenkz}
\end{tnexample}

There!  You have just typeset your first matrix product state contraction
$(A^{i_1}A^{i_2}A^{i_3})_{\alpha\beta}$.  Notice how cleanly the code
expresses the underlying mathematics.  The \tnenv{tenkz} environment holds one
typed tensor network in a single, coherent frame: \tnkey{cols=3} establishes
three lattice sites along the 1D chain, each \tncmd{tn} declares a local tensor
at that site, and the familiar \verb|&| alignment tab advances to the next site.
Because adjacent sites contract by default---forming the internal virtual
bonds---the only indices you need to declare explicitly are the open ones: the
boundary virtual indices $\alpha,\beta$ and the physical legs $i_1,i_2,i_3$.

The \tnkey{ports=} key defines each port around an atom's perimeter and
optionally attaches an index label.  (A port is simply the geometric anchor
where an index wire meets its tensor node.)  A typed port that finds no partner
cell to contract with remains an open physical or virtual index.  Notice also
the marginal annotation: during compilation, \pkg{} audits the picture and
writes its resolved boundary signature into the \tnfile{.tnlog} event stream:
two virtual boundary stubs, three physical legs, and nothing you did not ask
for.

\dbendpar Users of the \textsf{beamer} presentation package will be pleased to
learn that \pkg{} pictures require no special fuss.  Because \textsf{beamer}
scans a frame's body before typesetting, an alignment tab \verb|&| inside a
diagram reaches \pkg{} as an ordinary token.  The environment captures its body
and interprets the tab directly, so your diagrams compile happily inside
standard slides without needing the \texttt{[fragile]} option.

\tnexercise{ex:tut-matrix} Try drawing a single matrix $M$ by itself---one
tensor atom, both virtual indices open, with no physical leg---and determine
what boundary signature \pkg{} writes to the log.

\subsection{Layers and boundary policies}

Now let us add a second idea to our repertoire: rows represent layers.  Our
object of interest is the workhorse of matrix-product algorithms (such as DMRG
and TEBD), the transfer operator $\mathcal E_A(X)=\sum_i A^iXA^{i\dagger}$,
which sandwiches an input matrix $X$ on the virtual space between a ket layer
above and a bra layer below.

\begin{tnexample}[
  formula={\mathcal E_A(X)=\sum_i A^i X A^{i\dagger}},
  caption={the channel applied to $X$},
  index={$X$ closes the east input pair.  The west pair remains open because
    the output is a matrix; the vertical connection sums the physical
    index $i$.},
  signature={kernel-boundary|signature=open:w, open:w}]
% Formula: E_A(X) = sum_i A^i X A^{i dagger}.
% Boundary: the input closes east; the matrix output stays
% open west.
\begin{tenkz}[rows={ket,bra}, cols=1, west=open, east={cup=$X$}]
  \tn[label pos=90]{A} \\
  \tn[label pos=270]{$\overline{A}$}
\end{tenkz}
\end{tnexample}

Here \tnkey{rows=} declares a ket layer standing over a bra layer, and the
frame automatically contracts their facing physical ports---producing the
vertical bond that sums over the physical index $i$.  Notice that complex
conjugation is pure mathematics: $\overline{A}$ is an ordinary label name, not
a cryptic internal switch!

The perimeter sides declare boundary policy from a tidy four-word alphabet:
\tnval{open} mints legs and records them in the boundary signature;
\tnval{none} (the default) leaves a side unadorned; \tnval{trace} loops a row
back onto itself; and \tnval{cup} closes adjacent layers together.  In this
example, \tnkey{east=}\tnval{\{cup=\$X\$\}} closes the eastern pair through the
matrix $X$, while the western pair remains open, yielding a linear map on
virtual matrices---precisely matching the two-entry signature quoted in the
margin.

\dbendpar A labelled cup is what computer scientists call ``syntactic sugar'':
behind the scenes, \pkg{} expands it into an ordinary \tnval{cup} wire plus a
ring atom seated at its midpoint.  The kernel record stream never contains an
ad-hoc ``labelled cup'' entity, but only a wire named \tnval{cup-1-2} and an
atom on it.  Every convenience sugar row in the language registry defines its
canonical expansion this way, and authors who insist on absolute purity can
specify \tncmd{tnset}\tnval{\{strict\}} to reject sugar outright.

\tnexercise{ex:tut-transfer} Draw the full transfer matrix
$E=\sum_i A^i\otimes\overline{A^i}$ of the state---the map on the
$D^2$-dimensional doubled virtual space: a ket layer over a bra layer, with
the physical pair contracted and all four virtual ends left open.

\tnexercise{ex:tut-closed} A contraction loop with no tensor on it---the
spelling \verb|\tnwire[closed]{(1,1)}{(2,1)}|---refuses to compile.  Why?

\subsection{Boundary conditions: open, periodic, and closed}

A single row of matrices can represent three distinct mathematical objects
frequently encountered in tensor-network algorithms: an open matrix product
$(M_1M_2M_3)_{\alpha\beta}$ with free virtual boundary bonds, a finite chain
with trivial 1D boundary vectors where outer virtual bonds close without exposed
ink, and the periodic trace $\operatorname{tr}(M_1M_2M_3)$ representing a
state with periodic boundary conditions (PBC).  The convenient \tnkey{boundary=}
key sets both \tnkey{west=} and \tnkey{east=} policies simultaneously.  Watch
how easily its three settings produce all three objects from the very same row
of tensors:

\begin{tnmultiples}[
  formula={(M_1M_2M_3)_{\alpha\beta}},
  caption={one row, three boundary conditions},
  index={Left to right: the outer bonds close trivially and nothing is
    exposed; both ends open and the row is a matrix; the trace returns the
    row to itself and the picture is a scalar.  The quoted signature is the
    open panel's; the other two are empty.},
  signature={kernel-boundary|signature=open:e, open:w},
  variants={{boundary=none}{boundary=none},
            {boundary=open}{boundary=open},
            {boundary=periodic}{boundary=periodic}}]
% Formula: M_1 M_2 M_3 under three side policies.
\begin{tenkz}[rows={wire}, cols=3, variant]
  \tn{$M_1$} & \tn{$M_2$} & \tn{$M_3$}
\end{tenkz}
\end{tnmultiples}

This is a delightful demonstration of ``small multiples'' (in Edward Tufte's
sense): all three panels share identical code, varying only in the boundary
word beneath them.  The setting \tnval{none} explicitly spells the default---a
side that specifies no policy exposes no dangling ink, corresponding to a
finite chain whose outer boundary closes with trivial 1D boundary vectors.
The word \tnval{open} turns the row into an open matrix
$(M_1M_2M_3)_{\alpha\beta}$ with exposed boundary virtual bonds, while
\tnval{periodic} (convenient sugar for \tnkey{west=}\tnval{trace},
\tnkey{east=}\tnval{trace}) loops the virtual bond back upon itself to compute
the trace.  The atoms and internal bonds remain completely identical; only the
boundary signature moves!

\dbendpar A boundary leg appears only when it is declared.  The setting
\tnval{none} states the default; use \tnval{open} when the diagram should
expose an index.

\tnexercise{ex:tut-trace} Draw the coefficient of a periodic matrix product
state---the scalar $\operatorname{tr}(M_1M_2M_3)$---and state what boundary
signature it produces.

\subsection{Highlighting subsystems and regions}

In real-space renormalization group (RG) arguments, DMRG site-blocking, or
entanglement bipartition studies, one frequently groups several adjacent sites
into an effective block tensor $A^{[3]}$ or defines a subsystem $A$.  The
underlying tensor contraction does not change; instead, an annotation or
``mark'' speaks over the grouping.

\begin{tnexample}[
  formula={A^{[3]}=A^{i_1}A^{i_2}A^{i_3}},
  caption={blocking three sites},
  index={The bracket speaks from the south.  Box silhouettes keep the site
    names inside their measured ink.  The signature is Example \ref{tnex:tut-word}'s, unchanged: a
    mark owns no topology.},
  signature={kernel-boundary|signature=open:e, open:w, phys:n, phys:n, phys:n}]
% Formula: the blocked word A^{[3]}; the mark adds no index.
\begin{tenkz}[cols=3]
  \tn[skin=box, ports={180:virtual:$\alpha$, 0:virtual, 90:physical:$i_1$}]{A} &
  \tn[skin=box, ports={180:virtual, 0:virtual, 90:physical:$i_2$}]{A} &
  \tn[skin=box, ports={180:virtual, 0:virtual:$\beta$, 90:physical:$i_3$}]{A}
  \tnmark[form=bracket]{(1,1) .. (1,3)}{$A^{[3]}$}
\end{tenkz}
\end{tnexample}

The \tncmd{tnmark} command annotates a designated target without altering the
underlying network topology.  The target here is specified as a selector:
\tnval{(1,1)} names a cell in the frame, and the two-dot range \tnval{(1,1) ..
(1,3)} selects all records spanning between the two cells in sequence.  A
bracket mark with no side specified naturally speaks from the south, where a
horizontal brace under a formula belongs.  Observe the margin note: the boundary
signature is entirely identical to Example~\ref{tnex:tut-word}!  Marks own
annotations, never topology: if you delete every mark from a picture, not a
single tensor contraction changes.

\dbendpar Notice that the span is written with two dots (\texttt{..}), rather
than a hyphen.  This is because internal generated record names already use
hyphens (for instance, a cluster atom is named \tnval{a-2-2}); using two dots
keeps ranges visually unambiguous and easy for \TeX{} to parse.

\tnexercise{ex:tut-enclosure} Try restating the same blocked run using a tinted
enclosure whose label is placed below the bounding contour.

\subsection{Diagrammatic equations and verification}

We now arrive at one of the crowning features of \pkg{}: composing multiple
diagrams into an equation, and having \TeX{} verify that index contractions
remain balanced across equality signs!  Our example is the fundamental gauge
freedom of matrix product states: two sets of tensors $A$ and $B$, related by
an invertible gauge matrix $X$ via $B^i = X A^i X^{-1}$, generate the exact same
quantum state.

\begin{tnexample}[
  label={tnex:tut-eq},
  formula={B^i=XA^iX^{-1}},
  caption={a gauge identity, audited},
  index={The rings are matrices on the wire and add no indices.  Both
    panels expose one west stub, one east stub, and one physical leg, so
    the audit records the relation as equal.},
  signature={check|scope=1|relation=1|result=equal|signature=open:e, open:w, phys:n}]
% Formula: B^i = X A^i X^{-1}; one relation, audited.
\[
\begin{tenkzeq}[check=signature]
  \begin{tenkz}[cols=1]
    \tn[ports={180:virtual, 0:virtual, 90:physical:$i$}]{B}
  \end{tenkz}
  =
  \begin{tenkz}[cols=3]
    \tn[skin=ring, ports={180:virtual, 0:virtual}]{X} &
    \tn[ports={180:virtual, 0:virtual, 90:physical:$i$}]{A} &
    \tn[skin=ring, ports={180:virtual, 0:virtual}]{X^{-1}}
  \end{tenkz}
\end{tenkzeq}
\]
\end{tnexample}

The \tnenv{tenkzeq} environment neatly balances tensor diagrams on either side
of standard mathematical relation symbols under a unified scale and baseline.
Even better, it audits!  In tensor network theory, a diagrammatic identity
requires both sides of an equality to match in tensor rank and index structure:
the same set of open physical and virtual indices.  With
\tnkey{check=}\tnval{signature} active (which is the default setting), \pkg{}
verifies this balance automatically, recording the \tnval{check} event in the
\tnfile{.tnlog} stream.  This checks boundary index compatibility: both sides
must carry matching physical and virtual open ports.  The mathematical identity
itself remains the author's responsibility.

What happens when an equation fails the audit?  Let us deliberately omit the
physical leg from tensor $B$, and see how the compiler responds:

\begin{tnrefusal}[
  caption={the audit catches a dropped leg},
  index={The left panel now exposes two indices, the right three.  The
    correction is one token: restore the port 90:physical:$i$ on $B$.},
  diagnostic={[TKZ-EQ-SIGNATURE] sides 1 and 2 expose unequal boundaries:
    (open:e, open:w) versus (open:e, open:w, phys:n).}]
% Refused: B lost its physical leg, so the relation's two
% sides no longer expose the same boundary.
\[
\begin{tenkzeq}[check=signature]
  \begin{tenkz}[cols=1]
    \tn[ports={180:virtual, 0:virtual}]{B}
  \end{tenkz}
  =
  \begin{tenkz}[cols=3]
    \tn[skin=ring, ports={180:virtual, 0:virtual}]{X} &
    \tn[ports={180:virtual, 0:virtual, 90:physical:$i$}]{A} &
    \tn[skin=ring, ports={180:virtual, 0:virtual}]{X^{-1}}
  \end{tenkz}
\end{tenkzeq}
\]
\end{tnrefusal}

Don't be alarmed by compiler refusals!  Think of them as a vigilant proofreader
standing by your shoulder.  The diagnostic code names the exact check that
failed, and prints both boundary signatures side by side so the missing index
is immediately apparent.  The remedy here is simply to restore the port
\tnval{90:physical:\$i\$} to tensor~$B$.

\ddbendpar Mathematical relations are one of three joiner classes in
\tnenv{tenkzeq}.  A summation also requires matching signatures; a product, by
contrast, contracts facing cuts (eastern entries of the left factor cancelling
western entries of the right) and exposes the remainder.  Should you ever need
to state an equality where the two sides are legitimately unequal for reasons
outside the diagram (such as an implicit projection), you can record an explicit
opt-out using \tnval{off=\{<relation>: <reason>\}}.  The waiver is faithfully
logged to the event stream, ensuring that the audit cannot be silenced
covertly.

\tnexercise{ex:tut-checkword} Why does the spelling
\tnkey{check=}\tnval{\{signature=false\}} trigger a refusal?

\subsection{Two-dimensional lattices and PEPS}

Now that we have explored one-dimensional chains, we are ready to step into
the second dimension.  Our model object is the projected entangled pair state
(PEPS), which represents the wavefunction $\lvert\psi(A)\rangle$
of a two-dimensional quantum lattice system (such as a 2D spin model): one
five-index tensor $A$ per site, four virtual indices of bond dimension $D$
contracted with its four planar nearest neighbours, and one physical index of
local Hilbert space dimension $d$ standing perpendicular to the sheet.

\begin{tnexample}[
  label={tnex:tut-peps},
  formula={\lvert\psi(A)\rangle},
  caption={a PEPS on a $3\times3$ patch},
  index={Every dot is the same tensor $A$.  The in-sheet bonds are the
    contracted virtual indices; each transverse leg is one physical
    index, and the signature lists the nine of them.},
  signature={kernel-boundary|signature=phys:n, phys:n, phys:n, phys:n,
    phys:n, phys:n, phys:n, phys:n, phys:n}]
% Formula: the PEPS |psi(A)> generated by one tensor A.
% Ink: in-sheet bonds contract; each transverse leg is one
% physical index.
\begin{tenkz}[lattice={3x3}, frame=plane, physical=up]
  \tn{} & \tn{} & \tn{} \\
  \tn{} & \tn{} & \tn{} \\
  \tn[label pos=225]{A} & \tn{} & \tn{}
\end{tenkz}
\end{tnexample}

Just two concise options bring this two-dimensional sheet onto the page.  The
option \tnkey{lattice=}\tnval{\{3x3\}} is convenient shorthand for three rows
of three sites each, whose cells contract with their neighbours just as
chain cells do---these form the in-plane virtual bonds mediating 2D entanglement.
Next, \tnkey{frame=}\tnval{plane} projects the grid into perspective, while
\tnkey{physical=}\tnval{up} sprouts one physical leg per site along the
plane's transverse axis, pointing vertically on the page into the local Hilbert
space.  Because no boundary policy is stated on the perimeter, no virtual index
is exposed: the patch has open boundary conditions, and its boundary signature
lists exactly the nine physical legs of the state.

\dbendpar A projected plane possesses three spatial directions, but only two
lie within the sheet itself.  Specifying \tnval{ports=\{90:physical\}} on a
planar atom refers to the in-sheet north face, not the upward transverse leg;
the transverse physical axis is governed through the picture policy.  A PEPS
tensor is described by four numeric planar ports plus the frame policy---never
by an artificial fifth angle attempting to fake the 3D projection.

\tnexercise{ex:tut-pepstensor} Try drawing a single PEPS tensor by itself---the
five-index $A^{i}_{\,uldr}$: four open virtual ports labelled $u$, $l$, $d$,
$r$ in the sheet, and the physical leg pointing above.

\subsection{Planar projections and viewing angles}

The very same sheet of tensors can represent four fundamental concepts of the
two-dimensional literature, selected by a single enumeration key: a fully
contracted network computes a classical partition function $Z$ or scalar
overlap; physical legs pointing up define the quantum ket state
$\lvert\psi\rangle$; physical legs pointing down yield the conjugate bra
$\langle\psi\rvert$; and physical legs extending in both directions produce a
Projected Entangled Pair Operator (PEPO) $O$ representing a 2D Hamiltonian or
density matrix.

\begin{tnmultiples}[
  formula={Z,\;\lvert\psi\rangle,\;\langle\psi\rvert,\;O},
  caption={one sheet, four readings},
  index={Left to right: no physical legs, a fully contracted scalar;
    legs up, the state; legs down, its conjugate; legs both ways, the
    PEPS operator.  The quoted signature is the legs-up panel's.},
  signature={kernel-boundary|signature=phys:n, phys:n, phys:n, phys:n},
  variants={{physical=none}{physical=none},
            {physical=up}{physical=up},
            {physical=down}{physical=down},
            {physical=updown}{physical=updown}}]
% Formula: Z, |psi>, <psi|, O -- one sheet, four leg policies.
\begin{tenkz}[lattice={2x2}, frame=plane, variant]
  \tn{} & \tn{} \\
  \tn{} & \tn{}
\end{tenkz}
\end{tnmultiples}

Here again we see the elegance of small multiples: the four panels share every
token of input except the policy key beneath them.  Moreover, the boundary
signature distinguishes a ket from a bra even before the diagram is rendered: a
leg extending above the sheet logs \tnval{phys:n}, while one extending below
logs \tnval{phys:s}.  The event stream tells them apart immediately, and the
PEPO panel exposes both lists simultaneously.

\tnexercise{ex:tut-torus} A PEPS with periodic boundary conditions naturally
lives on a torus.  The single key \tnkey{surface=}\tnval{torus} wraps all four
sides of the patch---convenient sugar for \tnval{trace} on each of
\tnkey{west=}, \tnkey{east=}, \tnkey{north=}, and \tnkey{south=}.  What does
this change in the boundary signature of Example~\ref{tnex:tut-peps}, and what
does it change in the network?

\subsection{Double layers and expectation values}

Virtually every expectation value or correlation function in the PEPS
literature is computed within the ``double layer'': a conjugate bra sheet laid
atop the ket state, with each site's physical index contracted with its conjugate
partner to yield an effective 2D network with squared bond dimension $D^2$.  The
norm $\langle\psi|\psi\rangle$ is simply the double layer with no operator
inserted between them:

\begin{tnexample}[
  label={tnex:tut-doublelayer},
  formula={\langle\psi|\psi\rangle},
  caption={the norm as a double layer},
  index={Two $2\times2$ sheets in one frame: $A$ marks the ket sheet,
    $\overline{A}$ the bra copy above it.  Each short diagonal is one
    ket--bra physical contraction; nothing stays open, and the empty
    signature says scalar.},
  signature={kernel-boundary|signature=}]
% Formula: <psi|psi> -- the bra sheet contracted onto the
% ket sheet through every physical index.
\begin{tenkz}[lattice={2x2}, planes, bonds=none]
  \tn[at=(2,1,1), label pos=225]{A}
  \tn[at=(1,2,2), label pos=45]{$\overline{A}$}
  % ket-sheet virtual bonds
  \tnwire{(1,1,1)}{(1,2,1)} \tnwire{(2,1,1)}{(2,2,1)}
  \tnwire{(1,1,1)}{(2,1,1)} \tnwire{(1,2,1)}{(2,2,1)}
  % bra-sheet virtual bonds
  \tnwire{(1,1,2)}{(1,2,2)} \tnwire{(2,1,2)}{(2,2,2)}
  \tnwire{(1,1,2)}{(2,1,2)} \tnwire{(1,2,2)}{(2,2,2)}
  % ket-bra physical pairings
  \tnwire{(1,1,1)}{(1,1,2)} \tnwire{(1,2,1)}{(1,2,2)}
  \tnwire{(2,1,1)}{(2,1,2)} \tnwire{(2,2,1)}{(2,2,2)}
\end{tenkz}
\end{tnexample}

The key \tnval{planes} provides shorthand for a plane frame possessing a
two-member basis: sheet~1 for the ket, and sheet~2 for the bra.  Both sheets
inhabit a single coordinate frame, and every site is addressed as
\tnval{(r,c,sheet)}.  Because a multi-member basis does not guess your wiring,
we specify \tnkey{bonds=}\tnval{none} and declare each bond explicitly in the
body: eight in-sheet virtual bonds, followed by four vertical ket--bra
contractions.  Notice how cleanly \pkg{} handles these vertical wires: because
a member address names a lattice position rather than an explicit port, the
frame uses its knowledge of the transverse axis to type the wire as physical
automatically.

\dbendpar In projection, the two sheets naturally overlap, and several bond
lines pass near vertices of the opposite sheet.  Rest assured that nothing
contracts by accident: geometric coincidence in \TeX{} never creates an edge!
The only contractions that exist are the twelve wires explicitly declared in
the body.

\tnexercise{ex:tut-expectation} Now let us insert a local operator: the
expectation value $\langle\psi\rvert O\lvert\psi\rangle$ places a ring atom $O$
along one of the ket--bra pairing wires.  Name that pairing wire, and seat the
operator halfway along its length.

\subsection{Answers to the exercises}

\begin{tnexample}[
  answer={ex:tut-matrix},
  formula={M_{\alpha\beta}},
  index={Two typed ports with no partners: the matrix keeps two open
    virtual indices and nothing else.},
  signature={kernel-boundary|signature=open:e, open:w}]
% Formula: the matrix M with both virtual indices open.
\begin{tenkz}[cols=1]
  \tn[ports={180:virtual:$\alpha$, 0:virtual:$\beta$}]{M}
\end{tenkz}
\end{tnexample}

\begin{tnexample}[
  answer={ex:tut-transfer},
  formula={E=\sum_i A^i\otimes\overline{A^i}},
  index={The frame contracts the ket-bra physical pair; all four virtual
    ends stay open, so $E$ is a map on the doubled space.},
  signature={kernel-boundary|signature=open:e, open:e, open:w, open:w}]
% Formula: E = sum_i A^i tensor conj(A^i).
% Labels: automatic placement -- every face of the ket atom except the
% north one carries ink, so its name stands there.
\begin{tenkz}[rows={ket,bra}, cols=1, west=open, east=open]
  \tn{A} \\
  \tn{$\overline{A}$}
\end{tenkz}
\end{tnexample}

\tnanswer{ex:tut-closed} A closed wire represents a smooth, self-contained loop,
so it has no separate endpoints to specify; every open wire, by contrast,
connects exactly two points.  Specifying both at once is contradictory, and
\pkg{} catches it with the informative diagnostic code
\tnval{[TKZ-LANG-WIRE-ARITY]}: \emph{a closed wire takes no positional
ends; every other wire takes exactly two}.  Use \tnval{closed} when you want a
free loop, and specify two endpoints when you want a standard bond.

\begin{tnexample}[
  answer={ex:tut-trace},
  formula={\operatorname{tr}(M_1M_2M_3)},
  index={The trace returns the row to itself; no index is left open, and
    the empty signature says scalar.},
  signature={kernel-boundary|signature=}]
% Formula: tr(M_1 M_2 M_3); sugar: boundary=periodic
% expands to west=trace, east=trace.
\begin{tenkz}[rows={wire}, cols=3, boundary=periodic]
  \tn{$M_1$} & \tn{$M_2$} & \tn{$M_3$}
\end{tenkz}
\end{tnexample}

\begin{tnexample}[
  answer={ex:tut-enclosure},
  formula={A^{[3]}},
  index={The enclosure strokes the offset hull of the selection and tint
    lays ink over the paper inside it; the physical legs pierce the
    contour, and the signature still does not move.},
  signature={kernel-boundary|signature=open:e, open:w, phys:n, phys:n, phys:n}]
% Formula: the blocked word inside one tinted contour.
\begin{tenkz}[cols=3]
  \tn[skin=box, ports={180:virtual:$\alpha$, 0:virtual, 90:physical:$i_1$}]{A} &
  \tn[skin=box, ports={180:virtual, 0:virtual, 90:physical:$i_2$}]{A} &
  \tn[skin=box, ports={180:virtual, 0:virtual:$\beta$, 90:physical:$i_3$}]{A}
  \tnmark[form=enclosure, tint,
          label pos=270]{(1,1) .. (1,3)}{$A^{[3]}$}
\end{tenkz}
\end{tnexample}

\tnanswer{ex:tut-checkword} The audit deliberately refuses unrecognized
keywords rather than quietly ignoring them, because a check that fails silently
is an audit you believe is running when it is not!  The coded error is
\tnval{[TKZ-EQ-CHECK-WORD]}: \emph{the audit does not know
`signature=false'; check= states the audit (signature) and its recorded opt-outs
(off=\{<relation>: <reason>\})}.  The keyword \tnval{signature} names the
audit itself; it is not a boolean flag, and therefore takes no value.

\begin{tnexample}[
  answer={ex:tut-pepstensor},
  formula={A^{i}_{\,uldr}},
  index={Four open in-sheet virtual indices and one transverse physical
    leg: the five-index PEPS tensor.  The two receding faces expose
    their in-sheet bearings in the signature.},
  signature={kernel-boundary|signature=open:233.130102,
    open:53.130102, open:e, open:w, phys:n}]
% Formula: the five-index PEPS tensor A^i_{uldr}.
\begin{tenkz}[rows={wire}, cols=1, frame=plane,
              bonds=none, physical=up]
  \tn[ports={0:virtual:$r$, 90:virtual:$u$,
             180:virtual:$l$, 270:virtual:$d$},
      label pos=315]{A}
\end{tenkz}
\end{tnexample}

\tnanswer{ex:tut-torus} The boundary signature does not change at all, but six
new wrap wires appear in the diagram.  Because each \tnval{trace} closes
in-sheet virtual bonds that were never exposed on the perimeter, the boundary
signature continues to record nine physical legs.  Meanwhile, the network gains
one wrap wire per row and per column (\tnval{wrap-1} through \tnval{wrap-3} and
\tnval{wrap-col-1} through \tnval{wrap-col-3}), closing the flat patch into a
topological torus.  Always remember: the boundary signature records external
connections, not internal topology!  The open patch and the periodic state
expose identical boundary lists, yet represent fundamentally different networks.

\begin{tnexample}[
  answer={ex:tut-expectation},
  formula={\langle\psi\rvert O\lvert\psi\rangle},
  index={The ring stands halfway along the named ket--bra pairing: a
    one-site operator between the state and its conjugate.  The
    signature stays empty --- the expectation value is a scalar.},
  signature={kernel-boundary|signature=}]
% Formula: <psi|O|psi> -- O on one site's physical index.
\begin{tenkz}[lattice={2x2}, planes, bonds=none]
  \tnwire{(1,1,1)}{(1,2,1)} \tnwire{(2,1,1)}{(2,2,1)}
  \tnwire{(1,1,1)}{(2,1,1)} \tnwire{(1,2,1)}{(2,2,1)}
  \tnwire{(1,1,2)}{(1,2,2)} \tnwire{(2,1,2)}{(2,2,2)}
  \tnwire{(1,1,2)}{(2,1,2)} \tnwire{(1,2,2)}{(2,2,2)}
  \tnwire{(1,1,1)}{(1,1,2)} \tnwire{(1,2,1)}{(1,2,2)}
  \tnwire{(2,1,1)}{(2,1,2)}
  \tnwire[name=po]{(2,2,1)}{(2,2,2)}
  \tn[skin=ring, at=on po 0.5]{O}
\end{tenkz}
\end{tnexample}
