% language=uk

\environment luatex-style
\environment luatex-logos

\startcomponent luatex-math

\startchapter[reference=math,title={Math}]

The handling of mathematics in \LUATEX\ differs quite a bit from how \TEX82 (and
therefore \PDFTEX) handles math. First, \LUATEX\ adds primitives and extends some
others so that \UNICODE\ input can be used easily. Second, all of \TEX82's
internal special values (for example for operator spacing) have been made
accessible and changeable via control sequences. Third, there are extensions that
make it easier to use \OPENTYPE\ math fonts. And finally, there are some
extensions that have been proposed or considered in the past that are now added
to the engine.

\section{The current math style}

It is possible to discover the math style that will be used for a formula in an
expandable fashion (while the math list is still being read). To make this
possible, \LUATEX\ adds the new primitive: \type {\mathstyle}. This is a \quote
{convert command} like e.g. \type {\romannumeral}: its value can only be read,
not set.

\subsection{\type {\mathstyle}}

The returned value is between 0 and 7 (in math mode), or $-1$ (all other modes).
For easy testing, the eight math style commands have been altered so that the can
be used as numeric values, so you can write code like this:

\starttyping
\ifnum\mathstyle=\textstyle
    \message{normal text style}
\else \ifnum\mathstyle=\crampedtextstyle
    \message{cramped text style}
\fi \fi
\stoptyping

\subsection{\type {\Ustack}}

There are a few math commands in \TEX\ where the style that will be used is not
known straight from the start. These commands (\type {\over}, \type {\atop},
\type {\overwithdelims}, \type {\atopwithdelims}) would therefore normally return
wrong values for \type {\mathstyle}. To fix this, \LUATEX\ introduces a special
prefix command: \type {\Ustack}:

\starttyping
$\Ustack {a \over b}$
\stoptyping

The \type {\Ustack} command will scan the next brace and start a new math group
with the correct (numerator) math style.

\section{Unicode math characters}

Character handling is now extended up to the full \UNICODE\ range (the \type {\U}
prefix), which is compatible with \XETEX.

The math primitives from \TEX\ are kept as they are, except for the ones that
convert from input to math commands: \type {mathcode}, and \type {delcode}. These
two now allow for a 21-bit character argument on the left hand side of the equals
sign.

Some of the new \LUATEX\ primitives read more than one separate value. This is
shown in the tables below by a plus sign in the second column.

The input for such primitives would look like this:

\starttyping
\def\overbrace{\Umathaccent 0 1 "23DE }
\stoptyping

The altered \TEX82 primitives are:

\starttabulate[|l|l|r|c|l|r|]
\NC \bf primitive     \NC \bf min \NC \bf max \NC \kern 2em  \NC \bf min \NC \bf max \NC \NR
\NC \type {\mathcode} \NC 0       \NC 10FFFF  \NC =          \NC 0       \NC 8000    \NC \NR
\NC \type {\delcode}  \NC 0       \NC 10FFFF  \NC =          \NC 0       \NC FFFFFF  \NC \NR
\stoptabulate

The unaltered ones are:

\starttabulate[|l|l|r|]
\NC \bf primitive        \NC \bf min \NC \bf max \NC \NR
\NC \type {\mathchardef} \NC 0       \NC    8000 \NC \NR
\NC \type {\mathchar}    \NC 0       \NC    7FFF \NC \NR
\NC \type {\mathaccent}  \NC 0       \NC    7FFF \NC \NR
\NC \type {\delimiter}   \NC 0       \NC 7FFFFFF \NC \NR
\NC \type {\radical}     \NC 0       \NC 7FFFFFF \NC \NR
\stoptabulate

For practical reasons \type {\mathchardef} will silently accept values larger
that \type {0x8000} and interpret it as \type {\Umathcharnumdef}. This is needed
to satisfy older macro packages.

The following new primitives are compatible with \XETEX:

% somewhat fuzzy:

\starttabulate[|l|l|r|c|l|r|]
\NC \bf primitive                           \NC \bf min   \NC \bf max             \NC \kern 2em  \NC \bf min   \NC \bf max                    \NC \NR
\NC \type {\Umathchardef}                   \NC 0+0+0     \NC 7+FF+10FFFF\rlap{\high{1}}   \NC   \NC           \NC                            \NC \NR
\NC \type {\Umathcharnumdef}\rlap{\high{5}} \NC -80000000 \NC    7FFFFFFF\rlap{\high{3}}   \NC   \NC           \NC                            \NC \NR
\NC \type {\Umathcode}                      \NC 0         \NC      10FFFF                  \NC = \NC 0+0+0     \NC 7+FF+10FFFF\rlap{\high{1}} \NC \NR
\NC \type {\Udelcode}                       \NC 0         \NC      10FFFF                  \NC = \NC 0+0       \NC   FF+10FFFF\rlap{\high{2}} \NC \NR
\NC \type {\Umathchar}                      \NC 0+0+0     \NC 7+FF+10FFFF                  \NC   \NC           \NC                            \NC \NR
\NC \type {\Umathaccent}                    \NC 0+0+0     \NC 7+FF+10FFFF\rlap{\high{2,4}} \NC   \NC           \NC                            \NC \NR
\NC \type {\Udelimiter}                     \NC 0+0+0     \NC 7+FF+10FFFF\rlap{\high{2}}   \NC   \NC           \NC                            \NC \NR
\NC \type {\Uradical}                       \NC 0+0       \NC   FF+10FFFF\rlap{\high{2}}   \NC   \NC           \NC                            \NC \NR
\NC \type {\Umathcharnum}                   \NC -80000000 \NC    7FFFFFFF\rlap{\high{3}}   \NC   \NC           \NC                            \NC \NR
\NC \type {\Umathcodenum}                   \NC 0         \NC      10FFFF                  \NC = \NC -80000000 \NC    7FFFFFFF\rlap{\high{3}} \NC \NR
\NC \type {\Udelcodenum}                    \NC 0         \NC      10FFFF                  \NC = \NC -80000000 \NC    7FFFFFFF\rlap{\high{3}} \NC \NR
\stoptabulate

Specifications typically look like:

\starttyping
\Umathchardef\xx="1"0"456
\Umathcode   123="1"0"789
\stoptyping

Note 1: The new primitives that deal with delimiter|-|style objects do not set up a
\quote {large family}. Selecting a suitable size for display purposes is expected
to be dealt with by the font via the \type {\Umathoperatorsize} parameter (more
information can be found in a following section).

Note 2: For these three primitives, all information is packed into a single
signed integer. For the first two (\type {\Umathcharnum} and \type
{\Umathcodenum}), the lowest 21 bits are the character code, the 3 bits above
that represent the math class, and the family data is kept in the topmost bits
(This means that the values for math families 128--255 are actually negative).
For \type {\Udelcodenum} there is no math class. The math family information is
stored in the bits directly on top of the character code. Using these three
commands is not as natural as using the two- and three|-|value commands, so
unless you know exactly what you are doing and absolutely require the speedup
resulting from the faster input scanning, it is better to use the verbose
commands instead.

Note 3: The \type {\Umathaccent} command accepts optional keywords to control
various details regarding math accents. See \in {section} [mathacc] below for
details.

New primitives that exist in \LUATEX\ only (all of these will be explained
in following sections):

\starttabulate[|l|l|l|l|]
\NC \bf primitive         \NC \bf value range (in hex) \NC \NR
\NC \type {\Uroot}           \NC 0+0--FF+10FFFF$^2$       \NC \NR
\NC \type {\Uoverdelimiter}  \NC 0+0--FF+10FFFF$^2$       \NC \NR
\NC \type {\Uunderdelimiter} \NC 0+0--FF+10FFFF$^2$       \NC \NR
\NC \type {\Udelimiterover}  \NC 0+0--FF+10FFFF$^2$       \NC \NR
\NC \type {\Udelimiterunder} \NC 0+0--FF+10FFFF$^2$       \NC \NR
\stoptabulate

\section{Cramped math styles}

\LUATEX\ has four new primitives to set the cramped math styles directly:

\starttyping
\crampeddisplaystyle
\crampedtextstyle
\crampedscriptstyle
\crampedscriptscriptstyle
\stoptyping

These additional commands are not all that valuable on their own, but they come
in handy as arguments to the math parameter settings that will be added shortly.

In Eijkhouts \quotation {\TEX\ by Topic} the rules for handling styles in scripts
are described as follows:

\startitemize
\startitem
    In any style superscripts and subscripts are taken from the next smaller style.
    Exception: in display style they are taken in script style.
\stopitem
\startitem
    Subscripts are always in the cramped variant of the style; superscripts are only
    cramped if the original style was cramped.
\stopitem
\startitem
    In an \type {..\over..} formula in any style the numerator and denominator are
    taken from the next smaller style.
\stopitem
\startitem
    The denominator is always in cramped style; the numerator is only in cramped
    style if the original style was cramped.
\stopitem
\startitem
    Formulas under a \type {\sqrt} or \type {\overline} are in cramped style.
\stopitem
\stopitemize

In \LUATEX\ one can set the styles in more detail which means that you sometimes
have to set both normal and cramped styles to get the effect you want. If we
force styles in the script using \type {\scriptstyle} and \type {\crampedscriptstyle}
we get this:

\startbuffer[demo]
\starttabulate
\NC default       \NC $b_{x=xx}^{x=xx}$ \NC \NR
\NC script        \NC $b_{\scriptstyle x=xx}^{\scriptstyle x=xx}$ \NC \NR
\NC crampedscript \NC $b_{\crampedscriptstyle x=xx}^{\crampedscriptstyle x=xx}$ \NC \NR
\stoptabulate
\stopbuffer

\getbuffer[demo]

Now we set the following parameters

\startbuffer[setup]
\Umathordrelspacing\scriptstyle=30mu
\Umathordordspacing\scriptstyle=30mu
\stopbuffer

\typebuffer[setup]

This gives:

\start\getbuffer[setup,demo]\stop

But, as this is not what is expected (visually) we should say:

\startbuffer[setup]
\Umathordrelspacing\scriptstyle=30mu
\Umathordordspacing\scriptstyle=30mu
\Umathordrelspacing\crampedscriptstyle=30mu
\Umathordordspacing\crampedscriptstyle=30mu
\stopbuffer

\typebuffer[setup]

Now we get:

\start\getbuffer[setup,demo]\stop

\section{Math parameter settings}

In \LUATEX, the font dimension parameters that \TEX\ used in math typesetting are
now accessible via primitive commands. In fact, refactoring of the math engine
has resulted in many more parameters than were accessible before.

\starttabulate
\NC \bf primitive name               \NC \bf description \NC \NR
\NC \type {\Umathquad}               \NC the width of 18 mu's \NC \NR
\NC \type {\Umathaxis}               \NC height of the vertical center axis of
                                         the math formula above the baseline \NC \NR
\NC \type {\Umathoperatorsize}       \NC minimum size of large operators in display mode \NC \NR
\NC \type {\Umathoverbarkern}        \NC vertical clearance above the rule \NC \NR
\NC \type {\Umathoverbarrule}        \NC the width of the rule \NC \NR
\NC \type {\Umathoverbarvgap}        \NC vertical clearance below the rule \NC \NR
\NC \type {\Umathunderbarkern}       \NC vertical clearance below the rule \NC \NR
\NC \type {\Umathunderbarrule}       \NC the width of the rule \NC \NR
\NC \type {\Umathunderbarvgap}       \NC vertical clearance above the rule \NC \NR
\NC \type {\Umathradicalkern}        \NC vertical clearance above the rule \NC \NR
\NC \type {\Umathradicalrule}        \NC the width of the rule \NC \NR
\NC \type {\Umathradicalvgap}        \NC vertical clearance below the rule \NC \NR
\NC \type {\Umathradicaldegreebefore}\NC the forward kern that takes place before placement of
                                         the radical degree \NC \NR
\NC \type {\Umathradicaldegreeafter} \NC the backward kern that takes place after placement of
                                         the radical degree \NC \NR
\NC \type {\Umathradicaldegreeraise} \NC this is the percentage of the total height and depth of
                                         the radical sign that the degree is raised by; it is
                                         expressed in \type {percents}, so 60\% is expressed as the
                                         integer $60$ \NC \NR
\NC \type {\Umathstackvgap}          \NC vertical clearance between the two
                                         elements in a \type {\atop} stack \NC \NR
\NC \type {\Umathstacknumup}         \NC numerator shift upward in \type {\atop} stack \NC \NR
\NC \type {\Umathstackdenomdown}     \NC denominator shift downward in \type {\atop} stack \NC \NR
\NC \type {\Umathfractionrule}       \NC the width of the rule in a \type {\over} \NC \NR
\NC \type {\Umathfractionnumvgap}    \NC vertical clearance between the numerator and the rule \NC \NR
\NC \type {\Umathfractionnumup}      \NC numerator shift upward in \type {\over} \NC \NR
\NC \type {\Umathfractiondenomvgap}  \NC vertical clearance between the denominator and the rule \NC \NR
\NC \type {\Umathfractiondenomdown}  \NC denominator shift downward in \type {\over} \NC \NR
\NC \type {\Umathfractiondelsize}    \NC minimum delimiter size for \type {\...withdelims} \NC \NR
\NC \type {\Umathlimitabovevgap}     \NC vertical clearance for limits above operators \NC \NR
\NC \type {\Umathlimitabovebgap}     \NC vertical baseline clearance for limits above operators \NC \NR
\NC \type {\Umathlimitabovekern}     \NC space reserved at the top of the limit \NC \NR
\NC \type {\Umathlimitbelowvgap}     \NC vertical clearance for limits below operators \NC \NR
\NC \type {\Umathlimitbelowbgap}     \NC vertical baseline clearance for limits below operators \NC \NR
\NC \type {\Umathlimitbelowkern}     \NC space reserved at the bottom of the limit \NC \NR
\NC \type {\Umathoverdelimitervgap}  \NC vertical clearance for limits above delimiters \NC \NR
\NC \type {\Umathoverdelimiterbgap}  \NC vertical baseline clearance for limits above delimiters \NC \NR
\NC \type {\Umathunderdelimitervgap} \NC vertical clearance for limits below delimiters \NC \NR
\NC \type {\Umathunderdelimiterbgap} \NC vertical baseline clearance for limits below delimiters \NC \NR
\NC \type {\Umathsubshiftdrop}       \NC subscript drop for boxes and subformulas \NC \NR
\NC \type {\Umathsubshiftdown}       \NC subscript drop for characters \NC \NR
\NC \type {\Umathsupshiftdrop}       \NC superscript drop (raise, actually) for boxes and subformulas \NC \NR
\NC \type {\Umathsupshiftup}         \NC superscript raise for characters \NC \NR
\NC \type {\Umathsubsupshiftdown}    \NC subscript drop in the presence of a superscript \NC \NR
\NC \type {\Umathsubtopmax}          \NC the top of standalone subscripts cannot be higher than this
                                         above the baseline \NC \NR
\NC \type {\Umathsupbottommin}       \NC the bottom of standalone superscripts cannot be less than
                                         this above the baseline \NC \NR
\NC \type {\Umathsupsubbottommax}    \NC the bottom of the superscript of a combined super- and subscript
                                         be at least as high as this above the baseline \NC \NR
\NC \type {\Umathsubsupvgap}         \NC vertical clearance between super- and subscript \NC \NR
\NC \type {\Umathspaceafterscript}   \NC additional space added after a super- or subscript \NC \NR
\NC \type {\Umathconnectoroverlapmin}\NC minimum overlap between parts in an extensible recipe \NC \NR
\stoptabulate

Each of the parameters in this section can be set by a command like this:

\starttyping
\Umathquad\displaystyle=1em
\stoptyping

they obey grouping, and you can use \type {\the\Umathquad\displaystyle} if
needed.

\section{Skips around display math}

The injection of \type {\abovedisplayskip} and \type {\belowdisplayskip} is not
symmetrical. An above one is always inserted, also when zero, but the below is
only inserted when larger than zero. Especially the later mkes it sometimes hard
to fully control spacing. Therefore \LUATEX\ comes with a new directive: \type
{\mathdisplayskipmode}. The following values apply:

\starttabulate
\NC 0 \NC normal \TEX\ behaviour: always above, only below when larger than zero \NC \NR
\NC 1 \NC always \NC \NR
\NC 2 \NC only when not zero \NC \NR
\NC 3 \NC never, not even when not zero \NC \NR
\stoptabulate

\section{Font-based Math Parameters}

While it is nice to have these math parameters available for tweaking, it would
be tedious to have to set each of them by hand. For this reason, \LUATEX\
initializes a bunch of these parameters whenever you assign a font identifier to
a math family based on either the traditional math font dimensions in the font
(for assignments to math family~2 and~3 using \TFM|-|based fonts like \type
{cmsy} and \type {cmex}), or based on the named values in a potential \type
{MathConstants} table when the font is loaded via Lua. If there is a \type
{MathConstants} table, this takes precedence over font dimensions, and in that
case no attention is paid to which family is being assigned to: the \type
{MathConstants} tables in the last assigned family sets all parameters.

In the table below, the one|-|letter style abbreviations and symbolic tfm font
dimension names match those using in the \TeX book. Assignments to \type
{\textfont} set the values for the cramped and uncramped display and text styles,
\type {\scriptfont} sets the script styles, and \type {\scriptscriptfont} sets
the scriptscript styles, so we have eight parameters for three font sizes. In the
\TFM\ case, assignments only happen in family~2 and family~3 (and of course only
for the parameters for which there are font dimensions).

Besides the parameters below, \LUATEX\ also looks at the \quote {space} font
dimension parameter. For math fonts, this should be set to zero.

\start

\switchtobodyfont[8pt]

\starttabulate[|l|l|l|p|]
\NC \bf variable                      \NC \bf style             \NC \bf default value opentype               \NC \bf default value tfm \NC \NR
\NC \type {\Umathaxis}                \NC --                    \NC AxisHeight                               \NC axis_height \NC \NR
\NC \type {\Umathoperatorsize}        \NC D, D'                 \NC DisplayOperatorMinHeight                 \NC $^6$ \NC \NR
\NC \type {\Umathfractiondelsize}     \NC D, D'                 \NC FractionDelimiterDisplayStyleSize$^9$    \NC delim1 \NC \NR
\NC                                   \NC T, T', S, S', SS, SS' \NC FractionDelimiterSize$^9$                \NC delim2 \NC \NR
\NC \type {\Umathfractiondenomdown}   \NC D, D'                 \NC FractionDenominatorDisplayStyleShiftDown \NC denom1 \NC \NR
\NC                                   \NC T, T', S, S', SS, SS' \NC FractionDenominatorShiftDown             \NC denom2 \NC \NR
\NC \type {\Umathfractiondenomvgap}   \NC D, D'                 \NC FractionDenominatorDisplayStyleGapMin    \NC 3*default_rule_thickness \NC \NR
\NC                                   \NC T, T', S, S', SS, SS' \NC FractionDenominatorGapMin                \NC default_rule_thickness \NC \NR
\NC \type {\Umathfractionnumup}       \NC D, D'                 \NC FractionNumeratorDisplayStyleShiftUp     \NC num1 \NC \NR
\NC                                   \NC T, T', S, S', SS, SS' \NC FractionNumeratorShiftUp                 \NC num2 \NC \NR
\NC \type {\Umathfractionnumvgap}     \NC D, D'                 \NC FractionNumeratorDisplayStyleGapMin      \NC 3*default_rule_thickness \NC \NR
\NC                                   \NC T, T', S, S', SS, SS' \NC FractionNumeratorGapMin                  \NC default_rule_thickness \NC \NR
\NC \type {\Umathfractionrule}        \NC --                    \NC FractionRuleThickness                    \NC default_rule_thickness \NC \NR
\NC \type {\Umathskewedfractionhgap}  \NC --                    \NC SkewedFractionHorizontalGap              \NC math_quad/2 \NC \NR
\NC \type {\Umathskewedfractionvgap}  \NC --                    \NC SkewedFractionVerticalGap                \NC math_x_height \NC \NR
\NC \type {\Umathlimitabovebgap}      \NC --                    \NC UpperLimitBaselineRiseMin                \NC big_op_spacing3 \NC \NR
\NC \type {\Umathlimitabovekern}      \NC --                    \NC 0$^1$                                    \NC big_op_spacing5 \NC \NR
\NC \type {\Umathlimitabovevgap}      \NC --                    \NC UpperLimitGapMin                         \NC big_op_spacing1 \NC \NR
\NC \type {\Umathlimitbelowbgap}      \NC --                    \NC LowerLimitBaselineDropMin                \NC big_op_spacing4 \NC \NR
\NC \type {\Umathlimitbelowkern}      \NC --                    \NC 0$^1$                                    \NC big_op_spacing5 \NC \NR
\NC \type {\Umathlimitbelowvgap}      \NC --                    \NC LowerLimitGapMin                         \NC big_op_spacing2 \NC \NR
\NC \type {\Umathoverdelimitervgap}   \NC --                    \NC StretchStackGapBelowMin                  \NC big_op_spacing1 \NC \NR
\NC \type {\Umathoverdelimiterbgap}   \NC --                    \NC StretchStackTopShiftUp                   \NC big_op_spacing3 \NC \NR
\NC \type {\Umathunderdelimitervgap}  \NC--                     \NC StretchStackGapAboveMin                  \NC big_op_spacing2 \NC \NR
\NC \type {\Umathunderdelimiterbgap}  \NC--                     \NC StretchStackBottomShiftDown              \NC big_op_spacing4 \NC \NR
\NC \type {\Umathoverbarkern}         \NC --                    \NC OverbarExtraAscender                     \NC default_rule_thickness \NC \NR
\NC \type {\Umathoverbarrule}         \NC --                    \NC OverbarRuleThickness                     \NC default_rule_thickness \NC \NR
\NC \type {\Umathoverbarvgap}         \NC --                    \NC OverbarVerticalGap                       \NC 3*default_rule_thickness \NC \NR
\NC \type {\Umathquad}                \NC --                    \NC <font_size(f)>$^1$                       \NC math_quad \NC \NR
\NC \type {\Umathradicalkern}         \NC --                    \NC RadicalExtraAscender                     \NC default_rule_thickness \NC \NR
\NC \type {\Umathradicalrule}         \NC --                    \NC RadicalRuleThickness                     \NC <not set>$^2$ \NC \NR
\NC \type {\Umathradicalvgap}         \NC D, D'                 \NC RadicalDisplayStyleVerticalGap           \NC (default_rule_thickness+\crlf
                                                                                (abs(math_x_height)/4))$^3$ \NC \NR
