\chapter{Syntactic Model of \lang} \label{ch:model}

\input{figures/cic.tex}
\input{figures/definitions.tex}
\input{figures/translation.tex}

\lang is modelled in
\CICE,\index{Calculus of Inductive Constructions!Extensional \textasciitilde}
as briefly described in \cref{ch:introduction}.
The key idea is that sizes in \lang can themselves be represented as a inductive type in \CICE,
and naturals and well-founded trees are then inductives with an additional size parameter.
Sizes are represented as a (generalization of) the Brouwer notation for ordinals in type theory,
and their order as an inductive type indexed by sizes.
The order is \emph{well founded}:
there is no infinite sequence of ever-smaller sizes,
and there is always a ``smallest'' size (or many of them).
This property allows for \emph{well-founded induction}\index{well-founded induction},
where to prove some property on sizes, one supposes that it holds for all strictly smaller sizes.

Every fixpoint expression in \lang is modelled as an instance of well-founded induction in \CICE.
To prove well-foundedness and in turn the induction principle,
I show that sizes satisfy an \emph{accessibility predicate}\index{accessibility predicate}~\citep{accessibility}.
For the type preservation proof to go through,
\emph{definitional proof irrelevance}\index{proof irrelevance} of accessibility predicates
is required---every proof of accessibility is definitionally equal to one another.
This holds in extensional type theory via equality reflection\index{equality reflection}
but not in intensional type theory,
which is why an extensional CIC is used.

The first half of this chapter provides the syntax and judgements of \CICE.
In addition to the notation used in \cref{ch:sized-dep-types},
given variables $\vec{\xT} = \xT_1 \seq \xT_n$,
terms $\vec{\eT} = \eT_1 \seq \eT_n$,
and types $\vec{\tauT} = \tauT_1 \seq \tauT_n$,
\new{$\annotT{\vec{\xT}}{\vec{\tauT}}$} denotes the assumption environment
$\annotT*{\xT_1}{\tauT_1}, \seq, \annotT*{\xT_n}{\tauT_n}$,
\new{$\subst{\eT}{\vec{\xT}}{\vec{\eT}}$} denotes the simultaneous substitution
$\subst{\eT}{\xT_1, \seq, \xT_n}{\eT_1, \seq, \eT_n}$,
\new{$\funT{\vec{\xT}}{\vec{\tauT}}{\eT}$} denotes the $n$-ary function
$\funT{\xT_1}{\tauT_1}{\seq \funT{\xT_n}{\tauT_n}{\eT}}$, and
\new{$\type{\GammaT}{\vec{\eT}}{\vec{\tauT}}$} denotes the $n$ typing judgements
$(\type{\GammaT}{\eT_1}{\tauT_1})$, \seq, $(\type{\GammaT, \annotT{\eT_1}{\tauT_1}, \seq, \annotT{\eT_{n-1}}{\tauT_{n-1}}}{\eT_n}{\tauT_n})$.

The second half then describes the translation from \lang to \CICE,
which is a metafunction from typing derivations of \lang to terms of \CICE.
Therefore, the translation is only defined for well-typed \lang terms,
but the type preservation theorem only applies to well-typed terms anyway.

\section{Target Type Theory} \label{sec:target}

\FigSyntaxCIC{fig:syntax-cic}
The syntax of \CICE
is given in \cref{fig:syntax-cic};
differences from \lang include a 1-based index for the recursive argument of fixpoint expressions,
$\tg{case}$ expression motives abstracted over the target's inductive type indices,
and a homogeneous propositional equality\index{propositional equality} type with the reflexivity constructor and $\JT*$ eliminator.
New inductive types are defined using data definitions $\DT$,
whose syntax resembles the informal presentation used in \cref{ch:sized-dep-types}.
Metavariable usage convention is roughly the same as for \lang,
with the addition of $\pT$ for inductive type parameters or proofs of equality
and $\aT$ for inductive type indices.

The well-formedness conditions on inductive data definitions,
such as well-typedness and \emph{strict positivity}\index{strict positivity},
are entirely standard, so I omit them here;
see pCIC\index{Calculus of Inductive Constructions!Predicative \textasciitilde}~\citep{pCIC}
for instance for a full description.
Inductive definitions in their full generality are not needed,
and nonmutual, nonnested inductives suffice.
Indeed, only six inductive definitions are used for the translation,
for representing sizes, their order, their well-foundedness,
and the empty type, naturals, and well-founded trees.

The typed equivalence\index{equivalence}, subtyping, and typing judgements are defined mutually:
equivalence depends on typing and subtyping,
subtyping depends on equivalence,
and typing depends on subtyping and equivalence.
The mutual dependence is due to typed equivalence,
since with untyped conversion as seen in \lang has no typing premises.
I present first the equivalence rules in \cref{fig:equivalence},
with the subtyping and typing rules to follow.

Equivalence is, by definition, an equivalence relation,
satisfying reflexivity, symmetry, and transitivity.
Equivalence is also congruent, using the same summary of congruence rules as for \lang via \rref{equiv-cong};
the full set of rules can similarly be found in \cref{app:cong:equiv}.
An equivalence judgement can be converted to one annotated by a supertype via \rref{equiv-conv}.
The key rule for extensionality is equality reflection\index{equality reflection} in \rref{equiv-reflect},
which definitionally equates two terms whenever there exists some proof of their propositional equality.

\FigEquiv{fig:equivalence}