\NC                                   \NC T, T', S, S', SS, SS' \NC RadicalVerticalGap                       \NC (default_rule_thickness+\crlf
                                                                                (abs(default_rule_thickness)/4))$^3$ \NC \NR
\NC \type {\Umathradicaldegreebefore} \NC --                    \NC RadicalKernBeforeDegree                  \NC <not set>$^2$ \NC \NR
\NC \type {\Umathradicaldegreeafter}  \NC --                    \NC RadicalKernAfterDegree                   \NC <not set>$^2$ \NC \NR
\NC \type {\Umathradicaldegreeraise}  \NC --                    \NC RadicalDegreeBottomRaisePercent          \NC <not set>$^{2,7}$ \NC \NR
\NC \type {\Umathspaceafterscript}    \NC --                    \NC SpaceAfterScript                         \NC script_space$^4$ \NC \NR
\NC \type {\Umathstackdenomdown}      \NC D, D'                 \NC StackBottomDisplayStyleShiftDown         \NC denom1 \NC \NR
\NC                                   \NC T, T', S, S', SS, SS' \NC StackBottomShiftDown                     \NC denom2 \NC \NR
\NC \type {\Umathstacknumup}          \NC D, D'                 \NC StackTopDisplayStyleShiftUp              \NC num1 \NC \NR
\NC                                   \NC T, T', S, S', SS, SS' \NC StackTopShiftUp                          \NC num3 \NC \NR
\NC \type {\Umathstackvgap}           \NC D, D'                 \NC StackDisplayStyleGapMin                  \NC 7*default_rule_thickness \NC \NR
\NC                                   \NC T, T', S, S', SS, SS' \NC StackGapMin                              \NC 3*default_rule_thickness \NC \NR
\NC \type {\Umathsubshiftdown}        \NC --                    \NC SubscriptShiftDown                       \NC sub1 \NC \NR
\NC \type {\Umathsubshiftdrop}        \NC --                    \NC SubscriptBaselineDropMin                 \NC sub_drop \NC \NR
\NC \type {\Umathsubsupshiftdown}     \NC --                    \NC SubscriptShiftDownWithSuperscript$^8$    \NC \NC \NR
\NC                                   \NC                       \NC \quad\ or SubscriptShiftDown             \NC sub2 \NC \NR
\NC \type {\Umathsubtopmax}           \NC --                    \NC SubscriptTopMax                          \NC (abs(math_x_height * 4) / 5) \NC \NR
\NC \type {\Umathsubsupvgap}          \NC --                    \NC SubSuperscriptGapMin                     \NC 4*default_rule_thickness \NC \NR
\NC \type {\Umathsupbottommin}        \NC --                    \NC SuperscriptBottomMin                     \NC (abs(math_x_height) / 4) \NC \NR
\NC \type {\Umathsupshiftdrop}        \NC --                    \NC SuperscriptBaselineDropMax               \NC sup_drop \NC \NR
\NC \type {\Umathsupshiftup}          \NC D                     \NC SuperscriptShiftUp                       \NC sup1 \NC \NR
\NC                                   \NC T, S, SS,             \NC SuperscriptShiftUp                       \NC sup2 \NC \NR
\NC                                   \NC D', T', S', SS'       \NC SuperscriptShiftUpCramped                \NC sup3 \NC \NR
\NC \type {\Umathsupsubbottommax}     \NC --                    \NC SuperscriptBottomMaxWithSubscript        \NC (abs(math_x_height * 4) / 5) \NC \NR
\NC \type {\Umathunderbarkern}        \NC --                    \NC UnderbarExtraDescender                   \NC default_rule_thickness \NC \NR
\NC \type {\Umathunderbarrule}        \NC --                    \NC UnderbarRuleThickness                    \NC default_rule_thickness \NC \NR
\NC \type {\Umathunderbarvgap}        \NC --                    \NC UnderbarVerticalGap                      \NC 3*default_rule_thickness \NC \NR
\NC \type {\Umathconnectoroverlapmin} \NC --                    \NC MinConnectorOverlap                      \NC 0$^5$ \NC \NR
\stoptabulate

\stop

Note 1: \OPENTYPE\ fonts set \type {\Umathlimitabovekern} and \type
{\Umathlimitbelowkern} to zero and set \type {\Umathquad} to the font size of the
used font, because these are not supported in the \type {MATH} table,

Note 2: Traditional \TFM\ fonts do not set \type {\Umathradicalrule} because
\TEX82\ uses the height of the radical instead. When this parameter is indeed not
set when \LUATEX\ has to typeset a radical, a backward compatibility mode will
kick in that assumes that an oldstyle \TEX\ font is used. Also, they do not set
\type {\Umathradicaldegreebefore}, \type {\Umathradicaldegreeafter}, and \type
{\Umathradicaldegreeraise}. These are then automatically initialized to
$5/18$quad, $-10/18$quad, and 60.

Note 3: If \TFM\ fonts are used, then the \type {\Umathradicalvgap} is not set
until the first time \LUATEX\ has to typeset a formula because this needs
parameters from both family~2 and family~3. This provides a partial backward
compatibility with \TEX82, but that compatibility is only partial: once the \type
{\Umathradicalvgap} is set, it will not be recalculated any more.

Note 4: When \TFM\ fonts are used a similar situation arises with respect to
\type {\Umathspaceafterscript}: it is not set until the first time \LUATEX\ has
to typeset a formula. This provides some backward compatibility with \TEX82. But
once the \type {\Umathspaceafterscript} is set, \type {\scriptspace} will never
be looked at again.

Note 5: Traditional \TFM\ fonts set \type {\Umathconnectoroverlapmin} to zero
because \TEX82\ always stacks extensibles without any overlap.

Note 6: The \type {\Umathoperatorsize} is only used in \type {\displaystyle}, and
is only set in \OPENTYPE\ fonts. In \TFM\ font mode, it is artificially set to
one scaled point more than the initial attempt's size, so that always the \quote
{first next} will be tried, just like in \TEX82.

Note 7: The \type {\Umathradicaldegreeraise} is a special case because it is the
only parameter that is expressed in a percentage instead of as a number of scaled
points.

Note 8: \type {SubscriptShiftDownWithSuperscript} does not actually exist in the
\quote {standard} \OPENTYPE\ math font Cambria, but it is useful enough to be
added.

Note 9: \type {FractionDelimiterDisplayStyleSize} and \type
{FractionDelimiterSize} do not actually exist in the \quote {standard} \OPENTYPE\
math font Cambria, but were useful enough to be added.

\section{Math spacing setting}

Besides the parameters mentioned in the previous sections, there are also 64 new
primitives to control the math spacing table (as explained in Chapter~18 of the
\TEX book). The primitive names are a simple matter of combining two math atom
types, but for completeness' sake, here is the whole list:

\starttwocolumns
\starttyping
\Umathordordspacing
\Umathordopspacing
\Umathordbinspacing
\Umathordrelspacing
\Umathordopenspacing
\Umathordclosespacing
\Umathordpunctspacing
\Umathordinnerspacing
\Umathopordspacing
\Umathopopspacing
\Umathopbinspacing
\Umathoprelspacing
\Umathopopenspacing
\Umathopclosespacing
\Umathoppunctspacing
\Umathopinnerspacing
\Umathbinordspacing
\Umathbinopspacing
\Umathbinbinspacing
\Umathbinrelspacing
\Umathbinopenspacing
\Umathbinclosespacing
\Umathbinpunctspacing
\Umathbininnerspacing
\Umathrelordspacing
\Umathrelopspacing
\Umathrelbinspacing
\Umathrelrelspacing
\Umathrelopenspacing
\Umathrelclosespacing
\Umathrelpunctspacing
\Umathrelinnerspacing
\Umathopenordspacing
\Umathopenopspacing
\Umathopenbinspacing
\Umathopenrelspacing
\Umathopenopenspacing
\Umathopenclosespacing
\Umathopenpunctspacing
\Umathopeninnerspacing
\Umathcloseordspacing
\Umathcloseopspacing
\Umathclosebinspacing
\Umathcloserelspacing
\Umathcloseopenspacing
\Umathcloseclosespacing
\Umathclosepunctspacing
\Umathcloseinnerspacing
\Umathpunctordspacing
\Umathpunctopspacing
\Umathpunctbinspacing
\Umathpunctrelspacing
\Umathpunctopenspacing
\Umathpunctclosespacing
\Umathpunctpunctspacing
\Umathpunctinnerspacing
\Umathinnerordspacing
\Umathinneropspacing
\Umathinnerbinspacing
\Umathinnerrelspacing
\Umathinneropenspacing
\Umathinnerclosespacing
\Umathinnerpunctspacing
\Umathinnerinnerspacing
\stoptyping
\stoptwocolumns

These parameters are of type \type {\muskip}, so setting a parameter can be done
like this:

\starttyping
\Umathopordspacing\displaystyle=4mu plus 2mu
\stoptyping

They are all initialized by \type {initex} to the values mentioned in the table
in Chapter~18 of the \TEX book.

Note 1: for ease of use as well as for backward compatibility, \type
{\thinmuskip}, \type {\medmuskip} and \type {\thickmuskip} are treated
especially. In their case a pointer to the corresponding internal parameter is
saved, not the actual \type {\muskip} value. This means that any later changes to
one of these three parameters will be taken into account.

Note 2: Careful readers will realise that there are also primitives for the items
marked \type {*} in the \TEX book. These will not actually be used as those
combinations of atoms cannot actually happen, but it seemed better not to break
orthogonality. They are initialized to zero.

\section[mathacc]{Math accent handling}

\LUATEX\ supports both top accents and bottom accents in math mode, and math
accents stretch automatically (if this is supported by the font the accent comes
from, of course). Bottom and combined accents as well as fixed-width math accents
are controlled by optional keywords following \type {\Umathaccent}.

The keyword \type {bottom} after \type {\Umathaccent} signals that a bottom accent
is needed, and the keyword \type {both} signals that both a top and a bottom
accent are needed (in this case two accents need to be specified, of course).

Then the set of three integers defining the accent is read. This set of integers
can be prefixed by the \type {fixed} keyword to indicate that a non-stretching
variant is requested (in case of both accents, this step is repeated).

A simple example:

\starttyping
\Umathaccent both fixed 0 0 "20D7 fixed 0 0 "20D7 {example}
\stoptyping

If a math top accent has to be placed and the accentee is a character and has a
non-zero \type {top_accent} value, then this value will be used to place the
accent instead of the \type {\skewchar} kern used by \TEX82.

The \type {top_accent} value represents a vertical line somewhere in the
accentee. The accent will be shifted horizontally such that its own \type
{top_accent} line coincides with the one from the accentee. If the \type
{top_accent} value of the accent is zero, then half the width of the accent
followed by its italic correction is used instead.

The vertical placement of a top accent depends on the \type {x_height} of the
font of the accentee (as explained in the \TEX book), but if value that turns out
to be zero and the font had a \type {MathConstants} table, then \type
{AccentBaseHeight} is used instead.

The vertical placement of a bottom accent is straight below the accentee, no
correction takes place.

Possible locations are \type {top}, \type {bottom}, \type {both} and \type
{center}. When no location is given \type {top} is assumed. An additional
parameter \type {fraction} can be specified followed by a number; a value of for
instance 1200 means that the criterium is 1.2 times the width of the nuclues. The
fraction only applies to the stepwise selected shapes and is mostly meant for the
\type {overlay} location. It also works for the other locations but then it
concerns the width.

\section{Math root extension}

The new primitive \type {\Uroot} allows the construction of a radical noad
including a degree field. Its syntax is an extension of \type {\Uradical}:

\starttyping
\Uradical <fam integer> <char integer> <radicand>
\Uroot    <fam integer> <char integer> <degree> <radicand>
\stoptyping

The placement of the degree is controlled by the math parameters \type
{\Umathradicaldegreebefore}, \type {\Umathradicaldegreeafter}, and \type
{\Umathradicaldegreeraise}. The degree will be typeset in \type
{\scriptscriptstyle}.

\section{Math kerning in super- and subscripts}

The character fields in a \LUA|-|loaded \OPENTYPE\ math font can have a \quote
{mathkern} table. The format of this table is the same as the \quote {mathkern}
table that is returned by the \type {fontloader} library, except that all height
and kern values have to be specified in actual scaled points.

When a super- or subscript has to be placed next to a math item, \LUATEX\ checks
whether the super- or subscript and the nucleus are both simple character items.
If they are, and if the fonts of both character items are \OPENTYPE\ fonts (as
opposed to legacy \TEX\ fonts), then \LUATEX\ will use the \OPENTYPE\ math
algorithm for deciding on the horizontal placement of the super- or subscript.

This works as follows:

\startitemize
    \startitem
        The vertical position of the script is calculated.
    \stopitem
    \startitem
        The default horizontal position is flat next to the base character.
    \stopitem
    \startitem
        For superscripts, the italic correction of the base character is added.
    \stopitem
    \startitem
        For a superscript, two vertical values are calculated: the bottom of the
        script (after shifting up), and the top of the base. For a subscript, the two
        values are the top of the (shifted down) script, and the bottom of the base.
    \stopitem
    \startitem
        For each of these two locations:
        \startitemize
            \startitem
                find the math kern value at this height for the base (for a subscript
                placement, this is the bottom_right corner, for a superscript
                placement the top_right corner)
            \stopitem
            \startitem
                find the math kern value at this height for the script (for a
                subscript placement, this is the top_left corner, for a superscript
                placement the bottom_left corner)
            \stopitem
            \startitem
                add the found values together to get a preliminary result.
            \stopitem
        \stopitemize
    \stopitem
    \startitem
        The horizontal kern to be applied is the smallest of the two results from
        previous step.
    \stopitem
\stopitemize

The math kern value at a specific height is the kern value that is specified by the
next higher height and kern pair, or the highest one in the character (if there is no
value high enough in the character), or simply zero (if the character has no math kern
pairs at all).

\section{Scripts on horizontally extensible items like arrows}

The primitives \type {\Uunderdelimiter} and \type {\Uoverdelimiter} allow the
placement of a subscript or superscript on an automatically extensible item and
\type {\Udelimiterunder} and \type {\Udelimiterover} allow the placement of an
automatically extensible item as a subscript or superscript on a nucleus. The
input:

% these produce radical noads .. in fact the code base has the numbers wrong for
% quite a while, so no one seems to use this

\startbuffer
$\Uoverdelimiter  0 "2194 {\hbox{\strut  overdelimiter}}$
$\Uunderdelimiter 0 "2194 {\hbox{\strut underdelimiter}}$
$\Udelimiterover  0 "2194 {\hbox{\strut  delimiterover}}$
$\Udelimiterunder 0 "2194 {\hbox{\strut delimiterunder}}$
\stopbuffer

\typebuffer will render this:

\blank \startnarrower \getbuffer \stopnarrower \blank

The vertical placements are controlled by \type {\Umathunderdelimiterbgap}, \type
{\Umathunderdelimitervgap}, \type {\Umathoverdelimiterbgap}, and \type
{\Umathoverdelimitervgap} in a similar way as limit placements on large operators.
The superscript in \type {\Uoverdelimiter} is typeset in a suitable scripted style,
the subscript in \type {\Uunderdelimiter} is cramped as well.

These primitives accepts an option \type {width} specification. When used the
also optional keywords \type {left}, \type {middle} and \type {right} will
determine what happens when a requested size can't be met (which can happen when
we step to successive larger variants).

An extra primitive \type {\Uhextensible} is available that can be used like this:

\startbuffer
$\Uhextensible width 10cm 0 "2194$
\stopbuffer

\typebuffer This will render this:

\blank \startnarrower \getbuffer \stopnarrower \blank

Here you can also pass options, like:

\startbuffer
$\Uhextensible width 1pt middle 0 "2194$
\stopbuffer

\typebuffer This gives:

\blank \startnarrower \getbuffer \stopnarrower \blank

\LUATEX\ internally uses a structure that supports \OPENTYPE\ \quote
{MathVariants} as well as \TFM\ \quote {extensible recipes}. In most cases where
font metrics are involved we have a different code path for traditional fonts end
\OPENTYPE\ fonts.

\section {Extracting values}

You can extract the components of a math character. Say that we have defined:

\starttyping
\Umathcode 1 2 3 4
\stoptyping

then

\starttyping
[\Umathcharclass1] [\Umathcharfam1] [\Umathcharslot1]
\stoptyping

will return:

\starttyping
[2] [3] [4]
\stoptyping

These commands are provides as convenience. Before they came available you could
do the following:

\starttyping
\def\Umathcharclass{\directlua{tex.print(tex.getmathcode(token.scan_int())[1])}}
\def\Umathcharfam  {\directlua{tex.print(tex.getmathcode(token.scan_int())[2])}}
\def\Umathcharslot {\directlua{tex.print(tex.getmathcode(token.scan_int())[3])}}
\stoptyping

\section{fractions}