\clearpage
Typed equivalence is required in the presence of equality reflection since
inconsistencies are derivable when using untyped conversion\index{conversion}.
For instance, supposing that \lang had equality reflection and using \new{$\approx$} to denote conversion,
in the empty environment, freely using transitivity,
%
\begin{align*}
  \const{0'} &\approx \app{(\fun{p}{\eq{\const{0'}}{\N{\hat{\hat{\circ}}}}{\const{1}}}{\const{0'}})}{\refl{\const{0'}}} &&\textrm{by $\beta$-reduction} \\
  &\approx \app{(\fun{p}{\eq{\const{0'}}{\N{\hat{\hat{\circ}}}}{\const{1}}}{\const{1}})}{\refl{\const{0'}}} &&\textrm{by congruence and reflection of $p$} \\
  &\approx \const{1} &&\textrm{by $\beta$-reduction},
\end{align*}
since reduction and therefore conversion occurs even when its terms are ill typed,
as the second and third terms are.
An alternate solution would be to disallow transitivity of conversion~\citep{CCE},
but this is too limiting when trying to prove type preservation,
and equivalence would no longer be an equivalence relation.

Untyped conversion with equality reflection also violates subject reduction
under certain environments.
For example, suppose the environment contains the equality $\eq{\arr*{\N{\sss{\circ}}}{\N{\sss{\circ}}}}{}{\arr*{\N{\sss{\circ}}}{\Prop}}$.
Then $\app{(\fun{x}{\N{\sss{\circ}}}{x})}{\const{0}}$ can be assigned type $\Prop$
by equality reflection and conversion of the function's type,
but this term reduces to $\const{0}$ which \emph{cannot} be assigned type $\Prop$.
This can be resolved by adding
\emph{injectivity of type constructors}\index{injectivity of type constructors},
which would allow deriving the equality $\eq{\N{\sss{\circ}}}{}{\Prop}$
from the above, but doing so is generally undesirable since it's inconsistent with
the axioms of both excluded middle and univalence \citep{unification}.

The remaining equivalence rules are typed versions of the usual reduction rules,
with typing premises to ensure well-typedness of both sides.
Functions have both a $\beta$-equivalence rule and an $\eta$-equivalence rule,
the latter of which is only possible since equivalence is typed.
Equivalence rules for $\tg{let}$ expressions are exactly the same as in \lang.
The $\JT*$ eliminator and $\tg{case}$ expressions reduce when applied to
reflexivity and inductive constructors, respectively.

\rref{equiv-mu} for fixpoint expressions is \emph{unguarded}\index{guarded reduction},
meaning that fixpoints are equivalent to the substitution of itself into its own body
regardless of what they are applied to.
To maintain normalization,
the usual guarded reduction rule in intensional CIC reduces fixpoints
only when applied to a literal constructor in the recursive argument position.
\vspace{-0.25\baselineskip}
\begin{mathpar}
\inferrule[\rlabel{$\equiv$-$\mu$-guarded}{equiv-mu-guarded}]{\cdots \\ \card{\vec{\eT}'} + 1 = \nT}{
  \defeq{\GammaT}{\app{(\fixT{\nT}{\fT}{\tauT}{\eT})}{\vec{\eT}'}{(\app{\cT}{\vec{\aT}})}}{\app{(\subst{\eT}{\fT}{\fixT{\nT}{\fT}{\tauT}{\eT}})}{\vec{\eT}'}{(\app{\cT}{\vec{\aT}})}}{\tauT}
}
\end{mathpar}

Evidently \rref{equiv-mu-guarded} can be derived from \rref{equiv-mu} by congruence.
On the other hand, for any particular inductive type $\XT$,
letting $\tauT$ be $\arr{\vec{\xT}}{\vec{\sigmaT}}{\funtypeT{\xT}{\app{\XT}{\vec{\pT}}{\vec{\aT}}}{\tauT'}}$,
\rref{equiv-mu} can be derived from \rref{equiv-mu-guarded} via reflection of the following provable propositional equality,
freely using transitivity:

\begin{align*}
\fixT{\nT}{\fT}{\tauT}{\eT} &\eq{}{}{} \funT{\vec{\xT}}{\vec{\sigmaT}}{\funT{\xT}{\app{\XT}{\vec{\pT}}{\vec{\aT}}}{\app{(\fixT{\nT}{\fT}{\tauT}{\eT})}{\vec{\xT}}{\xT}}}
\qquad \textrm{definitionally by \rref{equiv-eta}} \\
& \eq{}{}{} \funT{\vec{\xT}}{\vec{\sigmaT}}{\funT{\xT}{\app{\XT}{\vec{\pT}}{\vec{\aT}}}{\matchT*{\xT}{\seq(\app{\cT}{\vec{\zT}} \RightarrowT \app{(\fixT{\nT}{\fT}{\tauT}{\eT})}{\vec{\xT}}{(\app{\cT}{\vec{\pT}}{\vec{\zT}})})\seq}}} \\
& \phantom{\eq{}{}{}} \textrm{by congruence and case analysis on $\xT$} \\
& \eq{}{}{} \funT{\vec{\xT}}{\vec{\sigmaT}}{\funT{\xT}{\app{\XT}{\vec{\pT}}{\vec{\aT}}}{\matchT*{\xT}{\seq(\app{\cT}{\vec{\zT}} \RightarrowT \app{(\subst{\eT}{\fT}{\fixT{\nT}{\fT}{\tauT}{\eT}})}{\vec{\xT}}{(\app{\cT}{\vec{\pT}}{\vec{\zT}})})\seq}}} \\
& \phantom{\eq{}{}{}} \textrm{definitionally by \rref{equiv-cong, equiv-mu-guarded}} \\
& \eq{}{}{} \funT{\vec{\xT}}{\vec{\sigmaT}}{\funT{\xT}{\app{\XT}{\vec{\pT}}{\vec{\aT}}}{\app{(\subst{\eT}{\fT}{\fixT{\nT}{\fT}{\tauT}{\eT}})}{\vec{\xT}}{\xT}}} \\
& \phantom{\eq{}{}{}} \textrm{by congruence and case analysis on $\xT$} \\
& \eq{}{}{} \subst{\eT}{\fT}{\fixT{\nT}{\fT}{\tauT}{\eT}}
\qquad \textrm{definitionally by \rref{equiv-eta}}
\end{align*}

Since \rref{equiv-mu} and \rref{equiv-mu-guarded} are metatheoretically equivalent,
I choose to use \rref{equiv-mu} for its simplicity.

\FigSubtypingCIC{fig:subtyping-cic}
As opposed to \lang, for \CICE I use
pCIC's\index{Calculus of Inductive Constructions!Predicative \textasciitilde}
presentation of subtyping\index{subtyping} in \cref{fig:subtyping-cic},
which has a typed equivalence premise in \rref{subtype-conv}.
It also has an explicit rule for transitivity of subtyping since judgements such as
$\subtype{\mt}{\app{(\funT{P}{\TypeT{\tg{1}}}{P})}{\PropT}}{\TypeT{\tg{0}}}$ would fail to hold otherwise.
Like \rref{acum-pi}, \rref{subtype-pi} is invariant in the domain of function types.

The typing and environment well-formedness rules are in \cref{fig:typing-cic}.
Except for \rref{fix*}, the starred rules are the same as for \lang,
with metafunctions $\axioms{\mt}$ and $\rules{\mt}{\mt}$ operating similarly on universes $\UT$
as in \cref{fig:rules-axioms}.
An additional premise to \rref{fix*} ensures that the $\nT$th argument is indeed an inductive type.
% in addition to checking well-typedness of fixpoint bodies with possible recursive references.

As previously mentioned, fixpoints must also be guarded\index{guardedness}:
recursive calls can only occur on structurally smaller arguments of elements of inductives.
The guard condition is well studied \citep{guard, guard-relax, Coq} and so omitted here.
To justify uses of fixpoint expressions in the translation,
I will provide either a mechanization or present a brief argument of guardedness.

\FigTypingCIC{fig:typing-cic}

The new \rref{eq, refl, J} are for the propositional equality\index{propositional equality} type,
its constructor, and its eliminator.
Given some equality proof $\pT$ of $\eqT{\eT_1}{\tauT}{\eT_2}$
and a motive $\PT$ dependent on a proof of equality
whose left-hand side is fixed at $\eT_1$ and right-hand side is variable\punctstack{,}%
\footnote{Occasionally referred to as \emph{Paulin-Mohring}'s equality~\citep{CIC},
as opposed to \emph{Martin-L\"of}'s equality~\citep{MLTT}
where the left-hand side is variable as well.}
to prove $\app{\PT}{\eT_2}{\pT}$ it suffices to provide to $\JT*$ a proof that
$\app{\PT}{\eT_1}{\refl{\eT_1}}$ holds.
Other usual functions on proofs of equality can be derived from it,
such as coercion (when the motive is \mbox{$\funT{A}{\UT}{\funT{\any}{\any}{A}}$})
or substitution (when the motive ignores the second argument),
as well as its symmetry, transitivity, and congruence.
The proof of type preservation eliminates propositional equalities mostly through
reflection\index{equality reflection} rather than using $\JT*$,
but I retain $\JT*$ in \CICE for completeness\punctstack{.}%
\footnote{The combined presence of $\JT*$ and equality reflection also allows proving the
\emph{uniqueness of identity proofs} (UIP)\index{uniqueness of identity proofs},
or that all proofs of an equality $\eqT{a}{A}{b}$ are themselves equal to one another,
by reflecting $p$ in the term $\JT{(\funT{b}{A}{\funT{p}{\eqT{a}{A}{b}}{\eqT{\reflT{a}}{}{p}}})}{\reflT{\reflT{a}}.}{}$}

\rref{ind, constr, case} assign types to inductive types, their constructors,
and $\tg{case}$ expressions, under the premise that
the relevant inductive data definition exists and is well formed.
Here, the difference between the parameters and the indices of inductive types becomes apparent:
the motive\index{motive} of a $\tg{case}$ expression is abstracted over the indices by $\vec{\yT}$
in addition to the target by $\xT$, while the parameters $\vec{\pT}$ are fixed throughout.
Therefore, when dealing with the types of indices and constructor arguments,
the parameters are first substituted in place of $\vec{\wT}$.

A $\tg{case}$ expression is well typed if its target is,
if its motive is for any indices and target with those indices,
and if each branch is well typed for that branch's constructor arguments,
where its type is the motive with the appropriate indices and reconstructed target.
For notational simplicity, the rule assumes that the binding variable names
$\vec{\yT}$ and $\vec{\zT}$ are those found in the data definition,
but of course these can be renamed at the expense of additional renaming substitutions.

Additionally, the motive of a $\tg{case}$ expression is restricted by the metarelation $\elim{\mt}{\mt}{\mt}$,
which indicates when \emph{large elimination}\index{large elimination} is allowed.
$\elim{\any}{\TypeT{\iT}}{\any}$ and $\elim{\any}{\PropT}{\PropT}$ always hold,
so that inductives in $\TypeT{}$ can be eliminated to any universe
and inductives in $\PropT$ can be eliminated to $\PropT$,
while $\elim{\XT}{\PropT}{\TypeT{\iT}}$ holds if the inductive $\XT$ in $\PropT$ satisfies further conditions.
For the purposes of the translation, the only relevant conditions are that $\XT$ either have no constructors
or have a single constructor whose arguments are all in $\PropT$.
They can be loosened while still retaining consistency (see \eg \citet{SProp}).

The typing premises of
\rref{equiv-beta, equiv-zeta, equiv-rho, equiv-iota, equiv-mu}
corresponding to some of the reduction rules duplicate the premises found in many of the typing rules,
trivially ensuring that both sizes of these equivalences are well typed with the same type
(a property known as \emph{subject equivalence}\index{subject reduction}).

\section{Preliminary Definitions}

Before defining the translation from \lang terms to \CICE terms,
in this section I describe how the \CICE terms are constructed,
which comprises the aforementioned six inductive data definitions
and well-founded induction principle
as well as the various properties which the order on sizes satisfies.

\FigData{fig:data-defns}

The inductive definitions are listed in \cref{fig:data-defns}
along with some basic definitions I treat as global.
$\botT$ is the usual empty type.
$\SizeT$ is a generalization of the $\Ord*$ type introduced in \cref{sec:examples},
with the domain of the function passed to the limit size $\limT$ replaced by some arbitrary type.
Although limit sizes aren't strictly necessary for the translation,
since \lang only has successor sizes and size variables,
I include them so that various solutions to the problem of the infinite size
can be explored in \cref{sec:infinity}.
Furthermore, this allows for a simplification of the definition,
since the zero size $\baseT$ can be defined as a limit size rather than as another constructor.

The order on sizes $\mt \szleT \mt$ is defined by the three properties that must hold~\citep{ordinals}:
\begin{itemize}[noitemsep]
  \item $\monoT$: The successor operator $\sucT$ is monotone with respect to the order;
  \item $\coconeT$: The limit operator $\limT$ constructs an upper bound in that
    given some function $f$ returning a size,
    any size smaller than any size returned by $f$ is also smaller than the limit of $f$;
  \item $\limitT$: The limit operator on $f$ constructs a \emph{least} upper bound such that
    if a size is larger than \emph{all} sizes returned by $f$
    then it must also be larger than the limit of $f$.
\end{itemize}

Other properties of the order can be derived by induction from these constructors alone.
A corresponding strict order $\mt \szltT \mt$ is also defined,
and an accessibility predicate\index{accessibility predicate} $\AccT$ is specialized to sizes and the strict order.
Note that it lives in $\PropT$, as does the argument of its sole constructor $\accT$,
so accessibility predicates are intended to be interpreted as proof irrelevant\index{proof irrelevance},
and their large elimination\index{large elimination} is allowed.

\FigDefns{fig:defns}

Before moving on to naturals and well-founded trees,
\cref{fig:defns} lists the names and types of a number of provable definitions.
First is \emph{function extensionality}\index{function extensionality},
asserting that two functions $\annot{f, g}{\funtypeT{x}{A}{\app{B}{x}}}$ are propositionally equal if they are pointwise equal.
In \CICE, they are in fact equivalent (\ie definitionally equal):
given some proof $h$ of their pointwise equality,
under the assumption $\annot{x}{A}$,
the propositional equality $\eq{\app{f}{x}}{}{\app{g}{x}}$ by $\app{h}{x}$
can be reflected into the corresponding definitional equality,
which by \rref{equiv-eta} is then a definitional equality of $f$ and $g$.

The remaining definitions have been mechanized in either Agda and Coq in
\cref{app:mechanization:agda:prelim} and \cref{app:mechanization:coq:prelim}, respectively,
under the assumption of function extensionality as an axiom
(which cannot be proven in intensional CIC).
The mechanizations don't use any additional type-theoretic features beyond CIC,
and the proofs could theoretically be written in plain CIC,
but they would be far less comprehensible without the ergonomics provided by the proof assistants.
As an example, the Coq proof for $\accessible$ consists of a dozen lines of tactics,
while the full proof term generated from the tactics is 129 lines long.

The definitions themselves describe properties of the order on sizes
and of the accessibility predicate:
\begin{itemize}[noitemsep]
  \item $\baseleq$, $\reflleq$, $\transleq$, and $\sucleq$:
    The order is reflexive and transitive (\ie a preorder)
    such that $\baseT$ is smaller than or equal to all sizes
    and the successor of a size is greater or equal to itself.
  \item $\accIsProp$: Accessibility predicates are \emph{mere propositions}\index{mere proposition}:
    any two proofs of accessibility of a size are propositionally equal.
  \item $\accleq$: Any size smaller or equal to an accessible size is itself accessible.
  \item $\accessible$: All sizes are accessible; in other words, the order on sizes is well founded.
  \item $\wfind$ and $\wfacc$: The well-founded induction principle\index{well-founded induction} on sizes with respect to the order,
    proven by structural induction on the accessibility of sizes.
\end{itemize}

The only time equality reflection\index{equality reflection} is needed is to prove $\accIsProp$ (via $\funext$),
which in turn is the only other equality that is reflected for proving type preservation.
Since $\AccT$ is in already $\PropT$, \CICE could be replaced by an intensional CIC
with a universe of \emph{strict propositions}\index{strict proposition} $\SPropT$
of types whose elements are definitionally equal~\citep{SProp},
then placing $\AccT$ in $\SPropT$.
This is disallowed by \opcit because it breaks normalization;
however, it doesn't break consistency,
so it would remain suitable as the target language of a syntactic model.
In any case, I use \CICE because equality reflection is more established in the literature
and it allows me to use \rref{equiv-mu} in place of \rref{equiv-mu-guarded}.

Finally, the naturals and the well-founded trees in \CICE are parametrized by a $\SizeT$.
Their definitions respect the translation in the upcoming section,
so that the types of $\NatT$ and $\WT$ and their constructors are preserved.

\section{Translation}

The key type preservation\index{type preservation} theorem states that well-typed terms of \lang translate to
corresponding well-typed terms of CICE.
However, terms are not the only thing requiring translation:
well-typedness holds under some environment, so term environments need translations;
sizes and their environments translate to terms and term environments as well;
and derivations of size orders translate to terms which represent them.

\FigTransSize{fig:trans:size}
I begin with the translation of sizes and their environments in \cref{fig:trans:size},
which are straightforward recursive metafunctions over their syntax.
I use an asterisk superscript \new{$\mt^\ast$} on a variable $\alphaT$ to represent
a fresh variable uniquely associated with $\alphaT$.
Given some bound size variable $\alphaT$,
$\alphaT^\ast$ represents the proof that the translated size is strictly smaller
than its size bound.

\FigTransSubsize{fig:trans:subsize}
The translation of subsizing judgements, on the other hand,
is a recursive metafunction over the \emph{subsizing derivation}.
\cref{fig:trans:subsize} defines the translation to \CICE terms
by induction on the subsizing rules, which recursively translates subderivations
(omitting irrelevant size well-scopedness premises).

The translation of terms and term environments are similarly defined
as recursive metafunctions over the typing and well-formedness derivations,
denoted by
\mbox{$\typeto{\Phi; \Gamma}{e}{\tau}{\eT}$} and \mbox{$\wfto{\Phi}{\Gamma}{\GammaT}$}
respectively.
However, for concision, I use $\compile{e}$ to mean the translation of $e$
when well typed under the current implicit environments,
$\compile{e}_{\Phi}$ or $\compile{e}_{\Gamma}$ to mean the translation of $e$
with the current implicit environments extended with $\Phi$ or $\Gamma$,
and $\compile{\Gamma}$ to mean the translation of $\Gamma$
when well formed under the current implicit size environment.

\FigTransTerm{fig:trans:term}

The translation for base \lang without inductives is given in \cref{fig:trans:term}
in the more concise notation translated terms follow directly from subderivations
and in the usual notation otherwise.
Terms not involving sizes are translated in a straightforward recursive manner.
Unbounded size quantifications and abstractions translate to quantifications and abstractions over $\SizeT$,
while bounded ones have additional quantifications and abstractions over a proof of $\szltT$.
Size applications translate to an additional application to a proof of $\szltT$
when the size abstraction applied is bounded.

Finally, \cref{fig:trans:ind} gives the translation for naturals, well-founded trees,
$\kw{case}$ expressions, and fixpoint expressions from their typing derivations
to a \CICE term (again omitting irrelevant premises).
Aside from fixpoints, the translations are fairly straightforward,
with an additional proof term from subsizing for constructors
and dually an additional abstraction over such terms in the branches of $\tg{case}$ expressions.

\FigTransInd{fig:trans:ind}

Fixpoints in \lang are not translated as fixpoints in \CICE.
Doing so while preserving types would mean that \lang fixpoints
need to be subject to the same guard conditions as \CICE fixpoints,
which is clearly undesirable and not the case in the examples from \cref{sec:examples}.
Instead, every single \lang fixpoint, regardless of the inductive on which they recur,
is translated to well-founded induction\index{well-founded induction},
which is defined via a \CICE fixpoint on accessibility predicates\index{accessibility predicate}.
Intuitively, the return type of a fixpoint corresponds to the motive of well-founded induction,
while recursion on a strictly smaller size corresponds to the induction hypothesis,
where the motive holds for all strictly smaller sizes.

The main challenge with this translation is showing that the translations of a fixpoint
and of its $\mu$-reduction are equivalent in \CICE,
because this requires showing that the computational behaviour of well-founded induction
is equivalent to the computational behaviour of the fixpoint.
Once that has been established,
showing type preservation of the translation is more or less going through the motions of the proof,
since the remaining \lang terms translate almost directly to their syntactically corresponding terms.


\subsection{Roots of unity}


\subsection{Vector space geometry}\label{subsec:vector_space_geometry}

\begin{remark}\label{rem:real_field_extensions}
  When speaking about vector spaces, we usually restrict ourselves to vector spaces over \( \BbbR \) or, at most, \( \BbbC \). This restriction may seem arbitrary, however important concepts like \hyperref[def:geometric_ray]{rays} or \hyperref[def:convex_set]{convexity} requires the field to be an extension of \( \BbbR \), and it just so happens that, by \fullref{thm:fundamental_theorem_of_algebra} and \fullref{thm:no_finite_extensions_of_closed_fields}, the only nontrivial finite \hyperref[def:field_extension]{extension field} of \( \BbbR \) is \( \BbbC \). It is technically possible to work with infinite extension fields, however in practice vector spaces over \( \BbbC \) are esoteric enough. A benefit of considering only \( \BbbC \) is given in \fullref{rem:linear_functionals_over_c}.
\end{remark}

\begin{definition}\label{def:geometric_shape}
  A \term{geometric shape} is an informal notion that refers to certain special subsets of a vector space, usually defined in a coordinate-independent manner. Shapes in two-dimensional spaces are called \term{figures} and shapes in three dimensions are called \term{surfaces}.

  When two geometric shapes shapes intersect, we say that they are \term{incident}.
\end{definition}

\begin{definition}\label{def:point}
  A \term{point} is a simple geometric \hyperref[def:geometric_shape]{shape} comprising a singleton subset of any set (usually a vector space or a topological space). We use the convention \fullref{rem:singleton_sets} and, unless the distinction is important, we do not distinguish between singleton sets and their only element - e.g. in \fullref{def:simplex/point}.

  Points are also called vectors, which is justified by \fullref{def:euclidean_plane_coordinate_system}.
\end{definition}

\begin{definition}\label{def:euclidean_transformation}
  The following bijections from \( \BbbR^n \) to \( \BbbR^n \) are collectively called \term{Euclidean transformations} or \term{rigid motions} in \( \BbbR^n \):

  \begin{thmenum}
    \thmitem{def:euclidean_transformation/translation} For any vector \( v \in \BbbR^n \), the function
    \begin{equation*}
      \op{t}_v(x) \coloneqq x + v
    \end{equation*}
    is called a \term{translation} along the \term{direction} \( v \).

    This easily generalizes to an arbitrary \hyperref[def:magma]{magma} \( (M, \cdot) \) by setting
    \begin{equation*}
      \op{t}_v(x) \coloneqq v \cdot x
    \end{equation*}
    for some \( v \in M \).

    \thmitem{def:euclidean_transformation/dilation} For any scalar \( \lambda \in \BbbR^n \), the function
    \begin{equation*}
      \op{d}_\lambda(x) \coloneqq \lambda x
    \end{equation*}
    is called a \term{dilation} or \term{scaling} by \( \lambda \).

    This easily generalizes to an arbitrary (left) \hyperref[def:magma]{module} \( (M, +, \cdot) \).

    \thmitem{def:euclidean_transformation/homothety} A composition of a \hyperref[def:euclidean_transformation/dilation]{dilation} with a \hyperref[def:euclidean_transformation/translation]{translation} is called a \term{homothety}.

    \thmitem{def:euclidean_transformation/rotation} For any point \( p \in \BbbR^n \) and any special (i.e. \hyperref[def:matrix_determinant]{determinant} one) \hyperref[def:orthogonal_matrix]{orthogonal matrix} \( A \in \op{O}_n(\BbbR) \), the function
    \begin{equation*}
      \op{rot}_{A,p}(x) \coloneqq p + A (x - p)
    \end{equation*}
    is called a \term{rotation} by \( A \) around \( p \).

    \thmitem{def:euclidean_transformation/reflection} For any point \( p \in \BbbR^n \), the function
    \begin{equation*}
      \op{ref}_p(x) \coloneqq 2p - x
    \end{equation*}
    is called a \term{point reflection} or \term{inversion} with respect to the point \( p \).
  \end{thmenum}
\end{definition}

\begin{definition}\label{def:zero_locus}
  Let \( S \) be an arbitrary set and let \( M \) be a \hyperref[def:unital_magma]{unital} \hyperref[def:magma]{magma} with identity \( e \).

  The \term{zero locus} or \term{set of zeros} of a function \( f: S \to M \) is the preimage
  \begin{equation*}
    f^{-1}(e) = \{ x \in X \colon f(x) = e \}.
  \end{equation*}

  In practice, \( M \) is usually a \hyperref[def:semiring/ring]{ring} or a \hyperref[def:left_module]{module}, in which case the zero locus is defined for the additive group, i.e.
  \begin{equation*}
    f^{-1}(0_M) = \{ x \in X \colon f(x) = 0_M \}.
  \end{equation*}

  See also \fullref{def:pointed_set_kernel}, \fullref{def:semiring_kernel} and \fullref{def:left_module_kernel}.
\end{definition}

\begin{definition}\label{def:hypersurface}
  A \term{hypersurfaces} can have different meanings depending on the context. We are interested in

  \begin{thmenum}
    \thmitem{def:hypersurface/parametric} A parametric hypersurface (\fullref{def:parametric_hypersurface}) is a purely topological definition.
    \thmitem{def:hypersurface/algebraic} An affine variety (\fullref{def:affine_variety}) is a purely algebraic definition.
    \thmitem{def:hypersurface/geometric} A manifold (\fullref{def:topological_manifold}) can be regarded as a geometric definition.
  \end{thmenum}

  Note that all of the enumerated hypersurfaces have a concept of dimension. Hypersurfaces of dimension \( 2 \) are simply called \term{surfaces} (see \fullref{def:affine_variety/algebraic_surface}) and hypersurfaces of dimension \( 1 \) are called \term{curves} (see also \fullref{def:affine_variety/algebraic_curve} and \fullref{def:affine_variety/algebraic_curve}).
\end{definition}

\begin{definition}\label{def:geometric_line}
  A particularly important \hyperref[def:hypersurface]{curve} is a \term{line} in a vector space \( X \) over any field \( \BbbK \), which can be defined equivalently as

  \begin{thmenum}
    \thmitem{def:geometric_line/subspace} A subspace of \( X \) of \hyperref[def:vector_space_dimension]{dimension} one. Note that this is not consistent with the other definitions because this defines only lines through the origin \( 0_X \). Hence, if \( L \subseteq X \) is a line (a subspace of dimension one) and if \( a \in X \) is any point, we define a line with origin \( a \) to be the translation \( a + L \).

    \thmitem{def:geometric_line/algebraic} An \hyperref[def:affine_variety/algebraic_curve]{algebraic curve} in \( X \) given by a polynomial of degree one.

    \thmitem{def:geometric_line/parametric} If the field \( \BbbK \) is ordered (usually when \( \BbbK = \BbbR \)), we can define a line with \term{directional vector} \( x \) and \term{origin} \( a \) as the parametric curve
    \begin{balign*}
       & l: \BbbK \to X   \\
       & l(t) = tx + a.
    \end{balign*}
  \end{thmenum}
\end{definition}

\begin{definition}\label{def:geometric_ray}
  If \( X \) is a vector space over \( \BbbK \in \{ \BbbR, \BbbC \} \), we define \term{closed rays} with a vertex \( a \) as the parametric curves
  \begin{balign*}
     & l^+: [0, \infty) \to X \\
     & l^+(t) = tx + a
  \end{balign*}
  and
  \begin{balign*}
     & l^-: (-\infty, 0] \to X \\
     & l^-(t) = tx + a
  \end{balign*}

  If the inequalities are strict, we instead obtain \term{open rays}.

  Unless explicitly noted otherwise, we assume that the vertex of the ray is \( 0 \) because every ray is a translation of a ray centered at \( 0 \).
\end{definition}

\begin{definition}\label{def:geometric_cone}
  An open (resp. closed) \term{cone} in a vector space over \( \BbbK \in \{ \BbbR, \BbbC \} \) is a union of open (resp. closed) \hyperref[def:geometric_ray]{rays} with a common vertex, called the \term{vertex} of the cone.
\end{definition}

\begin{definition}\label{def:hyperplane}
  Dually to \hyperref[def:geometric_line]{lines}, another particularly important \hyperref[def:hypersurface]{hypersurface} is a \term{hyperplane} in a vector space \( X \) over any field.

  \begin{thmenum}
    \thmitem{def:hyperplane/subspace} A \term{linear hyperplane} is simply a subspace of \( X \) of \hyperref[def:vector_space_dimension]{codimension} one. As in \fullref{def:geometric_line/subspace}, we define a \term{affine hyperplane} to be a \hyperref[def:euclidean_transformation/translation]{translation} of a linear hyperplane.

    \thmitem{def:hyperplane/kernel} Linear hyperplanes (as defined in \fullref{def:hyperplane/subspace}) are simply zero \hyperref[def:zero_locus]{loci} (\hyperref[def:semiring_kernel]{kernels}) of linear \hyperref[def:linear_operator]{functionals}. and affine hyperplanes are zero loci of \hyperref[def:affine_operator]{affine functionals}.
  \end{thmenum}
\end{definition}

\begin{example}\label{ex:hyperplanes}
  Affine \hyperref[def:hyperplane]{hyperplanes} in \( \BbbR^2 \) are \hyperref[def:geometric_line]{lines} and affine hyperplanes in \( \BbbR^3 \) are planes.

  Linear \hyperref[def:hyperplane]{hyperplanes} in \( \BbbR^2 \) are the lines passing through the origin \( (0, 0) \) and linear hyperplanes in \( \BbbR^3 \) are the planes incident to \( (0, 0, 0) \).
\end{example}

\begin{definition}\label{def:half_space}
  Vector spaces over \( \BbbR \) have the concept of \term{half-spaces}. Given a \hyperref[def:hyperplane]{hyperplane} \( H \) of the real vector space \( X \), defined by the affine functional \( l(x) = \inprod {x^*} x + a \), its closed half-spaces are defined as
  \begin{equation*}
    H^+ \coloneqq \{ l(x) \geq 0 \} = \{ \inprod {x^*} x \geq -a \}
  \end{equation*}
  and
  \begin{equation*}
    H^- \coloneqq \{ l(x) \leq 0 \} = \{ \inprod {x^*} x \leq -a \}.
  \end{equation*}

  If the inequalities are strict, we instead obtain \term{open half-spaces}.
\end{definition}

\begin{definition}\label{def:polyhedron}
  A \term{polyhedron} in a real vector space is an intersection of \hyperref[def:half_space]{half-spaces}.
\end{definition}

\begin{definition}\label{def:hyperplane_separation}
  Although \hyperref[def:hyperplane]{hyperplanes} are defined for vector spaces over an arbitrary field \( \BbbK \), we define \term{hyperplane separation} only for \( \BbbK \in \{ \BbbR, \BbbC \} \) (see \fullref{rem:real_field_extensions}).

  We say that the sets \( A, B \subseteq X \) are \term{separated} by the linear functional \( l \in X^* \) if there exists a real number \( c \in \BbbR \) such that
  \begin{equation}\label{def:hyperplane_separation/normal}
    \real l(x) < c \leq \real l(y) \quad\forall x \in A, y \in B.
  \end{equation}

  See \fullref{rem:linear_functionals_over_c} for a justification of only considering the real part of \( l \).

  The asymmetry in the inequalities \fullref{def:hyperplane_separation/normal} can be inverted by considering \( -l(x) \) and \( -c \).

  We say that \( A \) and \( B \) are \term{strongly separated} by \( l \) if both inequalities in \fullref{def:hyperplane_separation/normal} are strict:
  \begin{equation}\label{def:hyperplane_separation/strong}
    \real l(x) < c < \real l(y) \quad\forall x \in A, y \in B.
  \end{equation}

  We can regard \( l \) as a hyperplane as in \fullref{def:hyperplane/kernel}, which justifies the terminology \enquote{hyperplane separation}. It is more correct, however, especially if \( \BbbK = \BbbR \), to say that they are separated by the affine hyperplane \( l(x) + c \).

  If \( \BbbK = \BbbR \) \fullref{def:hyperplane_separation/normal} is equivalent to requiring that \( A \) is contained in an open \hyperref[def:half_space]{half-space} relative to \( l(x) + c \) and that \( B \) is contained in the complementing closed half-space (or vice-versa). \Fullref{def:hyperplane_separation/strong} then states that both \( A \) and \( B \) are contained in opposite open half-spaces.
\end{definition}

\begin{definition}\label{def:convex_set}
  \hfill
  \begin{thmenum}
    \thmitem{def:convex_set/line_segment} Given two points \( x, y \in X \) in a Banach space \( X \), we define the \term{line segment} between \( x \) and \( y \) as the parametric curve \( t \mapsto tx + (1-t)y, t \in [0, 1] \). The image
    \begin{equation*}
      [x, y] \coloneqq \{ tx + (1-t)y \colon t \in [0, 1] \}
    \end{equation*}
    of this parametric curve is called the \term{convex hull} of \( x \) and \( y \). We usually use the term \enquote{line segment} to refer to the convex hull itself.

    The length \( \len([x, y]) \) of a line segment is defined as \( \norm{x - y} \).

    \thmitem{def:convex_set/hull} We define the convex hull \( \conv A \) of a set \( A \subseteq X \) as the union of all line segments with endpoints in \( A \).

    \thmitem{def:convex_set/set} We call a set \term{convex} if it coincides with its convex hull, that is, if it contains the line segment between any two of its points.
  \end{thmenum}
\end{definition}

\begin{proposition}\label{thm:def:convex_set/properties}
  \hyperref[def:convex_set]{Convex sets} have the following basic properties:

  \begin{thmenum}
    \thmitem{thm:def:convex_set/properties/closed_under_combinations} A convex set is closed under convex \hyperref[def:linear_combination/convex]{combinations}.
    \thmitem{thm:def:convex_set/properties/cone_closed_under_combinations} A closed \hyperref[def:convex_set]{convex} \hyperref[def:geometric_cone]{cone} is closed under conic \hyperref[def:linear_combination/conic]{combinations}.
    \thmitem{thm:def:convex_set/properties/closed_under_intersections} Any intersection of convex sets is convex.
  \end{thmenum}
\end{proposition}
\begin{proof}
  \SubProofOf{thm:def:convex_set/properties/closed_under_combinations} Fix a convex set \( C \). Let \( \sum_{k=1}^n t_k x_k \) be a convex combination of elements of \( C \).

  We will use induction on \( n \). If \( n = 1 \), this is obvious. If \( n = 2 \), this is given by definition. Assume that it is true for \( n - 1 \). Denote \( s \coloneqq \sum_{k=1}^{n-1} t_k \). If \( s = 0 \), take another convex combination in order to handle all the possible cases of the induction. Suppose \( s \neq 0 \). Then
  \begin{equation*}
    \sum_{k=1}^n t_k x_k
    =
    s \sum_{k=1}^n \frac {t_k} s x_k
    =
    s \underbrace{\sum_{k=1}^{n-1} \frac {t_k} s x_k}_{\eqqcolon y} + t_n x_n.
  \end{equation*}

  By the inductive hypothesis, \( y \in C \). Note that \( s \in [0, 1] \) and that \( s + t_n = 1 \) by definitions of \( s \). Then \( s y + t_n x_n \) is a binary convex combination that we know is contained in \( C \) by definition.

  \SubProofOf{thm:def:convex_set/properties/cone_closed_under_combinations} Fix a cone \( C \). Let \( \sum_{k=1}^n t_k x_k \) be a conic combination of elements of \( C \). Each vector \( x_k \) lies on a closed ray, say \( r_k \), thus \( t_k x_k \) also lies on \( r_k \).

  Therefore, we only need to show that the sum of two elements \( x_1, x_2 \in C \) is again in \( C \). This is true because \( x_1 + x_2 \) is a convex combination of \( 2x_1 \in r_1 \) and \( 2x_2 \in r_2 \).

  \SubProofOf{thm:def:convex_set/properties/closed_under_intersections} Let \( X = \cap_{\alpha \in \mscrK} X_\alpha \) be an intersection of convex sets. Take \( x, y \in X \) and \( t \in [0, 1] \). Then \( tx + (1-t)y \in X_\alpha \) for all \( \alpha \in \mscrK \), hence \( tx + (1-t)y \in X \). Therefore, \( X \) is convex.
\end{proof}

\begin{definition}\label{def:simplex}
  A \( k \)-\term{simplex} is the convex \hyperref[def:convex_set/hull]{hull} of \( k + 1 \) affinely \hyperref[affine_independence]{independent} vectors called the \term{vertices} of the simplex. The convex hull of any subset of the vertices is called a \term{face} of the simplex.

  \begin{thmenum}
    \thmitem{def:simplex/point} A \( 0 \)-simplex is a \hyperref[def:point]{point}.
    \thmitem{def:simplex/line_segment} A \( 1 \)-simplex is a line segment as defined in \fullref{def:convex_set/line_segment}.
    \thmitem{def:simplex/triangle} A \( 2 \)-simplex is a triangle as defined in \fullref{def:triangle}.
    \thmitem{def:simplex/tetrahedron} A \( 3 \)-simplex is called a \term{tetrahedron}.
  \end{thmenum}
\end{definition}

\begin{definition}\label{def:k_cell}
  A \( k \)-cell is a \hyperref[def:cartesian_product]{Cartesian product} of \( k \) nonempty \hyperref[def:partially_ordered_set_interval/closed]{closed intervals} of real numbers.

  \begin{thmenum}
    \thmitem{def:k_cell/point} A \( 0 \)-cell is a \hyperref[def:point]{point}.
    \thmitem{def:k_cell/interval} A \( 1 \)-cell is a closed interval.
    \thmitem{def:k_cell/rectangle} A \( 2 \)-cell is called a \term{rectangle}. If a rectangle \( R \) is a product of two copies of the same interval, i.e. if \( R = [a, b]^2 \), we say that \( R \) is a \term{square} with side \( b - a \).
    \thmitem{def:k_cell/parallelepiped} A \( 3 \)-cell is called a \term{parallelepiped}. If \( R = [a, b]^3 \), we say that \( R \) is a \term{cube} with side \( b - a \).
  \end{thmenum}
\end{definition}

\begin{definition}\label{def:neighborhood_set_types}
  The following topology-independent definitions are often used for neighborhoods in a topological vector space \( X \):

  \begin{thmenum}
    \thmitem{def:neighborhood_set_types/absorbing} \( A \) is \term{absorbing} if \( \bigcup_{k=0}^\infty kA = X \).
    \thmitem{def:neighborhood_set_types/symmetric} \( A \) is \term{symmetric} if \( -A = A \).
    \thmitem{def:neighborhood_set_types/balanced} \( A \) is \term{balanced} if \( tA \subseteq A \) for any \( t \in [0, 1] \).
  \end{thmenum}
\end{definition}

\begin{definition}\label{def:collinear_complanar}
  The geometric version of \hyperref[def:left_module_linear_dependence]{linear independence} has two special names: we say that the set \( A \subseteq X \) of any vector space \( X \) is \term{collinear} (on the same line) if \( \dim(\linspan(A)) \leq 1 \) and \term{complanar} (on the same plane) if \( \dim(\linspan(A)) \leq 2 \).
\end{definition}

\begin{proposition}\label{thm:moment_curve}
  Consider \hyperref[def:parametric_curve]{curve}
  \begin{equation*}
    \begin{aligned}
      &\gamma: \BbbR \to \BbbR^n \\
      &\gamma(t) \coloneqq (t, t^2, \ldots, t^n).
    \end{aligned}
  \end{equation*}

  For any \( t_1 < \ldots < t_n \), the points \( \gamma(t_1), \ldots, \gamma(t_n) \) are linearly independent.

  This curve is called the \term{moment curve} of dimension \( n \).
\end{proposition}
\begin{proof}
  Follows from \fullref{ex:vandermonde_matrix}.
\end{proof}


\newpage
\section{Groebner package}
\begin{Introduction}{Groebner bases}
The GROEBNER package calculates \nameindex{Groebner bases} using the
\nameindex{Buchberger algorithm} and provides related algorithms
for arithmetic with ideal bases, such as ideal quotients,
Hilbert polynomials (\nameindex{Hollmann algorithm}),
basis conversion (
\nameindex{Faugere-Gianni-Lazard-Mora algorithm}), independent
variable set (\nameindex{Kredel-Weispfenning algorithm}).

Some routines of the Groebner package are used by \nameref{solve} - in
that context the package is loaded automatically. However, if you
want to use the package by explicit calls you must load it by
\begin{verbatim}
    load_package groebner;
\end{verbatim}

For the common parameter setting of most operators in this package
see \nameref{ideal parameters}.
\end{Introduction}

\begin{Concept}{Ideal Parameters}
\index{polynomial}
Most operators of the \name{Groebner} package compute expressions in a
polynomial ring which given as \meta{R}[\meta{var},\meta{var},...] where
\meta{R} is the current REDUCE coefficient domain.  All algebraically
exact domains of REDUCE are supported.  The package can operate over rings
and fields.  The operation mode is distinguished automatically.  In
general the ring mode is a bit faster than the field mode.  The factoring
variant can be applied only over domains which allow you factoring of
multivariate polynomials.

The variable sequence \meta{var} is either declared explicitly as argument
in form of a \nameref{list} in \nameref{torder}, or it is extracted
automatically from the expressions.  In the second case the current REDUCE
system order is used (see \nameref{korder}) for arranging the variables.
If some kernels should play the role of formal parameters (the ground
domain \meta{R} then is the polynomial ring over these), the variable
sequences must be given explicitly.

All REDUCE \nameref{kernel}s can be used as variables.  But please note,
that all variables are considered as independent.  E.g. when using
\name{sin(a)} and \name{cos(a)} as variables, the basic relation
\name{sin(a)^2+cos(a)^2-1=0} must be explicitly added to an equation set
because the Groebner operators don't include such knowledge automatically.

The terms (monomials) in polynomials are arranged according to the current
\nameref{term order}.  Note that the algebraic properties of the computed
results only are valid as long as neither the ordering nor the variable
sequence changes.

The input expressions \meta{exp} can be polynomials \meta{p}, rational
functions \meta{n}/\meta{d} or equations \meta{lh}=\meta{rh} built from
polynomials or rational functions.  Apart from the \name{tracing}
algorithms \nameref{groebnert} and \nameref{preducet}, where the equations
have a specific meaning, equations are converted to simple expressions by
taking the difference of the left-hand and right-hand sides
\meta{lh}-\meta{rh}=>\meta{p}.  Rational functions are converted to
polynomials by converting the expression to a common denominator form
first, and then using the numerator only \meta{n}=>\meta{p}.  So eventual
zeros of the denominators are ignored.

A basis on input or output of an algorithm is coded as \nameref{list} of
expressions \{\meta{exp},\meta{exp},...\} . \end{Concept}

%-----------------------------------------------------------------
\subsection{Term order}
%-----------------------------------------------------------------
\begin{Introduction}{Term order}
\index{distributive polynomials}
For all \name{Groebner} operations the polynomials are
represented in distributive form: a sum of terms (monomials).
The terms are ordered corresponding to the actual \name{term order}
which is set by the \nameref{torder} operator, and to the
actual variable sequence which is either given as explicit
parameter or by the system \nameref{kernel} order.
\end{Introduction}

\begin{Operator}{torder}
The operator \name{torder} sets the actual variable sequence and term order.

1. simple term order:
\begin{Syntax}
  \name{torder}\(\meta{vl}, \meta{m}\)
\end{Syntax}

where  \meta{vl} is a \nameref{list} of variables (\nameref{kernel}s) and
\meta{m} is the name of a simple \nameref{term order} mode
\ref{lex term order}, \ref{gradlex term order},
\ref{revgradlex term order} or another implemented parameterless mode.

2. stepped term order:
\begin{Syntax}

  \name{torder} \(\meta{vl},\meta{m},\meta{n}\)

\end{Syntax}

where \meta{m} is the name of a two step term order, one of
\nameref{gradlexgradlex term order}, \nameref{gradlexrevgradlex term order},
\nameref{lexgradlex term order} or \nameref{lexrevgradlex term order}, and
\meta{n} is a positive integer.

3. weighted term order
\begin{Syntax}
 \name{torder} \(\meta{vl}, \name{weighted}, \meta{n},\meta{n},...\);
\end{Syntax}

where the \meta{n} are positive integers, see \nameref{weighted term order}.

4. matrix term order
\begin{Syntax}
 \name{torder} \(\meta{vl}, \name{matrix}, \meta{m}\);
\end{Syntax}

where \meta{m} is a matrix with integer elements, see
\nameref{torder_compile}.

5. compiled term order
\begin{Syntax}
 \name{torder} \(\meta{vl}, \name{co}\);
\end{Syntax}

where \meta{co} is the name of a routine generated by
\nameref{torder_compile}.

\name{torder} sets the variable sequence and the term order mode. If the
an empty list is used as variable sequence, the automatic variable extraction
is activated. The defaults are the empty variable list an the
\nameref{lex term order}.
The previous setting is returned as a list.

Alternatively to the above syntax the arguments of \name{torder} may be
collected in a \nameref{list} and passed as one argument to
\name{torder}.

\end{Operator}
%------------------------------------------------------------
\begin{Operator}{torder_compile}
\index{term order}
A matrix can be converted into
a compilable LISP program for faster execution by using
\begin{Syntax}
    \name{torder\_compile}\(\meta{name},\meta{mat}\)
\end{Syntax}
where \meta{name} is an identifier for the new term order and \meta{mat}
is an integer matrix to be used as \nameref{matrix term order}. Afterwards
the term order can be activated by using \meta{name} in a \nameref{torder}
expression. The resulting program is compiled if the switch \nameref{comp}
is on, or if the  \name{torder\_compile} expression is part of a compiled
module.
\end{Operator}
%------------------------------------------------------------
\begin{Concept}{lex term order}
\index{term order}\index{variable elimination}
The terms are ordered lexicographically: two terms t1 t2
are compared for their degrees
along the fixed variable sequence: t1 is higher than t2
if the first different degree is higher in t1.
This order has the \name{elimination property}
for \name{groebner basis} calculations.
If the ideal has a univariate polynomial in the last
variable the groebner basis will contain
such polynomial. \name{Lex} is best
suited for solving of polynomial equation systems.

\end{Concept}

%------------------------------------------------------------
\begin{Concept}{gradlex term order}
\index{term order}
The terms are ordered first with their total
degree, and if the total degree is identical
the comparison is \nameref{lex term order}.
With \name{groebner} basis calculations this term order
produces polynomials of lowest degree.
\end{Concept}

%------------------------------------------------------------
\begin{Concept}{revgradlex term order}
\index{term order}
The terms are ordered first with their total
degree (degree sum), and if the total degree is identical
the comparison is the inverse of \nameref{lex term order}.
With \nameref{groebner} and \nameref{groebnerf}
calculations this term order
is similar to \nameref{gradlex term order}; it is known
as most efficient ordering with respect to computing time.
\end{Concept}

%------------------------------------------------------------
\begin{Concept}{gradlexgradlex term order}
\index{term order}
The terms are separated into two groups where the
second parameter of the \nameref{torder} call determines
the length of the first group. For a comparison first
the total degrees of both variable groups are compared.
If both are equal
\nameref{gradlex term order} comparison is applied to the first
group, and if that does not decide \nameref{gradlex term order}
is applied for the second group. This order has the elimination
property for the variable groups. It can be used e.g. for
separating variables from parameters.
\end{Concept}
%------------------------------------------------------------
\begin{Concept}{gradlexrevgradlex term order}
\index{term order}
Similar to \nameref{gradlexgradlex term order}, but using
\nameref{revgradlex term order} for the second group.
\end{Concept}
%------------------------------------------------------------
\begin{Concept}{lexgradlex term order}
\index{term order}
Similar to \nameref{gradlexgradlex term order}, but using
\nameref{lex term order} for the first group.
\end{Concept}
%------------------------------------------------------------
\begin{Concept}{lexrevgradlex term order}
\index{term order}
Similar to \nameref{gradlexgradlex term order}, but using
\nameref{lex term order} for the first group
\nameref{revgradlex term order} for the second group.
\end{Concept}
%------------------------------------------------------------
\begin{Concept}{weighted term order}
\index{term order}
establishes a graduated ordering
similar to \nameref{gradlex term order}, where the exponents first are
multiplied by the given weights. If there are less weight values than
variables, the weight list is extended by ones. If the weighted degree
comparison is not decidable, the
\nameref{lex term order} is used.
\end{Concept}
%------------------------------------------------------------
\begin{Concept}{graded term order}
\index{term order}
establishes a cascaded term ordering:  first a graduated ordering
similar to \nameref{gradlex term order} is used, where the exponents first are
multiplied by the given weights. If there are less weight values than
variables, the weight list is extended by ones. If the weighted degree
comparison is not decidable, the term ordering described in the following
parameters of the \nameref{torder} command is used.
\end{Concept}
%------------------------------------------------------------
\begin{Concept}{matrix term order}
\index{term order}
Any arbitrary term order mode can be installed by a matrix with
integer elements where the row length corresponds to the variable
number. The matrix must have at least as many rows as columns.
It must have full rank, and the top nonzero element of each column
must be positive.

The matrix \name{term order mode}
defines a term order where the exponent vectors of the monomials are
first multiplied by the matrix and the resulting vectors are compared
lexicographically.

If the switch \nameref{comp} is on, the matrix is converted into
a compiled LISP program for faster execution. A matrix can also be
compiled explicitly, see \nameref{torder_compile}.
\end{Concept}
%---------------------------------------------------------------
%------------------------------------------------------------
\subsection{Basic Groebner operators}
%-------------------------------------------------------------
\begin{Operator}{gvars}
\begin{Syntax}

  \name{gvars}\(\{\meta{exp},\meta{exp},... \}\)

\end{Syntax}
 where \meta{exp} are expressions or \nameref{equation}s.

\name{gvars} extracts from the expressions the \nameref{kernel}\name{s}
which can
play the role of variables for a \nameref{groebner} or \nameref{groebnerf}
calculation.
\end{Operator}

%---------------------------------------------------------------

\begin{Operator}{groebner}
\index{Buchberger algorithm}
\begin{Syntax}

  \name{groebner}\(\{\name{exp}, ...\}\)

\end{Syntax}
where \{\name{exp}, ... \} is a list of
expressions or equations.

The operator \name{groebner} implements the Buchberger algorithm
for computing Groebner bases for a given set of
expressions with respect to the given set of variables in the order
given.  As a side effect, the sequence of variables is stored as a REDUCE list
in the shared variable \nameref{gvarslast} - this is important in cases
where the algorithm rearranges the variable sequence because \nameref{groebopt}
is \name{on}.

\begin{Examples}
   groebner({x**2+y**2-1,x-y})  &  \{X - Y,2*Y**2 -1\}
\end{Examples}
\begin{Related}
\item[ \nameref{groebnerf} operator]
\item[ \nameref{gvarslast} variable]
\item[ \nameref{groebopt} switch]
\item[ \nameref{groebprereduce} switch]
\item[ \nameref{groebfullreduction} switch]
\item[ \nameref{gltbasis} switch]
\item[ \nameref{gltb} variable]
\item[ \nameref{glterms} variable]
\item[ \nameref{groebstat} switch]
\item[ \nameref{trgroeb} switch]
\item[ \nameref{trgroebs} switch]
\item[ \nameref{groebprot} switch]
\item[ \nameref{groebprotfile} variable]
\item[ \nameref{groebnert} operator]
\end{Related}
\end{Operator}
%-------------------------------------------------------

\begin{Operator}{groebner\_walk}
The operator \name{groebner\_walk} computes a \nameref{lex} basis
from a given \nameref{graded} (or \nameref{weighted}) one.
\begin{Syntax}
   \name{groebner\_walk}\(\meta{g}\)
\end{Syntax}

where \meta{g} is a \nameref{graded} basis (or \nameref{weighted} basis
with a weight vector with one repeated element) of the polynomial ideal.
\name{Groebner\_walk} computes a sequence of monomial bases, each
time lifting the full system to a complete basis.  \name{Groebner\_walk}
should be called only in cases, where a normal \nameref{kex} computation
would take too much computer time.

The operator \nameref{torder} has to be called before in order to
define the variable sequence and the term order mode of \meta{g}.

The variable \nameref{gvarslast} is not set.

Do not call \name{groebner\_walk} with \name{on} \nameref{groebopt}.

\name{Groebner\_walk} includes some overhead (such as e. g.
computation with division). On the other hand, sometimes
\name{groebner\_walk} is faster than a direct \nameref{lex} computation.
\end{Operator}

%-------------------------------------------------------

\begin{Switch}{groebopt}
If \name{groebopt} is set ON, the sequence of variables is optimized
with respect to execution speed of \name{groebner} calculations;
note that the final list of variables is available in \nameref{gvarslast}.
By default \name{groebopt} is off, conserving the original variable
sequence.

An explicitly declared dependency using the \nameref{depend}
declaration  supersedes the variable optimization.
\begin{Examples}

   depend a, x, y;

\end{Examples}
guarantees that a will be placed in front of x and y.
\end{Switch}

%-------------------------------------------------------

\begin{Variable}{gvarslast}
After a \nameref{groebner} or \nameref{groebnerf} calculation
the actual variable sequence is stored in the variable
\name{gvarslast}. If \nameref{groebopt} is \name{on}
\name{gvarslast} shows the variable sequence after reordering.
\end{Variable}

%--------------------------------------------------------------

\begin{Switch}{groebprereduce}
If \name{groebprereduce} set ON, \nameref{groebner}
and \nameref{groebnerf} try to simplify the
input expressions: if the head term of an input expression is a
multiple of the head term of another expression, it can be reduced;
these reductions are done cyclicly as long as possible in order to
shorten the main part of the algorithm.

By default \name{groebprereduce} is off.
\end{Switch}

%---------------------------------------------------------------

\begin{Switch}{groebfullreduction}
If \name{groebfullreduction} set off, the polynomial reduction steps during
\nameref{groebner} and \nameref{groebnerf} are limited to the pure head
term reduction; subsequent terms are reduced otherwise.

By default \name{groebfullreduction} is on.
\end{Switch}

%----------------------------------------------------------------

\begin{Switch}{gltbasis}
If \name{gltbasis} set on, the leading terms of the result basis
of a \nameref{groebner} or \nameref{groebnerf} calculation are
extracted. They are collected as a basis of monomials, which is
available as value of the global variable \nameref{gltb}.
\end{Switch}
%------------------------------------------------------------------
\begin{Variable}{gltb}
See \nameref{gltbasis}
\end{Variable}
%------------------------------------------------------------------

\begin{Variable}{glterms}
If the expressions in a \nameref{groebner} or \nameref{groebnerf}
call contain parameters (symbols
which are not member of the variable list), the share variable
\name{glterms} is set to a list of expression which during the
calculation were assumed to be nonzero. The calculated bases
are valid only under the assumption that all these expressions do
not vanish.
\end{Variable}

%-----------------------------------------------------------
\begin{Switch}{groebstat}
if \name{groebstat} is on, a summary of the
\nameref{groebner} or \nameref{groebnerf} computation is printed
at the end
including the computing time, the number of intermediate
H polynomials and the counters for the criteria hits.
\end{Switch}

%-----------------------------------------------------------
\begin{Switch}{trgroeb}
if \name{trgroeb} is on, intermediate H polynomials are
printed during a \nameref{groebner}
or \nameref{groebnerf} calculation.
\end{Switch}

%-----------------------------------------------------------
\begin{Switch}{trgroebs}
if \name{trgroebs} is on, intermediate H and S polynomials are
printed during a \nameref{groebner} or \nameref{groebnerf} calculation.
\end{Switch}

%-----------------------------------------------------------
\begin{Operator}{gzerodim?}
\begin{Syntax}

  \name{gzerodim!?}\(\meta{basis}\)

\end{Syntax}
where \meta{bas} is a Groebner basis in the current
\nameref{term order} with the actual setting
(see \nameref{ideal parameters}).

\name{gzerodim!?} tests whether the ideal spanned by the given basis
has dimension zero. If yes, the number of zeros is returned,
\nameref{nil} otherwise.
\end{Operator}

%---------------------------------------------------------------

\begin{Operator}{gdimension}
\index{ideal dimension}\index{groebner}
\begin{Syntax}

     \name{gdimension}\(\meta{bas}\)

\end{Syntax}
where \meta{bas} is a \nameref{groebner} basis in the current
term order (see \nameref{ideal parameters}).
\name{gdimension} computes the dimension of the ideal
spanned by the given basis and returns the dimension as an integer
number. The Kredel-Weispfenning algorithm is used: the dimension
is the length of the longest independent variable set,
see \nameref{gindependent\_sets}
\end{Operator}

%---------------------------------------------------------------

\begin{Operator}{gindependent\_sets}
\index{ideal variables}\index{ideal dimension}\index{groebner}
\index{Kredel-Weispfenning algorithm}
\begin{Syntax}

  \name{gindependent\_sets}\(\meta{bas}\)

\end{Syntax}
where \meta{bas} is a \nameref{groebner} basis in any \name{term order}
(which must be the current \name{term order}) with the specified
variables (see \nameref{ideal parameters}).

\name{Gindependent_sets} computes the maximal
left independent variable sets of the ideal, that are
the variable sets which play the role of free parameters in the
current ideal basis. Each set is a list which is a subset of the
variable list. The result is a list of these sets. For an
ideal with dimension zero the list is empty.
The Kredel-Weispfenning algorithm is used.
\end{Operator}

%--------------------------------------------------------------

\begin{Operator}{dd_groebner}
For a homogeneous system of polynomials under
\nameref{graded term order}, \nameref{gradlex term order},
\nameref{revgradlex term order}
or \nameref{weighted term order}
a Groebner Base can be computed with limiting the grade
of the intermediate S polynomials:
\begin{Syntax}
\name{dd_groebner}\(\meta{d1},\meta{d2},\meta{plist}\)
\end{Syntax}
where \meta{d1} is a non negative integer and \meta{d2} is an integer
or ``infinity". A pair of polynomials is considered
only if the grade of the lcm of their head terms is between
\meta{d1} and \meta{d2}.
For the term orders \name{graded} or \name{weighted} the (first) weight
vector is used for the grade computation. Otherwise the total
degree of a term is used.
\end{Operator}

%--------------------------------------------------------------

\begin{Operator}{glexconvert}
\index{ideal variables}\index{term order}
\begin{Syntax}

\name{glexconvert}\(\meta{bas}[,\meta{vars}][,MAXDEG=\meta{mx}]
[,NEWVARS=\meta{nv}]\)

\end{Syntax}
where \meta{bas} is a \nameref{groebner} basis
in the current term order,  \meta{mx} (optional) is a positive
integer and \meta{nvl} (optional) is a list of variables
(see \nameref{ideal parameters}).

The operator \name{glexconvert} converts the basis
of a zero-dimensional ideal (finite number
of isolated solutions) from arbitrary ordering into a basis under
\nameref{lex term order}.

The parameter \meta{newvars} defines the new variable sequence.
If omitted, the
original variable sequence is used. If only a subset of variables is
specified here, the partial ideal basis is evaluated.

If \meta{newvars} is a list with one element, the minimal
\nameindex{univariate polynomial} is computed.

\meta{maxdeg} is an upper limit for the degrees. The algorithm stops with
an error message, if this limit is reached.

A warning occurs, if the ideal is not zero dimensional.
\begin{Comments}
During the call the \name{term order} of the input basis must
be active.
\end{Comments}
\end{Operator}

%--------------------------------------------------------------

\begin{Operator}{greduce}
\begin{Syntax}

\name{greduce}\(exp, \{exp1, exp2, \ldots , expm\}\)

\end{Syntax}

where exp is an expression, and \{exp1, exp2, ... , expm\} is
a list of expressions or equations.

\name{greduce} is functionally equivalent with a call to
\nameref{groebner} and then a call to \nameref{preduce}.
\end{Operator}

%---------------------------------------------------------

\begin{Operator}{preduce}
\begin{Syntax}

 \name{preduce}\(\meta{p}, \{\meta{exp}, \ldots \}\)

\end{Syntax}

where \meta{p} is an expression, and \{\meta{exp}, ... \} is
a list of expressions or equations.

\name{Preduce} computes the remainder of \name{exp}
modulo the given set of polynomials resp. equations.
This result is unique (canonical) only if the given set
is a \name{groebner} basis under the current \nameref{term order}

see also: \nameref{preducet} operator.

\end{Operator}

%-------------------------------------------

\begin{Operator}{idealquotient}
\begin{Syntax}

\name{idealquotient}\(\{\meta{exp}, ...\}, \meta{d}\)

\end{Syntax}
where \{\meta{exp},...\} is a list of
expressions or equations,  \meta{d} is a single expression or equation.

\name{Idealquotient} computes the ideal quotient:
ideal spanned by the expressions \{\meta{exp},...\}
divided by the single polynomial/expression \meta{f}. The result
is the \nameref{groebner} basis of the quotient ideal.
\end{Operator}

%-------------------------------------------------------------

\begin{Operator}{hilbertpolynomial}
\index{Hollmann algorithm}
\begin{Syntax}

  hilbertpolynomial\(\meta{bas}\)

\end{Syntax}
where \meta{bas} is a \nameref{groebner} basis in the
current \nameref{term order}.

The degree of the \name{Hilbert polynomial} is the
dimension of the ideal spanned by the basis. For an
ideal of dimension zero the Hilbert polynomial is a
constant which is the number of common zeros of the
ideal (including eventual multiplicities).
The \name{Hollmann algorithm} is used.
\end{Operator}

%-------------------------------------------

\begin{Operator}{saturation}
\begin{Syntax}

\name{saturation}\(\{\meta{exp}, ...\}, \meta{p}\)

\end{Syntax}
where \{\meta{exp},...\} is a list of
expressions or equations,  \meta{p} is a single polynomial.

\name{Saturation} computes the quotient of the polynomial \meta{p}
and a power (with unknown but finite exponent) of the ideal built from
\{\meta{exp}, ...\}. The result is the computed quotient. \name{Saturation}
calls \nameref{idealquotient} several times until the result does not change
any more.
\end{Operator}

%-------------------------------------------------------------
\subsection{Factorizing Groebner bases}
%-------------------------------------------------------------

\begin{Operator}{groebnerf}
\begin{Syntax}

\name{groebnerf}\(\{\meta{exp}, ...\}[,\{\},\{\meta{nz}, ... \}]\);

\end{Syntax}
where \{\meta{exp}, ... \} is a list of expressions or
equations, and \{\meta{nz},... \} is
an optional list of polynomials to be considered as non zero
for this calculation. An empty list must be passed as second argument
if the non-zero list is specified.

\name{groebnerf} tries to separate polynomials into individual factors and
to branch the computation in a recursive manner (factorization tree).
The result is a list of partial Groebner bases.
Multiplicities (one factor with a higher power, the same partial basis
twice) are deleted as early as possible in order to speed up the
calculation.

The third parameter of \name{groebnerf} declares some polynomials
nonzero. If any of these is found in a branch of the calculation
the branch is canceled.

\begin{Bigexample}
groebnerf({ 3*x**2*y+2*x*y+y+9*x**2+5*x = 3,
            2*x**3*y-x*y-y+6*x**3-2*x**2-3*x = -3,
            x**3*y+x**2*y+3*x**3+2*x**2 }, {y,x});

       {{Y - 3,X},

                      2
    {2*Y + 2*X - 1,2*X  - 5*X - 5}}
\end{Bigexample}

\begin{Related}
\item[ \nameref{groebresmax} variable]
\item[ \nameref{groebmonfac} variable]
\item[ \nameref{groebrestriction} variable]
\item[ \nameref{groebner} operator]
\item[ \nameref{gvarslast} variable]
\item[ \nameref{groebopt} switch]
\item[ \nameref{groebprereduce} switch]
\item[ \nameref{groebfullreduction} switch]
\item[ \nameref{gltbasis} switch]
\item[ \nameref{gltb} variable]
\item[ \nameref{glterms} variable]
\item[ \nameref{groebstat} switch]
\item[ \nameref{trgroeb} switch]
\item[ \nameref{trgroebs} switch]
\item[ \nameref{groebnert} operator]
\end{Related}

\end{Operator}

% ------------------------------------------------------------------

\begin{Variable}{groebmonfac}
The variable \name{groebmonfac} is connected to
the handling of monomial factors.  A monomial factor is a product
of variable powers as a factor, e.g. x**2*y  in  x**3*y -
2*x**2*y**2.  A monomial factor represents a solution of the type
 x = 0  or  y = 0 with a certain multiplicity.  With
\nameref{groebnerf} the multiplicity of monomial factors is lowered
to the value of the shared variable \name{groebmonfac}
which by default is 1 (= monomial factors remain present, but their
multiplicity is brought down). With
\name{groebmonfac}:= 0
the monomial factors are suppressed completely.
\end{Variable}

% ----------------------------------------------------------------
\begin{Variable}{groebresmax}
The variable \name{groebresmax}
controls  during \nameref{groebnerf} calculations
the number of partial results. Its default value is 300. If
more partial results are calculated, the calculation is
terminated.
\end{Variable}

% ----------------------------------------------------------------
\begin{Variable}{groebrestriction}
During \nameref{groebnerf} calculations
irrelevant branches can be excluded
by setting the variable \name{groebrestriction}. The
following restrictions are implemented:
\begin{Syntax}
     \name{groebrestriction} := \name{nonnegative} \\
     \name{groebrestriction} := \name{positive}\\
     \name{groebrestriction} := \name{zeropoint}
\end{Syntax}
With \name{nonnegative} branches are excluded where one
polynomial has no nonnegative real zeros; with \name{positive}
the restriction is sharpened to positive zeros only.
The restriction \name{zeropoint} excludes all branches
which do not have the origin (0,0,...0) in their solution
set.
\end{Variable}

%---------------------------------------------------------
\subsection{Tracing Groebner bases}
%---------------------------------------------------------
\index{tracing Groebner}
\begin{Switch}{groebprot}
If \name{groebprot} is \name{ON} the computation steps during
\nameref{preduce}, \nameref{greduce} and \nameref{groebner}
are collected in a list which is assigned to the variable
\nameref{groebprotfile}.
\end{Switch}
%----------------------------------------------------------
\begin{Variable}{groebprotfile}
See \nameref{groebprot} switch.
\end{Variable}
%----------------------------------------------------------

\begin{Operator}{groebnert}
\begin{Syntax}

  \name{groebnert}\(\{\meta{v}=\meta{exp},...\}\)

\end{Syntax}
where \meta{v} are \nameref{kernel}\name{s} (simple or indexed variables),
\meta{exp} are polynomials.

\name{groebnert} is functionally equivalent to a \nameref{groebner}
call for \{\meta{exp},...\}, but the result is a set of
equations where the left-hand sides are the basis elements while
the right-hand sides are the same values expressed as combinations
of the input formulas, expressed in terms of the names \meta{v}
\begin{Bigexample}
    groebnert({p1=2*x**2+4*y**2-100,p2=2*x-y+1});

   GB1 := {2*X - Y + 1=P2,

           2
        9*Y  - 2*Y - 199= - 2*X*P2 - Y*P2 + 2*P1 + P2}
\end{Bigexample}
\end{Operator}
%----------------------------------------------------------

\begin{Operator}{preducet}
\begin{Syntax}

\name{preduce}\(\meta{p},\{\meta{v}=\meta{exp}...\}\)
\end{Syntax}
where \meta{p} is an expression, \meta{v} are kernels
(simple or indexed variables),
\name{exp} are polynomials.

\name{preducet} computes the remainder of \meta{p} modulo \{\meta{exp},...\}
similar to \nameref{preduce}, but the result is an equation
which expresses the remainder as combination of the polynomials.
\begin{Bigexample}

   GB2 := {G1=2*X - Y + 1,G2=9*Y**2  - 2*Y - 199}
   preducet(q=x**2,gb2);

 - 16*Y + 208= - 18*X*G1 - 9*Y*G1 + 36*Q + 9*G1 - G2
\end{Bigexample}
\end{Operator}

%------------------------------------------------------------
\subsection{Groebner Bases for Modules}
%------------------------------------------------------------
\begin{Concept}{Module}
Given a polynomial ring, e.g. R=Z[x,y,...] and an integer n>1.
The vectors with n elements of R form a free MODULE under
elementwise addition and multiplication with elements of R.

For a submodule given by a finite basis a Groebner basis
can be computed, and the facilities of the GROEBNER package
are available except the operators \nameref{groebnerf}
and \name{groesolve}. The vectors are encoded using auxiliary
variables which represent the unit vectors in the module.
These are declared in the share variable \nameref{gmodule}.

\end{Concept}

\begin{Variable}{gmodule}
The vectors of a free \nameref{module} over a polynomial ring R
are encoded as linear combinations with unit vectors of
M which are represented by auxiliary variables. These
must be collected in the variable \name{gmodule} before
any call to an operator of the Groebner package.

\begin{verbatim}
   torder({x,y,v1,v2,v3})$
   gmodule := {v1,v2,v3}$
   g:=groebner({x^2*v1 + y*v2,x*y*v1 - v3,2y*v1 + y*v3});
\end{verbatim}

compute the Groebner basis of the submodule

\begin{verbatim}
      ([x^2,y,0],[xy,0,-1],[0,2y,y])
\end{verbatim}
The members of the list \name{gmodule} are automatically
appended to the end of the variable list, if they are not
yet members there. They take part in the actual term ordering.
\end{Variable}

%------------------------------------------------------------
\subsection{Computing with distributive polynomials}
%------------------------------------------------------------

\begin{Operator}{gsort}
\index{distributive polynomials}
\begin{Syntax}

 \name{gsort}\(\meta{p}\)
\end{Syntax}
where \meta{p} is a polynomial or a list of polynomials.

The polynomials are reordered and sorted corresponding to
the current \nameref{term order}.
\begin{Examples}

  torder lex;\\
  gsort(x**2+2x*y+y**2,{y,x});  &  {y**2+2y*x+x**2}

\end{Examples}
\end{Operator}

%------------------------------------------------------------

\begin{Operator}{gsplit}
\index{distributive polynomials}
\begin{Syntax}

 \name{gsplit}\(\meta{p}[,\meta{vars}]\);
\end{Syntax}
where \meta{p} is a polynomial or a list of polynomials.

The polynomial is reordered corresponding to the
the current \nameref{term order} and then
separated into leading term and reductum. Result is
a list with the leading term as first and the reductum
as second element.
\begin{Examples}

  torder lex;\\
  gsplit(x**2+2x*y+y**2,{y,x});  &  \{y**2,2y*x+x**2\}

\end{Examples}
\end{Operator}
%-------------------------------------------------------

\begin{Operator}{gspoly}
\index{distributive polynomials}
\begin{Syntax}

 \name{gspoly}\(\meta{p1},\meta{p2}\);

\end{Syntax}
where \meta{p1} and \meta{p2} are polynomials.

The \name{subtraction} polynomial of p1 and p2 is computed
corresponding to the method of the Buchberger algorithm for
computing \name{groebner bases}: p1 and p2 are multiplied
with terms such that when subtracting them the leading terms
cancel each other.
\end{Operator}


\documentclass[accepted]{uai2021}
\usepackage[british]{babel}
\usepackage{natbib}
\bibliographystyle{plainnat}
\renewcommand{\bibsection}{\subsubsection*{References}}
\usepackage{mathtools} % amsmath with fixes and additions
\usepackage{booktabs} % commands to create good-looking tables
\usepackage{tikz} % nice language for creating drawings and diagrams

\usepackage{amsthm}
\usepackage{amsfonts}
\usepackage[capitalise]{cleveref}

\DeclareMathOperator{\im}{im}

\newtheorem{innercustomthm}{Theorem}
\newenvironment{customthm}[1]
{\renewcommand\theinnercustomthm{#1}\innercustomthm}
{\endinnercustomthm}
\newtheorem{innercustomlemma}{Lemma}
\newenvironment{customlemma}[1]
{\renewcommand\theinnercustomlemma{#1}\innercustomlemma}
{\endinnercustomlemma}

\title{Weighted Model Counting with Conditional Weights for Bayesian Networks
  (Supplementary Material)}

\author{Paulius~Dilkas}
\author{Vaishak~Belle}
\affil{%
  University of Edinburgh\\
  Edinburgh, UK
}

\begin{document}
\maketitle

\section{Proofs}

\begin{customthm}{1}
  The function $\mu_\nu$ is a measure.
\end{customthm}
\begin{proof}
  Note that $\mu_\nu(\bot) = 0$ since there are no atoms below $\bot$. Let $a, b
  \in 2^{2^{U}}$ be such that $a \land b = \bot$. By elementary properties of
  Boolean algebras, all atoms below $a \lor b$ are either below $a$ or below
  $b$. Moreover, none of them can be below both $a$ and $b$ because then they
  would have to be below $a \land b = \bot$. Thus
  \begin{align*}
    \mu_\nu(a \lor b) &= \sum_{\{u\} \le a \lor b} \nu(u) = \sum_{\{u\} \le a} \nu(u) + \sum_{\{u\} \le b} \nu(u) \\
                      &= \mu_\nu(a) + \mu_\nu(b)
  \end{align*}
  as required.
\end{proof}

\begin{customthm}{3}
  For any set $U$ and measure $\mu\colon 2^{2^U} \to \mathbb{R}_{\ge 0}$, there
  exists a set $V \supseteq U$, a factorable measure $\mu'\colon 2^{2^V} \to
  \mathbb{R}_{\ge 0}$, and a formula $f \in 2^{2^V}$ such that $\mu(x) = \mu'(x
  \land f)$ for all formulas $x \in 2^{2^U}$.
\end{customthm}
\begin{proof}
  Let $V = U \cup \{ f_m \mid m \in 2^U \}$, and $f = \bigwedge_{m \in 2^U} \{ m
  \} \leftrightarrow f_m$. We define weight function $\nu\colon 2^V \to
  \mathbb{R}_{\ge 0}$ as $\nu = \prod_{v \in V} \nu_v$, where $\nu_v(\{v\}) =
  \mu(\{m\})$ if $v = f_m$ for some $m \in 2^U$ and $\nu_v(x) = 1$ for all other
  $v \in V$ and $x \in 2^{\{v\}}$. Let $\mu'\colon 2^{2^V} \to \mathbb{R}_{\ge
    0}$ be the measure induced by $\nu$. It is enough to show that $\mu$ and $x
  \mapsto \mu'(x \land f)$ agree on the atoms in $2^{2^U}$. For any $\{ a \} \in
  2^{2^U}$,
  \begin{align*}
    \mu'(\{ a \} \land f) &= \sum_{\{ x \} \le \{ a \} \land f} \nu(x) = \nu(a \cup \{ f_a \}) \\
                          &= \nu_{f_a}(\{ f_a \}) = \mu(\{ a \})
  \end{align*}
  as required.
\end{proof}

\begin{customlemma}{1} \label{lemma:cpt}
  Let $X \in \mathcal{V}$ be a random variable with parents $\mathrm{pa}(X) = \{ Y_1,
  \dots, Y_n \}$. Then $\mathrm{CPT}_X\colon 2^{\mathcal{E}^*(X)} \to
  \mathbb{R}_{\ge 0}$ is such that for any $x \in \im X$ and $(y_1, \dots, y_n)
  \in \prod_{i=1}^n \im Y_i$,
  \[
    \mathrm{CPT}_X (T) = \Pr(X = x \mid Y_1 = y_1, \dots, Y_n = y_n),
  \]
  where $T = \{ \lambda_{X=x} \} \cup \{ \lambda_{Y_i=y_i} \mid i = 1, \dots, n
  \}$.
\end{customlemma}
\begin{proof}
  If $X$ is binary, then $\mathrm{CPT}_X$ is a sum of $2\prod_{i=1}^n |\im
  Y_i|$ terms, one for each possible assignment of values to variables $X, Y_1,
  \dots, Y_n$. Exactly one of these terms is nonzero when applied to $T$, and
  it is equal to $\Pr(X = x \mid Y_1 = y_1, \dots, Y_n = y_n)$ by definition.

  If $X$ is not binary, then $\left( \sum_{i=1}^m [\lambda_{X = x_i}]
  \right)(T) = 1$, and $\left( \prod_{i=1}^m \prod_{j=i+1}^m
    (\overline{[\lambda_{X = x_i}]} + \overline{[\lambda_{X = x_j}]})
  \right)(T) = 1$, so $\mathrm{CPT}_X(T) = \Pr(X = x \mid Y_1 = y_1,
  \dots, Y_n = y_n)$ by a similar argument as before.
\end{proof}

\begin{customlemma}{2} \label{lemma:full_distribution}
  Let $\mathcal{V} = \{X_1, \dots, X_n\}$. Then
  \[
    \phi(T) =
    \begin{cases}
      \Pr(x_1, \dots, x_n) &
      \begin{aligned}
        &\text{if } T = \{ \lambda_{X_i=x_i} \}_{i = 1}^n \text{ for} \\
        &\text{some } \textstyle (x_i)_{i=1}^n \in \prod_{i=1}^n \im X_i
      \end{aligned} \\
      0 & \text{otherwise,}
    \end{cases}
  \]
  for all $T \in 2^U$.
\end{customlemma}
\begin{proof}
  If $T = \{ \lambda_{X=v_X} \mid X \in \mathcal{V} \}$ for some $(v_X)_{X
    \in \mathcal{V}} \in \prod_{X \in \mathcal{V}} \im X$, then
  \begin{align*}
    \phi(T) &= \prod_{X \in \mathcal{V}} \Pr \left( X=v_X \;\middle|\; \bigwedge_{Y \in \mathrm{pa}(X)} Y=v_Y \right) \\
            &= \Pr \left( \bigwedge_{X \in \mathcal{V}} X=v_X \right)
  \end{align*}
  by \cref{lemma:cpt} and the definition of a Bayesian network. Otherwise there
  must be some non-binary random variable $X \in \mathcal{V}$ such that
  $|\mathcal{E}(X) \cap T| \ne 1$. If $\mathcal{E}(X) \cap T = \emptyset$, then
  $\left( \sum_{i=1}^m [\lambda_{X = x_i}] \right)(T) = 0$, and so
  $\mathrm{CPT}_X(T) = 0$, and $\phi(T) = 0$. If $|\mathcal{E}(X) \cap T| > 1$,
  then we must have two different values $x_1, x_2 \in \im X$ such that
  $\{\lambda_{X=x_1}, \lambda_{X=x_2} \} \subseteq T$ which means that
  $(\overline{[\lambda_{X=x_1}]} + \overline{[\lambda_{X=x_2}]})(T) = 0$, and
  so, again, $\mathrm{CPT}_X(T) = 0$, and $\phi(T) = 0$.
\end{proof}

\begin{customthm}{4}
  For any $X \in \mathcal{V}$ and $x \in \im X$,
  \[
    (\exists_U(\phi \cdot [\lambda_{X=x}]))(\emptyset) = \Pr(X = x).
  \]
\end{customthm}
\begin{proof}
  Let $\mathcal{V} = \{ X, Y_1, \dots, Y_n \}$. Then
  \begin{align*}
    (\exists_U (\phi \cdot [\lambda_{X=x}]))(\emptyset) &= \sum_{T \in 2^U} (\phi \cdot [\lambda_{X=x}])(T) \\
                                                        &= \sum_{\lambda_{X=x} \in T \in 2^U} \phi(T) \\
                                                        &= \sum_{\lambda_{X=x} \in T \in 2^U} \left( \prod_{Y \in \mathcal{V}} \mathrm{CPT}_Y \right)(T) \\
                                                        &= \sum_{(y_i)_{i=1}^n \in \prod_{i=1}^n \im Y_i} \Pr(x, y_1, \dots, y_n) \\
                                                        &= \Pr(X = x)
  \end{align*}
  by:
  \begin{itemize}
  \item the proof of Theorem~1 by \citet{DBLP:conf/aaai/DudekPV20};
  \item if $\lambda_{X=x} \not\in T \in 2^U$, then $(\phi \cdot
    [\lambda_{X=x}])(T) = \phi(T) \cdot [\lambda_{X=x}](T \cap \{
    \lambda_{X=x} \}) = \phi(T) \cdot 0 = 0$;
  \item \cref{lemma:full_distribution};
  \item marginalisation of a probability distribution.
  \end{itemize}
\end{proof}

\bibliography{paper}
\end{document}


\section{Instances}
\label{sec:instances}

As mentioned before, the design of ARX ciphers ensures they are efficient at both
hardware and software levels. Hardware efficiency enables ARX can be run on most
constrained platforms, who typically equips with several KBs RAM and limited CPU power.
On the other hand, being efficient at software level also accelerate the PC applications
and services, for example, easing the burden of a busy Web server who accepts intensive
TLS connections.

In this section, two instances of ARX ciphers are introduced. The first one, called
\textsc{Speck}\cite{beaulieu2015simon2}, is designated on IoT devices. The second one,
called ChaCha\cite{bernstein2008chacha}, is a general-purposed stream cipher family,
and it is recently selected as the replacement of RC4 in the
TLS\footnote{\url{https://tools.ietf.org/html/rfc7905}} standard.

\subsection{The \textsc{\textbf{Speck}} Block Cipher}

\textsc{Speck} is designed specifically for encrypting data on constrained platforms.
It is also able to offer security services on diverse platforms with different security
levels, which are controlled by two security parameters.

\textsc{Speck} block cipher adopts the notation \textsc{Speck}$2n/nm$, where $2n$ is the
block size and $mn$ is the key size (in bits). In the design, $n\in\{16,24,32,48,64\}$
and each $n$ corresponds to a set of options for $m$. The \textsc{Speck} round function
is the (Feistel-based) map
$$R_k(x,y)=((\mathrm{r}^{-\alpha}x+y)\oplus k,\ \mathrm{r}^\beta y\oplus(\mathrm{r}^{-\alpha}x+y)\oplus k)$$
where $x$ and $y$ are $n$-bits quantities, and $k$ is the round key. The rotation
parameters $\alpha$ and $\beta$, and the number of rounds are specified along with
block size $n$.

\textsc{Speck} with $m$-size words accepts the initial key $K=(\ell_{m-2},\dots,\ell_0,k_0)$,
it then generates round keys as follows:

\begin{equation*}
\setlength{\abovedisplayshortskip}{0em}
\setlength{\abovedisplayskip}{0em}
\begin{split}
\ell_{i+m-1} &= (k_i+\mathrm{r}^{-\alpha}\ell_i)\oplus i\\
k_{i+1} &= \mathrm{r}^\beta k_i \oplus \ell_{i+m-1}
\end{split}
\end{equation*}

\noindent The value $k_i$ is the $i$-th round key.

\textsc{Speck}, by designed, uses \textit{simple} round function with necessary times
of rounds for security, as it offers compact implementation hence is suited for
constrained platforms. The use of uniform parameters (across different security levels)
also approves this purpose. Moreover, \textsc{Speck} can be done entirely in-place, so
unnecessary moves of word can be avoided to obtain better performance.

\subsection{The ChaCha Stream Cipher}

The cryptosystem ChaCha is a successor of the stream cipher Salsa20
\cite{bernstein2008salsa20}, which is designed to improve diffusion at each round. By
design, ChaCha is faster than existing standard ciphers, and is aimed at users who
value speed more than secrecy. ChaCha offers 3 variants, they are differed in the number
of rounds: 8, 12 and 20 rounds versions.

ChaCha itself computes a quarter-round to update 4 32-bits state words $(a,b,c,d)$ as:

\begin{equation*}
\setlength{\abovedisplayshortskip}{0em}
\setlength{\abovedisplayskip}{0em}
\begin{split}
a &= a+b\\[1pt]
c &= c+d\\[1pt]
a &= a+b\\[1pt]
c &= c+d\\[1pt]
\end{split}
\quad
\begin{split}
d &= \mathrm{r}^{16}(d\oplus a)\\
b &= \mathrm{r}^{12}(b\oplus c)\\
d &= \mathrm{r}^{8}(d\oplus a)\\
b &= \mathrm{r}^{7}(b\oplus c)\\
\end{split}
\end{equation*}

A ChaCha quarter-round gives each input word a chance to affect each output word, hence
achieves efficient diffusion at each round: every 1-bit input difference changes 12.5
output bits on average. This is the major difference between ChaCha and its predecessor
Salsa20, who affects on 8 bits per round.

ChaCha adopts the strategy that the plaintext and ciphertext do not affect the key stream,
in other word, it is a synchronous stream cipher. To apply the stream, ChaCha simply xor
it to the plaintext, as how a pseudorandom-OTP will work.

Google proposed ChaCha20 along with Poly1305 MAC as a replacement for RC4 in TLS, to
secures TLS/SSL traffic between the Chrome browser on Android and Google's websites.
Shortly after Google, both the ChaCha20 and Poly1305 were implemented for a new
cipher in OpenSSH. These adoptions imply that the ARX cipher family does not only
essential for hardware efficiency, but also important for software performance.


\chapter{Expressions}

{\REDUCE} expressions\index{Expression} may be of several types and consist
of sequences of numbers, variables, operators, left and right parentheses
and commas.  The most common types are as follows:

\section{Scalar Expressions}

\index{Scalar}Using the arithmetic operations {\tt + - * / \verb|^|}
(power) and parentheses, scalar expressions are composed from numbers,
ordinary ``scalar'' variables (identifiers), array names with subscripts,
operator or procedure names with arguments and statement expressions.

{\it Examples:}
\begin{verbatim}
        x
        x^3 - 2*y/(2*z^2 - df(x,z))
        (p^2 + m^2)^(1/2)*log (y/m)
        a(5) + b(i,q)
\end{verbatim}
The symbol ** may be used as an alternative to the caret symbol (\verb+^+)
for forming powers, particularly in those systems that do not support a
caret symbol.

Statement expressions, usually in parentheses, can also form part of
a scalar\index{Scalar} expression, as in the example
\begin{verbatim}
        w + (c:=x+y) + z .
\end{verbatim}
When the algebraic value of an expression is needed, {\REDUCE} determines it,
starting with the algebraic values of the parts, roughly as follows:

Variables and operator symbols with an argument list have the algebraic
values they were last assigned, or if never assigned stand for themselves.
However, array elements have the algebraic values they were last assigned,
or, if never assigned, are taken to be 0.

Procedures are evaluated with the values of their actual parameters.

In evaluating expressions, the standard rules of algebra are applied.
Unfortunately, this algebraic evaluation of an expression is not as
unambiguous as is numerical evaluation. This process is generally referred
to as ``simplification''\index{Simplification} in the sense that the
evaluation usually but not always produces a simplified form for the
expression.

There are many options available to the user for carrying out such
simplification\index{Simplification}.  If the user doesn't specify any
method, the default method is used.  The default evaluation of an
expression involves expansion of the expression and collection of like
terms, ordering of the terms, evaluation of derivatives and other
functions and substitution for any expressions which have values assigned
or declared (see assignments and {\tt LET} statements).  In many cases,
this is all that the user needs.

The declarations by which the user can exercise some control over the way
in which the evaluation is performed are explained in other sections.  For
example, if a real (floating point) number is encountered during
evaluation, the system will normally convert it into a ratio of two
integers.  If the user wants to use real arithmetic, he can effect this by
the command {\tt on rounded;}.\ttindex{ROUNDED} Other modes for
coefficient arithmetic are described elsewhere.

If an illegal action occurs during evaluation (such as division by zero)
or functions are called with the wrong number of arguments, and so on, an
appropriate error message is generated.
% A list of such error messages is given in an appendix.

\section{Integer Expressions}

\index{Integer}These are expressions which, because of the values of the
constants and variables in them, evaluate to whole numbers.

{\it Examples:}
\begin{verbatim}
        2,      37 * 999,       (x + 3)^2 - x^2 - 6*x
\end{verbatim}
are obviously integer expressions.
\begin{verbatim}
        j + k - 2 * j^2
\end{verbatim}
is an integer expression when {\tt J} and {\tt K} have values that are
integers, or if not integers are such that ``the variables and fractions
cancel out'', as in
\begin{verbatim}
        k - 7/3 - j + 2/3 + 2*j^2.
\end{verbatim}

\section{Boolean Expressions}
\label{sec-boolean}
A boolean expression\index{Boolean} returns a truth value.  In the
algebraic mode of {\REDUCE}, boolean expressions have the syntactical form:
\begin{verbatim}
        <expression> <relational operator> <expression>
\end{verbatim}
or
\begin{verbatim}
        <boolean operator> (<arguments>)
\end{verbatim}
or
\begin{verbatim}
        <boolean expression> <logical operator>
        <boolean expression>.
\end{verbatim}
Parentheses can also be used to control the precedence of expressions.

In addition to the logical and relational operators defined earlier as
infix operators, the following boolean operators are also defined:\\
\mbox{}\\
\ttindex{EVENP}\ttindex{FIXP}\ttindex{FREEOF}\ttindex{NUMBERP}
\ttindex{ORDP}\ttindex{PRIMEP}
{\renewcommand{\arraystretch}{2}
\begin{tabular}{lp{\redboxwidth}}
{\tt EVENP(U)} & determines if the number {\tt U} is even or not; \\

{\tt FIXP(U)} & determines if the expression {\tt U} is integer or not; \\

{\tt FREEOF(U,V)} & determines if the expression
{\tt U} does not contain the kernel {\tt V} anywhere in its
structure; \\

{\tt NUMBERP(U)} & determines if {\tt U} is a number or not; \\

{\tt ORDP(U,V)} & determines if {\tt U} is ordered
ahead of {\tt V} by some canonical ordering (based on the expression structure
and an internal ordering of identifiers); \\

{\tt PRIMEP(U)} & true if {\tt U} is a prime object, i.e., any object
other than 0 and plus or minus 1 which is only exactly divisible
by itself or a unit.
 \\
\end{tabular}}

{\it Examples:}
\begin{verbatim}
        j<1
        x>0  or  x=-2
        numberp x
        fixp x and evenp x
        numberp x and x neq 0
\end{verbatim}
Boolean expressions can only appear directly within {\tt IF}, {\tt FOR},
{\tt WHILE}, and {\tt UNTIL} statements, as described in other sections.
Such expressions cannot be used in place of ordinary algebraic expressions,
or assigned to a variable.

NB:  For those familiar with symbolic mode, the meaning of some of
these operators is different in that mode.  For example, {\tt NUMBERP} is
true only for integers and reals in symbolic mode.

When two or more boolean expressions are combined with {\tt AND}, they are
evaluated one by one until a {\em false\/} expression is found. The rest are
not evaluated. Thus
\begin{verbatim}
        numberp x and numberp y and x>y
\end{verbatim}
does not attempt to make the {\tt x>y} comparison unless {\tt X} and {\tt Y}
are both verified to be numbers.

Similarly, evaluation of a sequence of boolean expressions connected by
{\tt OR} stops as soon as a {\em true\/} expression is found.

NB:  In a boolean expression, and in a place where a boolean expression is
expected, the algebraic value 0 is interpreted as {\em false}, while all
other algebraic values are converted to {\em true}.  So in algebraic mode
a procedure can be written for direct usage in boolean expressions,
returning say 1 or 0 as its value as in

\begin{verbatim}
        procedure polynomialp(u,x);
           if den(u)=1 and deg(u,x)>=1 then 1 else 0;
\end{verbatim}

One can then use this in a boolean construct, such as
\begin{verbatim}
        if polynomialp(q,z) and not polynomialp(q,y) then ...
\end{verbatim}

In addition, any procedure that does not have a defined return value
(for example, a block without a {\tt RETURN} statement in it)
has the boolean value {\em false}.

\section{Equations}

Equations\index{Equation} are a particular type of expression with the syntax

\begin{verbatim}
        <expression> = <expression>.
\end{verbatim}

In addition to their role as boolean expressions, they can also be used as
arguments to several operators (e.g., {\tt SOLVE}), and can be
returned as values.

Under normal circumstances, the right-hand-side of the equation is
evaluated but not the left-hand-side.  This also applies to any substitutions
made by the {\tt SUB}\ttindex{SUB} operator.  If both sides are to be
evaluated, the switch {\tt EVALLHSEQP}\ttindex{EVALLHSEQP} should be
turned on.

To facilitate the handling of equations, two selectors, {\tt LHS}
\ttindex{LHS} and {\tt RHS},\ttindex{RHS} which return the left- and
right-hand sides of a equation\index{Equation} respectively, are provided.
For example,
\begin{verbatim}
        lhs(a+b=c) -> a+b
and
        rhs(a+b=c) -> c.
\end{verbatim}

\section{Proper Statements as Expressions}

Several kinds of proper statements\index{Proper statement} deliver
an algebraic or numerical result of some kind, which can in turn be used as
an expression or part of an expression.  For example, an assignment
statement itself has a value, namely the value assigned.  So
\begin{verbatim}
        2 * (x := a+b)
\end{verbatim}
is equal to {\tt 2*(a+b)}, as well as having the ``side-effect''\index{Side
effect} of assigning the value {\tt a+b} to {\tt X}.  In context,
\begin{verbatim}
        y := 2 * (x := a+b);
\end{verbatim}
sets {\tt X} to {\tt a+b} and {\tt Y} to {\tt 2*(a+b)}.

The sections on the various proper statement\index{Proper statement} types
indicate which of these statements are also useful as expressions.