The \type {\abovewithdelims} command accepts a keyword \type {exact}. When issued
the extra space relative to the rule thickness is not added. One can of course
use the \type {\Umathfraction..gap} commands to influence the spacing. Also the
rule is still positioned around the math axis.

\starttyping
$$ { {a} \abovewithdelims() exact 4pt {b} }$$
\stoptyping

The math parameter table contains some parameters that specify a horizontal and
vertical gap for skewed fractions. Of course some guessing is needed in order to
implement something that uses them. And so we now provide a primitive similar to the
other fraction related ones but with a few options so that one can influence the
rendering. Of course a user can also mess around a bit with the parameters
\type {\Umathskewedfractionhgap} and \type {\Umathskewedfractionvgap}.

The syntax used here is:

\starttyping
{ {1} \Uskewed / <options> {2} }
{ {1} \Uskewedwithdelims / () <options> {2} }
\stoptyping

where the options can be \type {noaxis} and \type {exact}. By default we add half
the axis to the shifts and by default we zero the width of the middle character.
For Latin Modern The result looks as follows:

\def\ShowA#1#2#3{$x + { {#1} \Uskewed           /    #3 {#2} } + x$}
\def\ShowB#1#2#3{$x + { {#1} \Uskewedwithdelims / () #3 {#2} } + x$}

\start
    \switchtobodyfont[modern]
    \starttabulate[||||||]
        \NC \NC
            \ShowA{a}{b}{} \NC
            \ShowA{1}{2}{} \NC
            \ShowB{a}{b}{} \NC
            \ShowB{1}{2}{} \NC
        \NR
        \NC \type{exact} \NC
            \ShowA{a}{b}{exact} \NC
            \ShowA{1}{2}{exact} \NC
            \ShowB{a}{b}{exact} \NC
            \ShowB{1}{2}{exact} \NC
        \NR
        \NC \type{noaxis} \NC
            \ShowA{a}{b}{noaxis} \NC
            \ShowA{1}{2}{noaxis} \NC
            \ShowB{a}{b}{noaxis} \NC
            \ShowB{1}{2}{noaxis} \NC
        \NR
        \NC \type{exact noaxis} \NC
            \ShowA{a}{b}{exact noaxis} \NC
            \ShowA{1}{2}{exact noaxis} \NC
            \ShowB{a}{b}{exact noaxis} \NC
            \ShowB{1}{2}{exact noaxis} \NC
        \NR
    \stoptabulate
\stop

\section {Other Math changes}

\subsection {Verbose versions of single-character math commands}

\LUATEX\ defines six new primitives that have the same function as
\type {^}, \type {_}, \type {$}, and \type {$$}: %$

\starttabulate[|l|l|l|l|]
\NC \bf primitive           \NC \bf explanation \NC \NR
\NC \type {\Usuperscript}      \NC Duplicates the functionality of \type {^} \NC \NR
\NC \type {\Usubscript}        \NC Duplicates the functionality of \type {_} \NC \NR
\NC \type {\Ustartmath}        \NC Duplicates the functionality of \type {$}, % $
                                   when used in non-math mode. \NC \NR
\NC \type {\Ustopmath}         \NC Duplicates the functionality of \type {$}, % $
                                   when used in inline math mode. \NC \NR
\NC \type {\Ustartdisplaymath} \NC Duplicates the functionality of \type {$$}, % $$
                                   when used in non-math mode. \NC \NR
\NC \type {\Ustopdisplaymath}  \NC Duplicates the functionality of \type {$$}, % $$
                                   when used in display math mode. \NC \NR
\stoptabulate

The \type {\Ustopmath} and \type {\Ustopdisplaymath} primitives check if the current
math mode is the correct one (inline vs.\ displayed), but you can freely intermix
the four mathon|/|mathoff commands with explicit dollar sign(s).

\subsection{Allowed math commands in non-math modes}

The commands \type {\mathchar}, and \type {\Umathchar} and control sequences that
are the result of \type {\mathchardef} or \type {\Umathchardef} are also
acceptable in the horizontal and vertical modes. In those cases, the \type
{\textfont} from the requested math family is used.

\section{Math surrounding skips}

Inline math is surrounded by (optional) \type {\mathsurround} spacing but that is fixed
dimension. There is now an additional parameter \type {\mathsurroundskip}. When set to a
non|-|zero value (or zero with some stretch or shrink) this parameter will replace
\type {\mathsurround}. By using an additional parameter instead of changing the nature
of \type {\mathsurround}, we can remain compatible.

% \section{Math todo}
%
% The following items are still todo.
%
% \startitemize
% \startitem
%     Pre-scripts.
% \stopitem
% \startitem
%     Multi-story stacks.
% \stopitem
% \startitem
%     Flattened accents for high characters (maybe).
% \stopitem
% \startitem
%     Better control over the spacing around displays and handling of equation numbers.
% \stopitem
% \startitem
%     Support for multi|-|line displays using \MATHML\ style alignment points.
% \stopitem
% \stopitemize

\subsection {Delimiters: \type{\Uleft}, \type {\Umiddle} and \type {\Uright}}

Normally you will force delimiters to certain sizes by putting an empty box or
rule next to it. The resulting delimiter will either be a character from the
stepwise size range or an extensible. The latter can be quite differently
positioned that the characters as it depends on the fit as well as the fact if
the used characters in the font have depth or height. Commands like (plain \TEX
s) \type {\big} need use this feature. In \LUATEX\ we provide a bit more control
by three variants that supporting optional parameters \type {height}, \type
{depth} and \type {axis}. The following example uses this:

\startbuffer
\Uleft   height 30pt depth 10pt      \Udelimiter "0 "0 "000028
\quad x\quad
\Umiddle height 40pt depth 15pt      \Udelimiter "0 "0 "002016
\quad x\quad
\Uright  height 30pt depth 10pt      \Udelimiter "0 "0 "000029
\quad \quad \quad
\Uleft   height 30pt depth 10pt axis \Udelimiter "0 "0 "000028
\quad x\quad
\Umiddle height 40pt depth 15pt axis \Udelimiter "0 "0 "002016
\quad x\quad
\Uright  height 30pt depth 10pt axis \Udelimiter "0 "0 "000029
\stopbuffer

\typebuffer

\startlinecorrection
\ruledhbox{\mathematics{\getbuffer}}
\stoplinecorrection

The keyword \type {exact} can be used as directive that the real dimensions
should be applied when the criteria can't be met which can happen when we're
still stepping through the successively larger variants. When no dimensions are
given the \type {noaxis} command can be used to prevent shifting over the axis.

You can influence the final class with the keyword \type {class} which will
influence the spacing.

\subsection{Fixed scripts}

We have three parameters that are used for this fixed anchoring:

\starttabulate[|l|l|]
\NC $d$ \NC \type {\Umathsubshiftdown}    \NC \NR
\NC $u$ \NC \type {\Umathsupshiftup}      \NC \NR
\NC $s$ \NC \type {\Umathsubsupshiftdown} \NC \NR
\stoptabulate

When we set \type {\mathscriptsmode} to a value other than zero these are used
for calculating fixed positions. This is something that is needed for instance
for chemistry. You can manipulate the mentioned variables to achive different
effects.

\def\SampleMath#1%
  {$\mathscriptsmode#1\mathupright CH_2 + CH^+_2 + CH^2_2$}

\starttabulate[|c|c|c|l|]
\NC \bf mode \NC \bf down      \NC \bf up        \NC                \NC \NR
\NC 0        \NC dynamic       \NC dynamic       \NC \SampleMath{0} \NC \NR
\NC 1        \NC $d$           \NC $u$           \NC \SampleMath{1} \NC \NR
\NC 2        \NC $s$           \NC $u$           \NC \SampleMath{2} \NC \NR
\NC 3        \NC $s$           \NC $u + s - d$   \NC \SampleMath{3} \NC \NR
\NC 4        \NC $d + (s-d)/2$ \NC $u + (s-d)/2$ \NC \SampleMath{4} \NC \NR
\NC 5        \NC $d$           \NC $u + s - d$   \NC \SampleMath{5} \NC \NR
\stoptabulate

The value of this parameter obeys grouping but applies to the whole current
formula.

% if needed we can put the value in stylenodes but maybe more should go there

\subsection {Tracing}

Because there are quite some math related parameters and values, it is possible
to limit tracing. Only when \type {tracingassigns} and|/|or \type
{tracingrestores} are set to~2 or more they will be traced.

\subsection {Math options}

The logic in the math engine is rather complex and there are often no universal
solutions (read: what works out well for one font, fails for another). Therefore
some variations in the implementation will be driven by options for which a new
primitive \type {\mathoption} has been introduced (so that we don't end up with
many new commands). The approach of options also permits us to see what effect a
specific solution has.

\subsubsection {\type {\mathoption noitaliccompensation}}

This option compensates placement for characters with a built|-|in italic
correction.

\startbuffer
{\showboxes\int}\quad
{\showboxes\int_{|}^{|}}\quad
{\showboxes\int\limits_{|}^{|}}
\stopbuffer

\typebuffer

Gives (with computer modern that has such italics):

\startlinecorrection[blank]
    \switchtobodyfont[modern]
    \startcombination[nx=2,ny=2,distance=5em]
        {\mathoption noitaliccompensation 0\relax \mathematics{\getbuffer}}
            {\nohyphens\type{0:inline}}
        {\mathoption noitaliccompensation 0\relax \mathematics{\displaymath\getbuffer}}
            {\nohyphens\type{0:display}}
        {\mathoption noitaliccompensation 1\relax \mathematics{\getbuffer}}
            {\nohyphens\type{1:inline}}
        {\mathoption noitaliccompensation 1\relax \mathematics{\displaymath\getbuffer}}
            {\nohyphens\type{1:display}}
    \stopcombination
\stoplinecorrection

\subsubsection {\type {\mathoption nocharitalic}}

When two characters follow each other italic correction can interfere. The
following example shows what this option does:

\startbuffer
\catcode"1D443=11
\catcode"1D444=11
\catcode"1D445=11
P( PP PQR
\stopbuffer

\typebuffer

Gives (with computer modern that has such italics):

\startlinecorrection[blank]
    \switchtobodyfont[modern]
    \startcombination[nx=2,ny=2,distance=5em]
        {\mathoption nocharitalic 0\relax \mathematics{\getbuffer}}
            {\nohyphens\type{0:inline}}
        {\mathoption nocharitalic 0\relax \mathematics{\displaymath\getbuffer}}
            {\nohyphens\type{0:display}}
        {\mathoption nocharitalic 1\relax \mathematics{\getbuffer}}
            {\nohyphens\type{1:inline}}
        {\mathoption nocharitalic 1\relax \mathematics{\displaymath\getbuffer}}
            {\nohyphens\type{1:display}}
    \stopcombination
\stoplinecorrection

\subsubsection {\type {\mathoption useoldfractionscaling}}

This option has been introduced as solution for tracker item 604 for fuzzy cases
around either or not present fraction related settings for new fonts.

\stopchapter

\stopcomponent


\Lecture{Jayalal Sarma}{Sept 29, 2020}{08}{PIE and three applications}{Sumanth Naik}{$\alpha$}{JS}

%\section{Introduction}
The journey so far has been that we have been doing counting by bijections and established certain ideas regarding double counting and the bijections behind the scenes. Then we came to Principle of Inclusion-Exclusion(PIE) as a consequence of a bijection argument. In this lecture, we will look at another proof (an algebraic proof) for PIE and then 3 interesting applications of PIE.

\section{Principle of Inclusion Exclusion (PIE) - An Algebraic Proof} \label{sec:Principle of Inclusion - Exclusion(PIE)}
If there are $n$ subsets of a ground set $X$; $A_1$, $A_2$, $A_3, \ldots A_n$ $\subseteq$ $X$, then PIE helps us to estimate the size of the set of union of all $n$ subsets of the ground set. Mathematically, PIE states that,
\begin{align*}
\left|\bigcup_{i=1}^{n} A_i\right| &= \sum_{1 \le i \le n} | A_i|
\hspace{0.1cm}- \sum_{1 \le i < j \le n} \left| A_i \cap A_j \right| \\
&\hspace{0.5cm}+ \sum_{1 \le i < j < k \le n} | A_i \cap A_j \cap A_k| \hspace{0.2cm}.\hspace{0.1cm}.\hspace{0.1cm}.\hspace{0.1cm}.\hspace{0.1cm}.\\
\left|\bigcup_{i=1}^{n} A_i\right| &= \sum_{\emptyset \neq I \subseteq [n]} (-1)^{|I| +1} \left|\bigcap_{i \in I} A_i \right|\\
&=\sum_{\emptyset \neq I \subseteq [n]} (-1)^{|I| +1} \left|A_I\right|
\end{align*}
where $[n] = \{1,2,3, \ldots, n\} $ (short-hand notation for $1$ to $n$ elements) and $A_I = \bigcap_{i \in I} A_i$.\\
\\
Note that the intuition behind understanding the formula in the second step from first is that, $ \emptyset \neq I \subseteq [n]$ captures all the combinations of $1,2,3, \ldots ,n$ sized sets from $n$ sized set of numbers, i.e., $1 \le i \le n$ (set of combinations of 1 sized set from n sized set), $1 \le i < j \le n$ (set of combinations of 2 sized set from n sized set) and so on up to set of combinations of $n$ sized set from n sized set. The alternating sign in first equation's term is captured by $(-1)^{|I| +1}$ in second equation. And finally, the intersection part of all the terms in first equation, i.e., $|A_i|, |A_i \cap A_j|,  |A_i \cap A_j \cap A_j| \ldots$ is captured in $ \bigcap_{i \in I} A_i$ of the second equation.
\begin{proof}
Define the characterestic function of the set $A_i$ as $f_i$ described as : $f_i:X\longrightarrow\{0,1\}$, where the images are defined as $$\forall x \in X,\hspace{0.3cm} f_i(x) =
  \begin{cases}
    1&\mbox{if } x \in A_i \\
    0& \textrm{otherwise }
  \end{cases}
$$

By definition, $(1-f_i(x))$ is the characteristic function for the compliment of $A_i$ (i.e. $X\setminus A_i$ or $\overline A_i$). In other words, when you subtract the characteristic function of a set from $1$, the difference is the characteristic function of the compliment of the same set. It is also to be noted that $f_i(x)f_j(x)$ is the characteristic function of $A_i\cap A_j$. In other words; when you multiply the characteristic functions of two sets with each other, the product is the characteristic function of the intersection of the two sets.
\begin{align}
\intertext{Consider a function defined as,} F(x) &= \prod_{i=1}^{n}(1-f_i(x))\nonumber \\
&= (1-f_1(x))(1-f_2(x)) \ldots (1-f_n(x))\nonumber  \\
&= \sum_{I\subseteq[n]}(-1)^{|I|}\left(\prod_{i \in I} f_i(x)\right) \label{eq:F_def_in_PIE}
\end{align}
Note that the $F(x)$ represents the characteristic function of intersection of compliments (compliment of each $f_i$), hence by De-Morgan's Law, its mathematical equivalent is,
\[
\overline{\left(\bigcup_{i=1}^{n} A_i\right)} = X \setminus \bigcup	_{i=1}^{n}A_i
\]
To get the size of the set in the $RHS$ of previous equation (it has all the elements which are not present in any of the $n$ subsets of $X$), we just need to count the number of $x$'s in $X$ for which $F(x)$ is 1 (as $F(x)$ will be 1 for any $x$ only if every $f_i(x)$ is 0, i.e., $\forall i,x \notin A_i$). Hence:
\begin{equation}
\label{eq:sigma_F_1}
|X \setminus \bigcup_{i=1}^{n}A_i| = \sum_{x \in X} F(x)
\end{equation}

Also from (\ref{eq:F_def_in_PIE}),
\begin{align}
\sum_{x \in X} F(x)&= \sum_{x} \sum_{I \subseteq [n]} (-1)^{|I|} \left(\prod_{i \in I} f_i(x)\right)\nonumber \\
&= \sum_{I \subseteq [n]} (-1)^{|I|} \left(\sum_{x} \left(\prod_{i \in I} f_i(x)\right)\right)\nonumber \\
&=\sum_{I \subseteq [n]} (-1)^{|I|} \left|\bigcap_{i \in I}A_i\right|\label{eq:sigma_F_2}
\end{align}
The last step is because $(\prod_{i \in I} f_i(x))$ is the characteristic function of intersection of $n$ subsets, i.e., $\bigcap_{i \in I}A_i$. And its summation over $x$, $(\sum_{x} (\prod_{i \in I} f_i(x)))$ will give us the size of the intersection, $\left|\bigcap_{i \in I}A_i\right|$. Also, note that the convention when $I=\emptyset$ is,
%\begin{equation}
$\left|\bigcap_{i \in I}A_i\right| = |X|$.
which can be reasoned as when $I$ is empty, $\left(\prod_{i \in I} f_i(x)\right)$ is $1$ for any $x$. And its summation over $x$, $\sum_{x} \left(\prod_{i \in I} f_i(x)\right)$ gives $|X|$.
\begin{align*}
\intertext{By (\ref{eq:sigma_F_1}) and (\ref{eq:sigma_F_2}),}
\left|X \setminus \bigcup_{i=1}^{n}A_i\right| &= \sum_{I \subseteq [n]} (-1)^{|I|} \left|\bigcap_{i \in I}A_i\right|\\
|X | - \left| \bigcup_{i=1}^{n}A_i\right| &= \sum_{I \subseteq [n]} (-1)^{|I|} \left|\bigcap_{i \in I}A_i \right|\\
\left| \bigcup_{i=1}^{n}A_i \right| &= |X| - \sum_{I \subseteq [n]} (-1)^{|I|} \left|\bigcap_{i \in I}A_i\right|\\
&=\sum_{\emptyset \neq I \subseteq [n]} (-1)^{|I|+1} \left|\bigcap_{i \in I}A_i \right| \\
\end{align*}
This completes the algebraic proof for PIE.
\end{proof}

\section{Applications of PIE} \label{sec:Applications of PIE - lec1}

We now see three different applications of PIE which exposes some interesting features of the tool.

\subsection{Counting the number of derangements on $n$ elements.} \label{subsec:derangements application}
Consider a scenario where, $n$ people go to a theatre to watch a movie, they keep their hats outside with the gatekeeper. On return, in a rush, the gatekeeper panicked and gave back the hats randomly.\\
\textbf{Question:} What is the chance that nobody got their own hat for a very large $n$?\\
\textbf{Answer (surprisingly high)}: roughly 36\% ! (more precisely, the probability is $1/e = 0.3678$).

Formally, if we view the rearrangement as a permutation on $n$ elements, the property that we are looking for can be expressed mathematically as follows : A permutation $\sigma \in S_n$ is said to be a derangement if $\forall i \in [n], \sigma(i) \ne i$.
Now we prove the following theorem.

\begin{theorem}
Number of derangements on $n$ elements is $$\left(\sum_{k=0}^{n} \frac{(-1)^k}{k!}\right)n!$$
\end{theorem}

Before we proceed, let us demonstrate why this implies our surprising answer. We know that the total number of ways for the $n$ people to pick $n$ hats is $n!$ (factorial of $n$) and hence the chance of derangement is $\left(\sum_{k=0}^{n} \frac{(-1)^k}{k!}\right)$. As $n\rightarrow\infty$, $\left(\sum_{k=0}^{n} \frac{(-1)^k}{k!}\right) \rightarrow 1/e \thicksim 0.3678$.). We now proceed with the proof of the above theorem, which is a nice application of PIE.

\begin{proof}
Let $S_n$ be the set of permutations on $n$ elements. $\sigma \in S_n$ is a permutation function on $n$  elements ($\sigma : [n] \rightarrow [n]$). $\forall_{i=1}^{n},~ \sigma(i)$ is defined as the person to whom $i^{\text{th}}$ person's hat was given. If $\sigma(i) = i$, then it means that the $i^{\text{th}}$ person got the correct hat - in terms of formal language of permutations, this is called a \textit{fix-point} of the permutation. What we are looking for is to count the number of fix-point-free permutations in $S_n$.

The strategy is to count the number of non-derangements and subtract from $n!$.
Mathematically, non-derangement is captured as $\exists i,\hspace{0.2cm} \sigma(i) = i$. Now we set up the application of PIE in this context, by defining the $A_i$s first. Define $A_i$ as,
$$\forall i \in \{1,2,...n\},\hspace{0.2cm} A_i = \{\sigma \in S_n\hspace{0.1cm} |\hspace{0.1cm} \sigma(i) = i\}$$
So, $A_i$ represents the set of $n$ elements whose $i^{\text{th}}$ element is fixed to $i$, other elements can be any non repeating value of $1$ to $n$ (except $i$ as it is taken).

The set that we want to estimate the size of - the set of non-derangement can be represented as $\bigcup_{i=1}^{n} A_i$.
Hence, we are interested in finding the number of non-derangements $|\bigcup_{i=1}^{n} A_i|$.

We want to apply PIE - which is about intersection of these $A_i$. Can $A_i$ and $A_j$ really intersect? Indeed, they can, and we can even estimate the size of the intersection: indeed, for a permutation to be in the intersection it has to be fixing the element $i$ and $j$ and it has the freedom to choose any permutation for the remaining values. Hence,
$$|A_i \cap A_j| = (n-2)!$$

Now we generalize this estimate to arbitrary size intersections since they appear in the RHS of PIE. For a shorthand notation, define, $A_I = \bigcap_{i \in I} A_i$. Now, from the statement of $PIE$, we need to estimate sizes of $\left| A_I \right|$ for different $I \subseteq [n]$. Observe that,
\begin{align}
|A_I| &= (n-|I|)! \label{eq:size_of_A_I_derangement_problem}
\end{align}
Indeed, in $A_I$, $\forall i \in I$, $\sigma(i)$ is fixed to $i$ by definition. For the remaining $n-|I|$ values, $\sigma$ can take any arbitrary permutation of the same $n-|I|$ values, hence $(n-|I|)!$ gives the number of possibilities.\\

Using PIE and using the idea of fixing size of $I$ and sum over each size in next step,
\begin{align}
|\bigcup_{i=1}^{n} A_i| &= \sum_{\emptyset \neq I \subseteq [n]} (-1)^{|I|+1} |A_I|\nonumber \\
&= \sum_{k=1}^{n} (-1)^{k+1} \left(\sum_{I\subseteq [n],|I|=k} |A_I|\right)\nonumber \\
&= \sum_{k=1}^{n} (-1)^{k+1} \left(\sum_{I\subseteq [n],|I|=k} (n-k)!\right)\nonumber \tag{By (\ref{eq:size_of_A_I_derangement_problem})}\\
&= \sum_{k=1}^{n} (-1)^{k+1} (n-k)! {n \choose k}\nonumber \\
&= \sum_{k=1}^{n} (-1)^{k+1} \frac{n!} {k!}\nonumber \\
&=  \left(\sum_{k=1}^{n}  \frac{(-1)^{k+1}} {k!}\right)n! \label{eq:non_derangements}
\end{align}
Now, to get number of derangements, subtract (\ref{eq:non_derangements}) from $n!$, which is
\begin{align*}
n! - \left(\sum_{k=1}^{n}  \frac{(-1)^{k+1}} {k!}\right)n! &= \left(\sum_{k=0}^{n} \frac{(-1)^k}{k!}\right)n!
\end{align*}
\end{proof}

\subsection{Euler's $\Phi$ function.} \label{subsec:euler's function application}
\begin{theorem}
Let $n \in N$, $\Phi (n)$ = number of numbers $\leq n$, which are relatively prime to $n$. If $$n=\prod_{i=1}^{k}p_i^{\alpha_i}$$ where $p_i$ are distinct primes and $\forall i,~ \alpha_i \geq 1$, then $$\Phi(n) = n \left(\prod_{i=1}^{k}\left(1-\frac{1}{p_i}\right) \right)$$
\end{theorem}
\begin{proof}
Let $X=\{1,2,3,...,n\}$. Then,
\[
\forall 1 \leq i \leq k, A_i = \{m\in X ~|~p_i \textrm{ divides } m\}
\]
Thus, $A_i$ represents the set of multiples of $p_i$ less than $n$.
Number of numbers which are not relatively prime to $n$ is given by (as every number in any of $A_i$ will have $p_i$ as common factor) - is given by exactly the set : $\bigcup_{i=1}^{k} A_i$.  Thus we have the ground set for application for PIE. We need to be able to estimate the sizes of the intersections. More precisely:
\begin{align}
\Phi (n) &= n - |\bigcup_{i=1}^{k}A_i| \tag{apply PIE}
\nonumber \\
&=n- \sum_{I \subseteq [k], I \neq \emptyset} (-1)^{|I|+1}|A_I| \label{eq:mobius_with_PIE}
\end{align}
where
%\begin{align}
To esteimate $|A_I|$. We claim that $|A_I| = |\bigcap_{i \in I}A_i| = \frac{n}{\prod_{i \in I}p_i}$. This can be reasoned as follows : in $\bigcap_{i \in I}A_i$, there will be those numbers which are multiples of all the $p_i$'s. The same set can be obtained by including the product of every $p_i$, i.e., $\prod_{i \in I}p_i$, and all the numbers less than $n$ which are multiples of that product. The number of such numbers can be captured by $\frac{n}{\prod_{i \in I}p_i}$.\\
By Equation~\ref{eq:mobius_with_PIE} and using the convention of $\prod_{i \in I}p_i$ is 1 when $I=\emptyset$,
\begin{align*}
\Phi (n) &= n - \sum_{I \subseteq [k], I \neq \emptyset} (-1)^{|I|+1}\frac{n}{\left(\prod_{i \in I}p_i\right)}\\
&= \sum_{I \subseteq [k]} (-1)^{|I|}\frac{n}{(\prod_{i \in I}p_i)}\\
&= n\sum_{I \subseteq [k]} (-1)^{|I|}\frac{1}{\left(\prod_{i \in I}p_i\right()}\\
&=n\left(\prod_{i=1}^{k}\left(1-\frac{1}{p_i}\right)\right)
\end{align*}
Note that the last step is done similar to  (\ref{eq:F_def_in_PIE}) in PIE (section \ref{sec:Principle of Inclusion - Exclusion(PIE)}) derivation : $f_i$ there is equivalent to $\frac{1}{p_i}$ here. This completes the proof for the theorem.
\end{proof}
\vspace{.5cm}
\noindent
\begin{corollary}$\Phi$ is multiplicative when numbers are co-primes. i.e., if $n_1, n_2$ are co-primes, then $\Phi(n_1 n_2) = \Phi(n_1) \Phi(n_2)$.
\end{corollary}
\begin{proof}
Let $A$ be the set of prime factors of $n_1n_2$. Since $n_1n_2$ is the product of two numbers $n_1$ and $n_2$, any prime $p \in A$ should divide at least one of $n_1$ and $n_2$. If $n_1$ and $n_2$ are co-primes, then the do not have any common prime factor. Therefore, any prime $p \in A$ should divide exactly one of $n_1$ and $n_2$. So, we can partition the set $A$ into two sets $X$ and $Y$ where $X$ is the set of prime factors of $n_1$ and $Y$ is that of $n_2$.
\begin{align*}
    \Phi(n_1n_2) &= n_1 n_2  (\prod_{p \in A}(1-\frac{1}{p}))\\
    &= n_1 (\prod_{p\in X}(1-\frac{1}{p})). n_2 (\prod_{p\in Y}(1-\frac{1}{p}))\\
    &= \Phi(n_1) \Phi(n_2)
\end{align*}
Thus, if $n_1$, $n_2$ are co-primes, then $\Phi(n_1 n_2) = \Phi(n_1) \Phi(n_2)$. \end{proof}

\subsection{Probability that two natural numbers are co-primes} \label{subsec:co-primes application}
For two randomly chosen natural numbers, what is the probability that they do not have a common factor (other than 1)?\\
Answer: $\sim60\% $
\begin{proof}
Fix $n$; $S = \{(a,b) | a,b \in [n]\}$.\\
Consider two definitions, the good set $G$ (represents set of pairs whose elements have $gcd = 1$) and the bad set $B$ (represents set of pairs whose elements have $gcd > 1$),
\[
G = \{(a,b)| \text{ no } d > 1 \text{ exist such that }d  \hspace{0.1cm}divides \hspace{0.1cm} a \text{ and } d  \hspace{0.1cm}divides \hspace{0.1cm} b\}
\]
\[
B = \{(a,b)| \exists d > 1 \text{ such that }d \hspace{0.1cm}divides \hspace{0.1cm} a \text{ and } d \hspace{0.1cm}divides \hspace{0.1cm} b\}
\]
We want the upper bound of $|B|$ in terms of $n^2$.\\
Define $X$ which has all the permutations of pairs possible as, $$X = \{(a,b)|a,b \in [n]\}$$
And for prime $p \le n$, define $A_p$ as a set which contains pairs whose elements both have $p$ as a prime factor and the pair belongs to $X$. $$A_p = \{(a,b)|p \hspace{0.1cm}divides \hspace{0.1cm}a,p \hspace{0.1cm}divides \hspace{0.1cm}b, p \hspace{0.1cm}is\hspace{0.1cm}prime ,(a,b)\in X\}$$
Clearly, $$B = \bigcup_{p \le n} A_p$$
By PIE,
\begin{align}
|B| = \sum_{I \subseteq Q, I \neq \emptyset} (-1)^{|I|+1} |A_I| ~~\text{where,} ~~Q = \{p|p \le n, prime\}\label{eq:PIE_usage_application_3}
\end{align}
Now, the aim is to estimate $|A_I|$ (as stated in PIE), we can write,
\begin{align}
|A_I| =|\bigcap_{p_i \in I} A_{p_i}|\label{eq:size_of_A_I_mobius}
\end{align}
Here, $\bigcap_{p_i \in I} A_{p_i}$ denotes the set of pairs whose elements are both divisible by product of numbers (which are primes) in $I$. Note that the product need not be a prime. We can not write the resulting set ($\bigcap_{p_i \in I} A_{p_i}$) in terms of $A_p$ as $p$ is prime in the definition. So, lets create a new definition.\\
Let's define $A_d$, which denotes the set of pairs whose elements both have $d$ as a factor and the pairs belongs to $X$ (note that this definition is different from $A_p$ as there $p$ should be a prime, here $d$ can be any number), $$A_d = \{(a,b)|d \hspace{0.1cm}divides \hspace{0.1cm} a, d \hspace{0.1cm}divides \hspace{0.1cm} b, (a,b) \in X\}$$
Rewriting (\ref{eq:size_of_A_I_mobius}) using the definition of $A_d$,
\begin{align}
|A_I| =|A_d| \label{eq:size_of_A_I_equals_size_of_A_d}
~~where, \hspace{0.3cm}d = \prod_{p_i \in I}p_i
\end{align}
Estimating $|A_d|$ separately, from definition, $a$ can be any mutiple of $d$ which is less than or equal to $n$, similarly $b$ too can be any mutiple of $d$ which is less than or equal to $n$. Hence,
\begin{align}
|A_d| &=\lfloor \frac{n}{d} \rfloor \lfloor \frac{n}{d} \rfloor\nonumber\\
&=(\lfloor \frac{n}{d} \rfloor)^2 \label{eq:size_of_A_d}
\end{align}
From (\ref{eq:PIE_usage_application_3}), splitting the summation by number of primes taking part,
\begin{align}
|B| &=\sum_{k \geq 1} (\sum_{I \subseteq Q, I \neq \emptyset,|I| = k} (-1)^{|I|+1} |A_I|) \nonumber \tag{Apply (\ref{eq:size_of_A_I_equals_size_of_A_d}) and (\ref{eq:size_of_A_d}) }\\
&=  \sum_{k \geq 1}(\sum_{d \le n,\substack{d\text{ is a product } \\ \text{of } k \text{ distinct}\\ \text{primes from }Q} }(-1)^{k+1}(\lfloor \frac{n}{d} \rfloor)^2)  \label{eq:bad_set}
\end{align}
Note that the value of $k$ is used only to determine the sign of the terms in $|B|$. Usage of Mobius function gives a clever way to reduce the equation of $|B|$ to a single summation from double summation.\\
Mobius function $\mu(d)$ is given by
\[
  \mu(d) =
  \begin{cases}
    0 &\mbox{if } p^2 \hspace{0.1cm} \text{divides} \hspace{0.1cm} d, \hspace{0.1cm} p  \hspace{0.1cm} \text{is prime}\\
    1 &\mbox{if } d = 1\\
    (-1)^k &\mbox{if } d \text{ is a product of }k \text{ distinct primes}
  \end{cases}
\]
Using $\mu(d)$ in (\ref{eq:bad_set}),
$$|B| = \sum_{2 \le d \le n}(-\mu(d) ((\lfloor \frac{n}{d} \rfloor)^2))$$
Now estimating $|G|$; since all of $S$ can be either in $G$ or $B$ but not both and size of $S$ is $n^2$,
\begin{align}
|G| &= n^2 - |B|\nonumber \\
&= n^2 + \sum_{2 \le d \le n}\mu(d) ((\lfloor \frac{n}{d} \rfloor)^2)\nonumber \\
&= \sum_{1 \le d \le n}\mu(d) ((\lfloor \frac{n}{d} \rfloor)^2) \label{eq:good_set_1}
\end{align}
Last step uses the fact that $\mu(1) = 1$ in the Mobius function.\\
 Furthermore for any $x$,
\begin{align*}
(\lfloor x \rfloor )^2 - x^2 &= (x-\{x\})^2 - x^2\\
&= x^2 - 2\{x\}x + \{x\}^2 -x^2\\
&= -2x\{x\} + \{x\}^2\\
&= O(x)
\end{align*}
Using this fact in (\ref{eq:good_set_1}),
\begin{align}
|G| &= \sum_{1 \le d \le n}\mu(d) (\frac{n^2}{d^2} + O(\frac{n}{d}))\nonumber \\
&= n^2 \sum_{1 \le d \le n}\frac{\mu(d)}{d^2} +  O(n \sum_{1 \le d \le n}(\frac{\mu(d)}{d})) \label{eq:good_set_2}
\end{align}
Estimating the second term in (\ref{eq:good_set_2}):
\begin{align}
n \sum_{1 \le d \le n}(\frac{\mu(d)}{d}) &\le n (\sum_{1 \le d \le n}\frac{1}{d})\nonumber \\
&\le n \log{n} \label{eq:term_2_in_good_set}
\end{align}
Last step is derived by the asymptotic estimate of the sequence of Harmonic series. \\ \\
Estimating the first term in (\ref{eq:good_set_2}):\\
Using Euler's series, the following approximation can be done.
\begin{align}
M = \sum_{d=1}^{\infty} \frac{\mu(d)}{d^2} \sim \frac{6}{\pi^2} \label{eq:approx_M}
\end{align} \\
It can also be proven that
\begin{align}
|M-\sum_{1 \le d \le n} \frac{\mu(d)}{d^2}| \le \frac{1}{n}\label{eq:term_1_in_good_set}
\end{align}
Using (\ref{eq:good_set_2}), (\ref{eq:term_2_in_good_set}), (\ref{eq:approx_M}) and (\ref{eq:term_1_in_good_set}),
\begin{align*}
|G| &= n^2 (\frac{6}{\pi^2} + \frac{1}{n})+ O(n \log{n})\\
|G| &= n^2 \frac{6}{\pi^2} + O(n \log{n})\\
\frac{|G|}{n^2}&=\frac{6}{\pi^2} + O(1)
\end{align*}
Thus, as $n\rightarrow \infty$, the probability that two randomly chosen numbers do not have a common factor converges to $\frac{6}{\pi^2}$ $\sim$ $60\%$.
\end{proof}

\Lecture{Jayalal Sarma}{Sept 29, 2020}{09}{Surjections and Stirling numbers}{Raghul}{$\alpha$}{JS}

\section{Introduction}
In this lecture, we will look at another application of Principle of Inclusion-Exclusion(PIE) - counting number of surjections. Later, we will look at a concept related to that application - Stirling numbers of the second kind.

\section{Applications of PIE} \label{sec:Applications of PIE - lec2}
\subsection{Number of surjections from $[m]$ to $[n]$} \label{subsec:surjections application}
Consider $f : [m] \rightarrow [n]$. The total number of functions is $n^m$ - each element in $[m]$ has $n$ choices for its image. The number of injections is ${n \choose m}m!$ - the $m$ different images required can be chosen from $[n]$ in ${n \choose m}$ ways and then these images can assigned their pre-images from $[m]$ in $m!$ ways. The number of surjections is not that obvious and can be derived using PIE.\\
\begin{theorem}
The number of surjections from $[m]$ to $[n]$ is given by
$$\sum_{k=0}^{n} (-1)^k (n-k)^m {n \choose k}$$
\end{theorem}
\begin{proof}
Let $X$ be the set of all functions from $[m]$ to $[n]$. We know that
\begin{align}
    |X| = n^m \label{eq:surjection:size(X)}
\end{align}
Let us define $A_i$ ($\subseteq X$) for all $i\in[n]$ as follows.
$$A_i = \{f : [m] \rightarrow [n] ~|~ \forall j \in [m],~ f(j) \neq i\} $$
In other words, $A_i$ is the set of functions in which the element $i$ in $[n]$  does not have a pre-image and hence any element in $A_i$ is a non-surjection. The union of all the $A_i$'s will be the set of all non-surjections.\\
Clearly, $|A_i| = (n-1)^m$ : since each element in $[m]$ has only $n-1$ choices for its image. Similarly, $\forall i < j, ~|A_i\cap A_j| = (n-2)^m$ and so on. Thus, for any $I \subseteq [n]$,
\begin{align}
|A_I| = |\bigcap_{i \in I} A_i| = (n-|I|)^m \label{eq:surjection:size(A_I)}
\end{align}
Using PIE to find the number of non-surjections,
\begin{align}
|\bigcup_{i=1}^{n} A_i| &= \sum_{\emptyset \neq I \subseteq [n]} (-1)^{|I| +1} |A_I|\nonumber\\
&= \sum_{k=1}^{n} (-1)^{k+1} \sum_{I \subseteq [n], |I| = k} |A_I|\nonumber\\
&= \sum_{k=1}^{n} (-1)^{k+1} \sum_{I \subseteq [n], |I| = k} (n-k)^m \nonumber\tag{By \ref{eq:surjection:size(A_I)}}\\
&= \sum_{k=1}^{n} (-1)^{k+1} (n-k)^m {n \choose k} \label{eq:surjection:size(unionA_i)}
\end{align}
Therefore, the number of surjections is given by
\begin{align*}
|X \setminus \bigcup_{i=1}^{n} A_i| &= |X| - |\bigcup_{i=1}^{n} A_i|\\
&= n^m - \sum_{k=1}^{n} (-1)^{k+1} (n-k)^m {n \choose k} \tag{using \ref{eq:surjection:size(X)} and \ref{eq:surjection:size(unionA_i)}}\\
&= (-1)^0 (n-0)^m {n \choose 0}+ \sum_{k=1}^{n} (-1)^{k} (n-k)^m {n \choose k}\\
&= \sum_{k=0}^{n} (-1)^{k} (n-k)^m {n \choose k}
\end{align*}
This completes the proof.
\end{proof}
\noindent\\
\section{Stirling numbers of the second kind}
Let us now look at another way of counting the number of surjections - in terms of Stirling numbers of the second kind. The number of ways of partitioning $[n]$ into $k$ non-empty parts, where neither the order of the parts nor the order of elements within a part matter, is denoted by ${n \brace k}$ and is a Stirling number of the second kind. \\
For example; ${4 \brace 1} = 1$ because [1,2,3,4] is the only way of partitioning, ${4 \brace 2} = 7$ because $[1,2,3|4]$, $[1,2,4|3]$, $[1,3,4|2]$, $[2,3,4|1]$, $[1,2|3,4]$, $[1,3|2,4]$ and $[1,4|2,3]$ are the ways of partitioning, ${4 \brace 3} = 6$ because $[1,2|3|4]$, $[1,3|2|4]$, $[1,4|2|3]$, $[1|2,3|4]$, $[1|2,4|3]$ and $[1|2|3,4]$ are the ways of partitioning and ${4 \brace 4}$ = 1 because $[1|2|3|4]$ is the only way of partitioning.\\ \\
Let us now count the number of surjections from $[m]$ to $[n]$ in terms of Stirling numbers of the second kind. We know that in a surjection, every element in the co-domain $[n]$ has at least one pre-image. So, we could partition the domain $[m]$ into $n$ non-empty parts such that all the elements within a part have the same image in the co-domain. (For example; for $f : [5] \rightarrow {0,1,2}$, $f(x) = x ~mod~3 $, the partition of the domain is $[1,4|2,5|3]$.) Such a partition could be done in ${m \brace n}$ ways and then each of these parts can be assigned to one element in $[n]$ in $n!$ ways. Thus the number of surjections from $[m]$ to $[n]$ in terms of Stirling numbers of the second kind is ${m \brace n}n!$. \\ \\
We have counted the number of surjections in 2 different ways (using PIE and in terms of ${m \brace n}$). These two values should be equal and equating them would give us an expression for ${m \brace n}$ as follows.
\begin{align*}
    {m \brace n}n! &= \sum_{k=0}^{n} (-1)^{k} (n-k)^m {n \choose k}\\
    {m \brace n} &= {\frac{1}{n!}}\sum_{k=0}^{n} (-1)^{k} (n-k)^m {n \choose k}
\end{align*}
It is to be noted that by convention, ${0 \brace 0} = 1$ and $\forall n>0, {n \brace 0} = {0 \brace n} = 0$. \\
\begin{theorem} For any $n,k \in \N$;
$${n \brace k} = {n-1 \brace k-1} + k {n-1 \brace k}$$
\end{theorem}
\begin{proof}
We shall use double counting to prove this theorem. Let us count the number of ways of partitioning $[n]$ into $k$ non-empty parts.\\ Clearly, the L.H.S. of the equation is the number of ways of partitioning $[n]$ into $k$ non-empty parts. \\
Consider the element $n$ in $[n]$; in a partition, this element can either be in a part of size $1$ or a part of size $\geq 2$. The number of partitions in which $n$ is in a part of size $1$ is ${n-1 \brace k-1}$ : $n$ is the only element in a part and then the remaining $n-1$ elements are to be partitioned into $k-1$ non-empty parts. The number of partitions in which $n$ is in a part of size $\geq 2$ is $k {n-1 \brace k}$ : the remaining $n-1$ elements are to be partitioned into $k$ non-empty parts and then $n$ is added to one of those parts in $k$ ways. Thus, the total number of partitions is ${n-1 \brace k-1} + k {n-1 \brace k}$, which is the R.H.S. of the equation.\\
These two methods have counted the same value and hence should be equal.
\end{proof}
\noindent
The equation stated in the theorem above is actually a very important property of Stirling numbers of the second kind. It is often used to connect any function or a set of numbers with the Stirling numbers of the second kind. \\
\section{Instances of Stirling numbers of the second kind}
Following are some of the instances where Stirling numbers of second kind appear.
\subsection{$n^{th}$ derivative of $e^{e^x}$}
The $n^{\text{th}}$ derivative of the function $f(x) = e^{e^x}$ is given by
    $$f^{(n)}(x) = f(x) \sum_{k=0}^{\infty}{n \brace k} e^{kx}$$
\subsection{Falling factorials of $x$}
We know that polynomials in one variable $x$ (like $4x^2+3x+2$, $10x^3+9x$, etc.) can be expressed as a linear combination of the powers of $x$ i.e. $x^0,x^1,x^2,\ldots$. Thus, the powers of $x$ are said to form a basis for such polynomials. \\
    The falling factorials of $x$ form another basis for polynomials in one variable $x$. The falling factorials are given by
    \begin{align*}
        (x)_0 &= 1 &
        (x)_1 &= x\\
        (x)_2 &= x(x-1) &
        for~ any~k > 0,~ (x)_k &= x(x-1)(x-2)\ldots(x-k+1)
    \end{align*}
    One can easily prove that the falling factorials form a basis for polynomials if it can be proved that $\forall n$, $x^n$ is a linear combination of falling factorials (for any polynomial, write the polynomial as a linear combination of $x^n$'s and then replace $x^n$'s with the corresponding linear combinations of $(x)_n$'s).
\begin{theorem}Powers of $x$ can be written as the linear combination of falling factorials of $x$ using the following equation.
    $$\forall n, x^n \equiv \sum_{k=0}^n {n \brace k} (x)_k$$
\end{theorem}
    \begin{proof} (Note: This proof was done during the discussion session - not in the lecture video.)\\
    Let the polynomial on the L.H.S. be $P(x)$ and that on the R.H.S. be $Q(x)$. In order to prove that $P(x) \equiv Q(x)$, it is sufficient to prove that $P(x) = Q(x)$ for sufficiently large number of distinct values of $x$. The reasoning for the same is as follows.\\
    One can clearly see that the degree of both $P(x)$ and $Q(x)$ is $n$. So, the maximum degree of the polynomial $R(x) = P(x) - Q(x)$ is also $n$. This implies that the maximum number of roots for the equation $R(x)=0$ is $n$. Therefore, if one can prove that $R(x)=0$ for at least $n+1$ distinct values of $x$, then it must be the case that $R(x) \equiv 0$ and hence $P(x) \equiv Q(x)$.\\
    So, all we have to do now is to prove that $P(x) = Q(x)$ for at least $n+1$ distinct $x$'s where $n$ is the degree of the polynomial $P(x)$. Let us use double counting to prove this.\\
    \noindent\\
    Let $x$ be any natural number. Let us count the number of different strings of length $n$ over \{$1,2,3\ldots x$\} in two different ways.
    \begin{enumerate}
        \item Each character in the string can be chosen in $x$ ways and there are $n$ characters in total. Therefore the count is $x^n$ ($=P(x)$).
        \item Let there be $k$ distinct characters in our string. Clearly, $0 \leq k \leq n$ and different values of $k$ would lead to different strings. So, we have to do summation over the value of $k$. Now, let us partition the $n$ available spaces into $k$ non-empty parts - so that spaces within the same part will get the same character and spaces in different parts get different characters. This partitioning can be done in ${n \brace k}$ ways. There are $k$ parts now and we have to assign one character each to these parts from \{$1,2,3\ldots x$\}. The character for the first part can be chosen in $x$ ways, for the second part it is $(x-1)$ ways, for the third part it is $(x-2)$ ways and so on until $(x-k+1)$ ways for the $k^{\text{th}}$ part. Therefore, the count here is given by
        \begin{align*}
            \sum_{k=0}^{n}{n \brace k} x(x-1)(x-2)\ldots(x-k+1) = \sum_{k=0}^{n}{n \brace k} (x)_k = Q(x)
        \end{align*}
    \end{enumerate}
    These two methods count the same number and hence they should be equal. Therefore, $\forall x \in \N, ~ P(x)=Q(x)$, irrespective of the value of $n$. This means that for any $n$, we have proven that $P(x)=Q(x)$ for an infinite number of values of $x$. Hence, $\forall n,~P(x)\equiv Q(x)$.
    \end{proof}
\section{Other interesting types of numbers}
\subsection{Bell numbers ($B_n$) }
    The number of ways of partitioning $[n]$ into non-empty parts is given by the Bell number $B_n$. It can clearly be seen that
    $$B_n = \sum_{k=0}^{n} {n \brace k}$$
    \begin{figure}[h]
        \centering
         \includegraphics[scale = 0.7]{images/Stirling1.png}
        \caption{Permutations on 4 elements with 2 cycles }
        \label{Fig:StirlingI}
    \end{figure}
\subsection{Stirling numbers of the first kind (${n \brack k}$)} The number of ways of permuting $n$ elements such that the permutations have $k$ cycles is given by the Stirling number of the first kind ${n \brack k}$. Figure \ref{Fig:StirlingI} shows all possible ways of permuting 4 elements with 2 cycles (${4 \brack 2} = 11$). From the definition of ${n \brack k}$, it can clearly be seen that $$n! = \sum_{k=0}^{n} {n \brack k}$$

\Lecture{Jayalal Sarma}{Sept 29, 2020}{10}{Tutte’s Matrix Tree Theorem and counting arborescences}{Raghul}{$\alpha$}{JS}
\section{Introduction}
In this lecture, we will be looking at another application of the Principle of Inclusion-Exclusion(PIE) - Matrix Tree Theorem. We will understand the theorem and then we will cover all the bases required to prove the theorem. The proof of the theorem will be completed in the next lecture.

\section{Kirchoff’s Matrix Tree Theorem} \label{sec:kirchoff's application}
The original theorem for undirected graphs was stated by Kirchoff in the 19th century and the generalised verion for directed graphs was stated by Tutte in the 20th century. This theorem is a classical bridge between combinatorial and algebraic quantities. Let us define few important terms before we jump into the theorems and proofs.\\
\begin{definition}\textbf{Laplacian Matrix for undirected graphs:}
For any undirected graph $G(V,E)$ with $n$ vertices, let us define a $n$x$n$ matrix $L(G)$ called the \textit{Laplacian matrix} of $G$ as follows.
\[
  L(G)_{ij} =
  \begin{cases}
    deg(v_i) &\mbox{if }~ i = j\\
    -1 &\mbox{if }~ i \neq j ~\text{and}~(v_i,v_j)\in E\\
    0 &\mbox{otherwise}
  \end{cases}
\]
\end{definition}
\noindent
It can also be noted that for a graph $G(V,E)$ without any self edges (i.e. $\forall i, ~ (v_i,v_i) \notin E$), the Laplacian matrix can also be defined as $L(G) = D - A$ where $D$ is a diagonal matrix with $D_{ii} = ~deg(v_i)$ and $A$ is the adjacency matrix of $G$.
\begin{theorem} Matrix Tree Theorem for undirected graphs by Kirchoff:\\
For any undirected graph $G(V,E)$, the number of different spanning trees rooted at $v_i$ contained in $G$ is given by $det(L_G[i])$ where $L_G[i]$ refers to the matrix obtained by removing the $i^{\text{th}}$ row and the $i^{\text{th}}$ column from $L(G)$ (for any $i \in [n]$).
\end{theorem}
\noindent
Note that the theorem has connected a combinatorial quantity to an algebraic one. It should also be noted that $det(L_G[i])$ is the same for every value of $i$ (since the number of undirected spanning trees does not change with the root $v_i$). The usual proof of this theorem is done using induction on the number of vertices. Instead we will use PIE to prove the generalised version and this theorem will follow as a consequence. Before doing the proof, let us cover few other concepts required for the proof.
\section{Determinant of a Matrix}\label{sec:determinant of a matrix}
From high school mathematics; we all know that for a 2x2 matrix $A$ and a 3x3 matrix $B$, the determinants are given by
\begin{align*}
  det(A) &= a_{11}a_{22}-a_{12}a_{21}\\
  det(B) &= b_{11}b_{22}b_{33}-b_{11}b_{23}b_{32}-b_{12}b_{21}b_{33}+b_{12}b_{23}b_{31}+b_{13}b_{21}b_{32}-b_{13}b_{22}b_{31}
\end{align*}
It is to be noticed that in the determinant expression of a $n$x$n$ matrix, the subscripts in each term match with one of the $n!$ possible permutations on $[n]$ and there are $n!$ terms in the expression. For example; the first term in the expression for $|A|$ represents the permutation $[1\rightarrow1; ~2\rightarrow2]$ and the other term represents $[1\rightarrow2; ~2\rightarrow1]$. Similarly, the second term in the expression for $|B|$ represents $[1\rightarrow1; ~2\rightarrow3;~3\rightarrow2]$ while the fifth term represents $[1\rightarrow3; ~2\rightarrow1;~3\rightarrow2]$.\\
Thus, each term in determinant expression of a $n$x$n$ matrix represents one of the permutations of $[n]$ and all the permutations are represented exactly once. In other words, given a permutation $\sigma$ on $[n]$, the term $\prod_{i=1}^{n} a_{i\sigma(i)}$ appears exactly once in the expression of the determinant of a $n$x$n$ matrix $A$.\\
Given any permutation $\sigma$ on $[n]$, we can represent it in the point representation as a $n$-tuple as $(\sigma(1),\sigma(2),\sigma(3)\ldots \sigma(n))$. We can define the number of inversions of $\sigma$ ($Inv(\sigma)$) as follows.
$$Inv(\sigma) = |\{(i,j)~|~i<j~\text{and}~\sigma(i)>\sigma(j)\}|$$
For example; for the permutation $\sigma_1 = (1,3,2)$, $Inv(\sigma_1) = 1$ (since (2,3) is the only such $(i,j)$ pair); for $\sigma_2 = (3,1,2)$, $Inv(\sigma_2) = 2$ (since (1,2) and (1,3) are the $(i,j)$ pairs) and for $\sigma_3 = (3,2,1)$, $Inv(\sigma_3) = 3$ (since (1,2), (2,3) and (1,3) are the $(i,j)$ pairs). \\
It can be noticed that the sign of a term representing the permutation $\sigma$ in the determinant expression is given by
$$Sign(\sigma) = (-1)^{Inv(\sigma)}$$
From the inferences done above, one can logically guess the determinant expression for a $n$x$n$ matrix $A$ in terms of
$Sign(\sigma)$ and $\prod_{i=1}^{n} a_{i\sigma(i)}$. However, until proven mathematically, this remains nothing more than a logical guess. So, let us state this as a theorem and prove it.
\begin{theorem}
For any $n \in \N$, the determinant of the $n^{\text{th}}$ order square matrix $A$ is given by
$$det(A) = \sum_{\sigma \in S_n} Sign(\sigma)  \prod_{i=1}^{n} a_{i\sigma(i)}$$
where $S_n$ is the set of all permutations on $[n]$.
\end{theorem}
\begin{proof}
We know that the determinant of any matrix $A$ follows the following four properties.
\begin{enumerate}
    \item If all the elements in a row of $A$ are 0, then $det(A)=0$
    \item If two rows of $A$ are identical, then $det(A)=0$
    \item If a row of $A$ is a multiple of another row, then $det(A)=0$
    \item Adding the multiple of a row of $A$ to another row, does not change the value of $det(A)$
\end{enumerate}
Though not done as part of the lecture, it can be proven that there is only one expression in terms of $a_{ij}$'s that satisfies all the four properties. Therefore, it is sufficient to prove that the expression given in the theorem satisfies all the four properties stated above to prove the whole theorem. \\
Let us now prove the first property : Let all the elements in row $k$ be 0 i.e. $\forall_{j\in[n]}~ a_{kj} = 0$. It can clearly be seen that each term in the determinant expression stated in the theorem has some $a_{k\sigma(k)}$ in it. So each term will be 0 and hence $det(A)=0$. \\
Proving that the expression stated in the theorem satisfies the other three properties is left as an exercise for the students.
\end{proof}

\section{Applications of PIE} \label{sec:Applications of PIE - lec3}
\subsection{Tutte’s Matrix Tree Theorem} \label{subsec:tutte's application}
 Now, let us continue our journey towards stating and proving Tutte's Matrix Tree Theorem. Firstly, let us define Spanning Arborescences - the directed graphs equivalent for spanning trees and Laplacian matrix for directed graphs.
\begin{definition}\textbf{Spanning Arborescences:} An \textit{Arborescence} is a directed graph in which a vertex $u$ is called the root and for every other vertex $v$ in the graph, there is exactly one directed path from $u$ to $v$. In simpler terms, an arborescence is an directed tree in which all the edges are directed away from the root. A \textit{Spanning Arborescence} $S(V,E)$ of a directed graph $G(V',E')$ is an arborescence such that $V=V'$ and $E\subseteq E'$.
\end{definition}
\noindent\\
\begin{definition}\textbf{Laplacian matrix for directed graphs:} For any directed graph $G(V,E)$ with $n$ vertices, let us define a $n$x$n$ matrix $L(G)$ called the \textit{Laplacian matrix} of $G$ as follows.
\[
  L(G)_{ij} =
  \begin{cases}
    indeg(v_i) &\mbox{if }~ i = j\\
    -1 &\mbox{if }~ i \neq j ~\text{and}~(v_i,v_j)\in E\\
    0 &\mbox{otherwise}
  \end{cases}
\]
\end{definition}
\begin{theorem} Tutte's Matrix Tree Theorem for directed graphs\\
For any directed graph $G(V,E)$, the number of different spanning arborescences rooted at $v_i$ contained in $G$ is given by $det(L_G[i])$ where $L_G[i]$ refers to the matrix obtained by removing the $i^{\text{th}}$ row and the $i^{\text{th}}$ column from $L(G)$ (for any $i \in [n]$).
\end{theorem}
\noindent
Note that since spanning arborescences are directed, the number of spanning arborecences depend on the chosen root. Hence, unlike the undirected case, $det(L_G[i])$ here depends on the value of $i$. Without loss of generality, we can choose $i = n$ for our proof. Therefore, all we should prove is the number of spanning arborescences rooted at $v_n$ for the directed graph $G$ is given by
\begin{align}
    det(L_G[n]) = \sum_{\sigma \in S_{n-1}}~
    Sign(\sigma)~\prod_{i=1}^{n-1}l_{i\sigma(i)}
    \label{eq:to_prove:Tutte}
\end{align}
The R.H.S. of the equation is the determinant expression for the $(n-1)$x$(n-1)$ matrix $(L_G[n])$.\\Now let us define another type of directed graphs called Spregs to help with our proof process.\\
\noindent\\
\begin{definition}\textbf{Spregs:} Single prdecessor graphs or \textit{Spregs} with distinguished vertex $v$ of a directed graph $G(V,E)$ is a subgraph $T(V,E')$, $E' \subseteq E$, such that each vertex in $T$ except the vertex $v$ has exactly one predecessor and the vertex $v$ has no predecessors. In other words; in the spreg T, $indeg(v) = 0$ and for every $u \neq v$, $indeg(u)=1$.\\
\end{definition}
\begin{figure}[h]
    \centering
    \includegraphics[scale = 0.5]{images/Spreg1.png}
    \caption{Both spreg and arborescence}
    \label{Fig:Spreg1}
\end{figure}
\begin{figure}[h]
    \centering
    \includegraphics[scale = 0.6]{images/Spreg2.png}
    \caption{Spreg but not arborescence}
    \label{Fig:Spreg2}
\end{figure}
\noindent\\
It is important to distinguish between spregs and spanning arborescences : spregs may contain disconnected components and cycles in them. On the other hand, spanning arborescences are directed spanning trees and hence are single connected components and do not have cycles in them. The directed graph in figure \ref{Fig:Spreg1} is a spreg with distinguished vertex $A$ and an arborescence rooted at $A$. On the other hand, the graph in figure \ref{Fig:Spreg2} is a spreg with distinguished vertex $A$ but not an arborescence. Now let us consider the following lemma and prove it.
\noindent\\
\begin{lemma} If $T(V,E)$ is a spanning arborescence rooted at $v$, then $T$ is a spreg with distinguished vertex $v$.
\end{lemma}
\begin{proof}
Let $T(V,E)$ is a spanning arborescence rooted at $v$. We know from the definition that for every other vertex $u$ in $T$, there is a unique directed path from $v$ to $u$. The underlying undirected graph of $T$ is a tree and does not have any cycles and hence there should not be any cycles (directed/undirected) in $T$.\\
Let us now assume that $indeg(v) \neq 0$. This means that there exists a vertex $u$ in $T$ such that the edge $e = (u,v)\in E$. We know that there is a unique path in $T$ from $v$ to $u$ - let that path be $P$. Now the path $P+e$ is a directed cycle in $T$. A contradiction. Therefore, $indeg(v) = 0$.\\
Let us now assume that for some $u \neq v$ in $T$, $indeg(u) = 0$. This implies that T is not a spanning arborescence.  A contradiction. Therefore, $indeg(u) > 0$. \\
Let us now assume that for some $u \neq v$ in $T$, $indeg(u) \geq 2$. This implies $\exists u_1 \neq u_2$ such that $e_1 = (u_1,u) \in E$ and $e_2 = (u_2,u) \in E$. We know that there exists a unique path $P_1$ from $v$ to $u_1$ and another path $P_2$ from $v$ to $u_2$. Since $u_1 \neq u_2$, $P_1 \neq P_2$. Now, $P_1+e_1$ and $P_2+e_2$ are two distinct paths from $v$ to $u$. A contradiction. Therefore, $indeg(u) = 1$.\\
Therefore,  $indeg(v) = 0$ and for every other vertex $u$, $indeg(u) = 1$. In other words, $T$ is a spreg with distinguished vertex $v$.
\end{proof}
\noindent It is important to note that the converse of the above stated lemma is not true because spregs may contain discconnected components and cycles in them. Now, we will look at another lemma.
\noindent\\
\begin{lemma} If $T(V,E)$ is a spreg with distinguished vertex $v$, then the spreg consists of an arborescence rooted at $v$ and zero or more weakly connected components (the underlying undirected component is connected). Each of these weakly connected components have exactly one directed cycle in them.
\end{lemma}
\begin{proof}
The proof of this lemma is left as an exercise for the students to complete.
\end{proof}
\noindent Thus; (a spreg  with distinguished vertex $v$) = (an arborescence rooted at $v$) + $k$ (weakly connected components with one directed cycle each); where $k \geq 0$. \\
\noindent\\
For proving Tutte's theorem; the idea to count the number of arborescences rooted at $v_n$ is that we would count the number of spregs with distinguished vertex $v_n$ and then remove the number of spregs that are not arborescences - the terms in such a expression would exactly match with that of the R.H.S. of \ref{eq:to_prove:Tutte}.\\
\noindent\\
In the R.H.S. of \ref{eq:to_prove:Tutte}, consider the term for $\sigma =$ identity permutation i.e. $\forall i,~ \sigma(i)=i$. Clearly, $Sign(\sigma)=1$ since $Inv(\sigma)=0$. The term would be $+ \prod_{i=1}^{n-1}l_{ii}$. This is exactly equal to the total number of spregs with distinguished vertex $v_n$ - the reasoning is as follows.\\
Since $v_n$ is the distinguished vertex, ignore all the edges whose end vertex is $v_n$. For every other vertex $u$, choose exactly one of the edges whose end vertex is $u$ ($\prod_{i=1}^{n-1}indeg(v_i)$ ways). Clearly, such a subgraph is a spreg - by definition of spregs. Therefore, the number of distinct spregs is $\prod_{i=1}^{n-1}indeg(v_i) = \prod_{i=1}^{n-1}l_{ii}$ (by the definition of Laplacian matrix). \\
\noindent\\
We have counted all the spregs; now, spregs with cycles have to be removed from the count. This part of the proof involves PIE and will be done in the next lecture.


The Integrated Information Theory (IIT) has is proposed as a mathematical way to understand consciousness.
It revolves around analyzing the phenomenology of a system, that is, how a system experiences the environment.
IIT 3.0 mostly does this by finding the maximally irreducible conceptual structures formed by a causal structure interacting with the environment.
The theory tries to assume properties of consciousness (axioms), and from there, it postulates the properties that must be necessary for a physical substrate hosting the system.
The causal structure, also called a cause-effect structure (CES), is analyzed to find conceptual structures that measure how well a system integrates information.
A more substantial amount of integrated information results in a higher amount of possible states in the system.
Integrated information is when there is no way to cut the CES without losing information.
The CES is an unfolding of a model of the neural substrate in the sense that the model is cut in every possible way (imagine cutting a network of nodes).
The CES maps to the properties of experience, and the CES can be quantified by $\Phi$ \cite{oizumi_phenomenology_2014}.

Although IIT might seem overly abstract, the first tangible result was published as a study on the question "Why does space feel the way it does?".
Here a model of the Visual Cortex 1 and 2 (V1 and V2) was cut into a CES, using the knowledge of the grid cells that are proven to be essential for localization \cite{haun_why_2019}.

\paragraph{A summary of corollaries} of IIT, based on the article by Oizumi et. al \cite{oizumi_phenomenology_2014}:
An intelligent system will usually consist of a main \textbf{complex}, and smaller supporting complexes.
This central complex will be the most conscious part of the system, like the part of our brain that we could not function without, while the supporting complexes could be compared to smaller parts of the brain, like, for example, the visual cortex.
Intelligent systems will not be modular, that is, if the system produces less functionality than their components, and they have to produce functionality that is more than a higher order of the combined components.
Inactive systems can be conscious in the way that a system may have significant parts that are ready to be activated or that are passively affecting the state of the system.
A system can perform very complex functions but still not be conscious.
In particular, feed-forward networks would not be conscious.
An example if this is a microprocessor implementing a neural network that, in some cases, can recognize thousands of different objects faster than a human can recognize one object.
IIT states that it is not only the functionality of a system that determines how conscious it is but also how the function performs internally.
A network that can recognize objects based on internal states and previous experiences is more conscious compared to a feed-forward neural network, which only recognizes the object based on the external input it gets.
Networks that are not necessarily feed-forward only, but simulated on a physical substrate that implements functionality based on numerical approximation, would not be termed conscious in IIT 3.0 \cite{marshall_integrated_2016}.
A final corollary that summarises the ones above says that an intelligent system can develop concepts based on other concepts within itself without the need for external stimuli.
These internal concepts would more often be connected to a large number of other concepts and not contribute to specific details.

\paragraph{In this project} I hope to utilize IIT as a way to analyze the perception of automated agents, evolved as SNN \vref{sect:snn} animats \vref{sect:agent} on BrainScaleS \vref{sect:bss}.
As the complexity and states of the animats are known, the animats can be analyzed.
Analyzing the animats in regards to IIT will only be attempted if time permits.