\chapter{Gradual Typing Meets Dependent Types}
\label{chap:gradual-dependent}

\margintoc

Before diving into what \kl{GCIC} is about, let me first say what it is not about.
The aim is not to put forth a unique design or solution,
but rather to explore the space of possibilities.
Nor is it about a concrete implementation of gradual \kl{CIC} and an evaluation of its
applicability; these are challenging perspectives of their own,
which first require the theoretical landscape to be unveiled.
Rather, I believe that studying the gradualization of a full-blown dependent type theory
like \kl{CIC} is in and of itself a valuable scientific endeavour,
which is very likely to inform the gradual typing research community in its drive towards
supporting ever more challenging typing disciplines.

This being said, we can still highlight some practical motivating scenarios
for gradualizing \kl{CIC},
anticipating what could be achieved in a hypothetical gradual version of \eg \kl{Coq}.

\subsection{Smoother development with indexed types}
  \label{sec:indices}

Dependent type systems such as \kl{CIC}, which underpin languages and
proof assistants such as \kl{Coq},
\kl{Agda} and \kl{Idris}, among others, are very powerful system to program in,
but at the same time extremely demanding.
Mixing programs and their specifications is attractive, but challenging.

Consider the example of the vector type $\Vect(A,n)$ as defined in \cref{sec:tech-cic}.
In \kl{Coq}, its definition is the following:

\begin{coqcode}
Inductive vec (A : Type) : ℕ -> Type :=
| nil  : vec A 0
| cons : A -> forall n : ℕ, vec A n -> vec A (S n).
\end{coqcode}

Indexing the inductive type by its length allows us to define a \emph{total}
\coqe{head} function, which can only be applied to non-empty vectors:
\begin{coqcode}
  head : forall A n, vec A (S n) -> A
\end{coqcode}

Developing functions over such structures can be tricky. For instance, what type should the \coqe{filter} function be given?
\begin{coqcode}
  filter : forall A n (p : A -> 𝔹), vec A n -> vec A …
\end{coqcode}
The size of the resulting list depends on how many elements in the list actually match the given predicate \coqe{p}!
Dealing with this level of intricate specification can (and does) scare programmers away from mixing programs and specifications. The truth is that many libraries, such as the Mathematical
Components library \sidecite{Mahboubi2021},
give up on mixing programs and specifications even for simple structures such as these, which are instead dealt with as ML-like lists with extrinsically-established properties. This
tells a lot about the current intricacies of dependently-typed programming.

Instead of avoiding the obstacle altogether, gradual dependent types provide a uniform and flexible mechanism to a tailored adoption of dependencies. For instance, one could give \coqe{filter} the following gradual type, which makes use of the \reintro{unknown term} $\?$
in an index position:
\begin{coqcode}
  filter : forall A n (f : A -> 𝔹), vec A n -> vec A ?
\end{coqcode}
This imprecise type means that uses of \coqe{filter} will be optimistically accepted by the type-checker, although subject to associated checks during reduction. For instance,
\begin{coqcode}
head ℕ ? (filter ℕ 4 even [ 0 ; 1 ; 2 ; 3 ])
\end{coqcode}
type-checks, and successfully evaluates to \coqe{0}, while
\begin{coqcode}
head ℕ ? (filter ℕ 2 even [ 1 ; 3 ])
\end{coqcode}
type-checks but fails during reduction, upon the discovery that the assumption
of non-emptiness of the argument to head is in fact incorrect.

\subsection{Defining general recursive functions}
\label{sec:rec}

Another challenge of working in \kl{CIC} is to convince the type-checker that recursive
definitions are well-founded.
This can either require tight syntactic restrictions, or sophisticated arguments involving
accessibility predicates. At any given stage of a development,
one might not be in a position to follow any of these.
In such cases, a workaround is to adopt the “fuel” pattern, \ie parametrize a function with
a clearly syntactically decreasing argument in order to please the termination checker,
and to use an arbitrary initial fuel value.
In practice, one sometimes requires a simpler way to unplug termination checking,
and for that purpose, many proof assistants support external commands or parameters to deactivate termination checking.%
\mintedstring{terminating}{{-# TERMINATING #-}}%
\sidenote{For instance \mintinlinestring{agda}{terminating} in \kl{Agda}
or \coqe{Unset Guard Checking} in \kl{Coq}.}

Because the use of the \reintro{unknown type} $\?$
allows the definition of fixed point combinators \sidecite{Siek2006,Eremondi2019},
one can use this added expressiveness to bypass termination checking locally.
This just means that the external facilities provided by specific proof assistant implementations now become internalized in the language.

\subsection{Large elimination, gradually}
\label{sec:elim}

One of the argued benefit of dynamically-typed languages, which is accommodated by gradual typing, is the ability to define functions that can return values of different types depending on their inputs, such as the following:%
\sidenote{With \coqe{?>} a boolean comparison operator.}
\begin{coqcode}
  Definition foo n m := if (n ?> m) then m + 1 else m ?> 0.
\end{coqcode}

In a gradually-typed language, one can give such a function the type \coqe{?},
or even \coqe{ℕ -> ℕ -> ?} in order to enforce proper argument types,
and remain flexible in the treatment of the returned value.
Of course, we know very well that in a dependently-typed language, using large elimination, we can simply give \coqe{foo} the dependent type:
\begin{coqcode}
  foo : forall (n m : ℕ), if (n ?> m) then ℕ else 𝔹
\end{coqcode}

Lifting the term-level comparison \coqe{n ?> m} to the type level is extremely expressive, but hard to work with as well, both for the implementer of the function and its clients.
In a gradual, dependently-typed setting, one can explore the whole spectrum of type-level
precision for such a function, starting from the least precise to the most precise,
for instance:
\begin{coqcode}
    foo : ?
    foo : ℕ -> ℕ -> ?
    foo : ℕ -> ℕ -> if ? then ℕ else ?
    foo : forall (n m : ℕ), if (n ?> m) then ℕ else ?
    foo : forall (n m : ℕ), if (n ?> m) then ℕ else 𝔹
\end{coqcode}

At each stage from top to bottom, there is less flexibility – but more guarantees! –
for both the implementer of \coqe{foo} and its clients. The \kl{gradual guarantee}%
\sidenote{One of the important properties we seek in our \kl{GCIC}.}
ensures that if the function is actually faithful to the most precise type
then giving it any of the less precise types above does not introduce any new failure
\sidecite{Siek2015}.

\subsection{Gradually refining specifications}
\label{sec:specif}

Let us come back to the \coqe{filter} function from the first example.
Its fully-precise type requires appealing to a type-level function that counts the number of
elements in the list satisfying the predicate
– notice the dependency to the input vector \coqe{v}:
\begin{coqcode}
  filter : forall A n (p : A -> 𝔹) (v : vec A n),
            vec A (count A n p v)
\end{coqcode}

Anticipating the need for this function, a gradual specification could adopt the above
signature for \coqe{filter} but leave \coqe{count} unspecified:
\begin{coqcode}
Definition count A n (p : A -> 𝔹) (v: vec A n) : ℕ := ?.
\end{coqcode}

This situation does not affect the behaviour of the program compared to leaving the return type index unknown. More interestingly, one could immediately define the base case, which trivially specifies that there are no matching elements in an empty vector:
\begin{coqcode}
Definition count A n (p : A -> 𝔹) (v : vec A n) : ℕ :=
  match v with
  | nil _ _ => 0
  | cons _ _ _ => ?
  end.
\end{coqcode}

This slight increment in precision provides a little more static checking, for instance:
\coqe{head ℕ ? (filter ℕ 4 even [])}
does not even type-check, instead of failing during reduction.

Again, the gradual guarantee ensures that such incremental refinements in precision towards the proper fully-precise version do not introduce spurious errors.
Note that this is in stark contrast with the use of axioms – which will be discussed in more depth in \cref{sec:axiom}. Indeed, replacing correct code with an axiom can simply break typing! For instance, with the following definitions:
\begin{coqcode}
Axiom to_be_done : ℕ.
Definition count A n (p : A -> 𝔹) (v: vec A n) : ℕ :=
  to_be_done.
\end{coqcode}
the definition of \coqe{filter} does not type-check any more,
as the axiom at the type-level is not convertible to any given value.

\subsection{Gradual programs or proofs?}

When adapting the ideas of gradual typing to a dependent type theory, one might
expect to deal with programs rather than proofs.
This observation is however misleading: from the point of view of the Curry-Howard correspondence, proofs and programs are intrinsically related, so that gradualizing the latter begs for a gradualization of the former. The examples above illustrate mixed programs and specifications, which naturally also appeal to proofs: dealing with indexed types typically requires exhibiting equality proofs to rewrite terms.
Moreover, there are settings in which one must consider computationally-relevant proofs, such as constructive algebra and analysis, homotopy type theory, etc. In such settings, using axioms to bypass unwanted proofs breaks reduction, and because typing requires reduction, the use of axioms can simply prevent typing, as illustrated in the last example.

\subsection{Fundamental trade-offs}

Before exposing a specific approach to gradualizing \kl{CIC},
there is a need for a general analysis of the properties at stake and tensions
that arise when gradualizing a dependent type theory.

Thus, in what follows
we start by recalling the two cornerstones properties of progress and normalization,
and explain the need to reconsider them carefully in a gradual setting
(\cref{sec:norm-canon-endang}).
Next, we show why two obvious approaches based respectively on axioms (\cref{sec:axiom}),
and exceptions (\cref{sec:extt}) are unsatisfying.
We then turn to the gradual approach, recalling its essential properties in the simply-typed
setting (\cref{sec:grad-simple}),
and revisiting them in the context of a dependent type theory (\cref{sec:graduality}).
This finally leads us to establish a fundamental impossibility in the gradualization
of \kl{CIC}, which means that at least one of the desired properties has to be sacrificed (\cref{sec:fire-triangle}).
With all set up, we can finally present our \kl(typ){gradual},
\kl{dependently} typed system, \kl{GCIC}, and its main characteristics
(\cref{sec:gcic-overview}).

\section{Safety and Normalization, Endangered}[Safety and Normalization]
\label{sec:norm-canon-endang}

% As a well-behaved typed programming language, \kl{CIC} enjoys
% (type) \intro{safety}%
% %  \sidenote{That we abbreviate as \psafe in this part.}
% – the combination of \kl{progress} and \kl{preservation} –,
% meaning that well-typed closed terms cannot get stuck,
% \ie that normal, closed terms of a given type are exactly the \kl{canonical forms} of that type.
% %
% % In \kl{CIC}, a closed canonical form is a term whose typing derivation ends
% % with an introduction rule, \ie a $\lambda$-abstraction for a function
% % type, and a constructor for an inductive type.
% %
% % For instance, any closed term of type \coqe{bool} is convertible (and
% % reduces) to either \coqe{true} or \coqe{false}.
% Note that a normal open term, on the contrary, must not be \kl{canonical form}.
% Instead, it can also be a \kl{neutral form}.

% As a logically consistent type theory, \kl{CIC} also enjoys \kl{normalization},
% %(\pnorm)
% meaning that any term reduces to its (unique) normal form.
% \kl{Normalization}, together with \kl{safety}, imply \kl{canonicity}:
% any closed term of a given type \emph{must} reduce to a \kl{canonical form} of that type.
% %
% When applied to the empty type $\Empty$, canonicity ensures \kl{logical consistency}:
% because there is no canonical form for $\Empty$, there is no
% closed proof of $\Empty$.
% %
% Note that \kl{normalization} also has an important consequence in \kl{CIC}. Indeed, in
% this system, conversion---which coarsely means syntactic equality
% up-to reduction---is used in the type-checking algorithm.

In the gradual setting, the two cornerstone properties of \kl{CIC} exposed in
\cref{sec:tech-properties}, \kl{safety}%
\sidenote{The combination of \kl{progress} and \kl{preservation}.}
and \kl{normalization}, must be considered with care.
%

First, any \kl{closed term} can be ascribed the unknown type $\?$
and then any other type: for instance, $\z \ascop \? \ascop \Bool$ is a
well-typed closed term of type $\Bool$.%
\sidenote{
  We write $\intro*\asc{a}{A}$ for a type \intro{ascription}, used to “force” the term $a$ to inhabit type $A$.
  We define it as syntactic sugar for $(\l x:A.\ x)\ a$ \cite{Siek2006},
  so $\z \ascop \? \ascop \Bool$ is $(\z \ascop \?) \ascop \Bool$. In
  other systems, it is taken as a primitive notion \cite{Garcia2016}.}%
\margincite{Siek2006}%
\margincite{Garcia2016}
However, such a term
cannot possibly reduce to either $\true$ or $\false$, so some
concessions must be made with respect to \kl{safety} – at the very least, the notion
of canonical forms must be extended.
%

\AP Second, \kl{normalization} is endangered.
The quintessential example of non-termination in the untyped lambda calculus is the
term $\Omega$, defined as $\delta~\delta$
where $\delta$ is $\l x.\ (x\ x)$.
In the \intro{simply-typed lambda calculus}%
  \sidenote{Hereafter abbreviated as \intro{STLC}.},
as in \kl{CIC}, \emph{self-applications} like $\delta\ \delta$ and $x\ x$ are ill-typed.
However, when introducing gradual types, one usually expects to accommodate such idioms,
and therefore in a standard gradually-typed calculus such as
\intro{GTLC}%
\sidenote{The gradual counterpart to \kl{STLC}.}
\cite{Siek2006}, a variant of $\Omega$ that uses
$(\l x : \?.\ x\ x)$ as $\delta$ is well-typed and diverges – \ie reduces indefinitely.
The reason is that the domain type of $\delta$, the \kl{unknown type} $\?$,
is \reintro(grad){consistent} with the type of $\delta$ itself,
$\? \to \?$, meaning that we wish to optimistically accept the application as
plausibly valid. But at runtime, nothing prevents reduction from going on forever.
Therefore, if one aims at ensuring \kl{normalization} in a gradual setting,
some care must be taken to restrict expressiveness.

\section{Non-Gradual Approaches}

\subsection{Axioms}
\label{sec:axiom}

Let us first address the elephant in the room:
why would one want to gradualize \kl{CIC} instead of simply postulating
an axiom for any term – be it a program or a proof – that one does not feel like providing (yet)?

\AP Indeed, we can augment \kl{CIC} with a wildcard axiom $\intro*\axiom \ty \P A : \uni.\ A$.
The resulting system, called \intro{CICax}, has an obvious practical benefit: we can use
$\axiom A$
%\sidenote{Hereafter written $\axiom[A]$.}
as a wildcard whenever we are
asked to exhibit an inhabitant of some type $A$ and we do not (yet) want to.
This is exactly what admitted definitions are in \kl{Coq}, for instance,
and they do play an important practical role during any \kl{Coq} development.

However, we cannot use the axiom $\axiom A$ in any meaningful way \emph{at the
  type level}.
%
For instance, going back to the examples of \cref{sec:indices},
one might be tempted to give to the \coqe{filter} function on vectors the type
\begin{coqcode}
  forall A n (p : A -> 𝔹), vec A n -> vec A (ax ℕ)
\end{coqcode}
%
in order to avoid the complications related to specifying the
size of the vector produced by \coqe{filter}.
%
The problem is that the term:
\begin{coqcode}
  head ℕ (ax ℕ) (filter ℕ 4 even [ 0 ; 1 ; 2 ; 3 ])
\end{coqcode}
is ill-typed since the type of the filtering expression, \coqe{vec A (ax ℕ)},
is not convertible to \coqe{vec A (S (ax ℕ))}, as required by
\coqe{head ℕ (ax ℕ)} in its domain type.

Thus, the axiomatic approach is not useful for making dependently-typed programming
any more pleasing.
%
That is, using axioms goes in total opposition to the \kl{gradual guarantee}
– characteristic of gradual languages \sidecite{Siek2015}~–
when it comes to the smoothness of
the static-to-dynamic checking spectrum: given a well-typed term,
making it “less precise” by using axioms for some sub-terms actually
results in programs that do not type-check or reduce any more.

%
Because \kl{CICax} amounts to working in \kl{CIC}
with an initial context extended with $\axiom$, this theory
satisfies \kl{normalization} as much as \kl{CIC}, so conversion remains decidable.
However, \kl{CICax} lacks a satisfying notion of \kl{safety}, because
there is an \emph{infinite} number of \emph{stuck} terms
that inhabit any type \coqe{A}.
%
For instance, in $\Bool$, we not only have the normal forms $\true$,
$\false$, and $\axiom \Bool$, but also plenty of terms stuck on an
elimination of $\axiom$, such as $\axiom (\Nat \to \Bool)\ 1$ or
$\ind{\Nat}{\axiom \Nat}{P}{b_{\z},b_{\Sop}}$.

\subsection{Exceptions}
\label{sec:extt}

\sidetextcite{Pedrot2018} present the exceptional type theory \intro{ExTT},
demonstrating that it is possible to extend a
type theory with a wildcard term while enjoying a satisfying notion of \kl{safety},
which coincides with that of programming languages with exceptions.

\kl{ExTT} is essentially \kl{CICrai}, that is, it
extends \kl{CIC} with an exceptional term $\intro*\rai[A]$ that can inhabit any type $A$.
But instead of being treated as a computational black box like $\axiom A$,
$\rai[A]$ is endowed with computational content
emulating exceptions in programming languages, which propagate instead of being stuck.
%
For instance, in \kl{ExTT} the following conversion holds:
\[\ind{\Bool}{\rai[\Bool]}{\Nat}{\z,1} \conv \rai[\Nat]\]

\AP Notably, such exceptions are \intro{call-by-name} exceptions, so one can only
discriminate exceptions on positive types – \ie inductive types –, not on negative
types – \ie function types. In particular, in \kl{ExTT}, $\rai[A \to B]$ reduces to
$\l x : A.\ \rai[B]$.
So $\rai[A]$ is a normal form of $A$ only if $A$ is a positive type.

\kl{ExTT} has a number of interesting properties. It is
\kl{normalizing} and \kl{safe}, taking $\rai[A]$
into account as usual in programming languages,
where exceptions are possible outcomes of computation: the canonical forms
of a positive type – \eg $\Bool$ – are either the
constructors of that type – \eg $\true$ and $\false$ –, or
$\rai$ at that type – \eg $\rai[\Bool]$.
%
As a consequence, \kl{ExTT} does not satisfy full \kl{canonicity}, but
a weaker form of it. In particular, it enjoys
(weak) \kl{logical consistency}: any closed proof of $\Empty$ is \kl{convertible}
to $\rai[\Empty]$, which is discriminable at $\Empty$.
%
It has been shown that we can still reason soundly in an
exceptional type theory, either using a parametricity
requirement \sidecite{Pedrot2018}, or, more flexibly, a
different universe hierarchies \sidecite{Pedrot2019}.

It is also important to highlight that this weak form of \kl{logical
consistency} is the \emph{most} one can expect in
a theory with effects. Indeed, \sidetextcite{Pedrot2020} have
shown that it is not possible to define a type theory with full
dependent elimination%
\sidenote{That is, a term former such as $\indop$.}
that has observable effects – of which
exceptions are a particular case – and at the same time validates
traditional \kl{canonicity}.
%
Settling for less, as explained in \cref{sec:axiom} for the axiomatic
approach, leads to an infinite number of stuck terms, even in the
case of booleans, which contradicts the type safety criterion of gradual languages,
which only allows for runtime type errors.

Unfortunately, while \kl{ExTT} solves the safety issue of the axiomatic approach, it still suffers from the same limitation as the axiomatic approach regarding type-level comparison.
Indeed, even though we can use $\rai$ to inhabit any type,
we cannot use it in any meaningful way at the type level.
In such a system, the following term is ill-typed
\begin{coqcode}
  head ℕ (raise ℕ) (filter ℕ 4 even [ 0 ; 1 ; 2 ; 3 ])
\end{coqcode}
as \coqe{vec A (raise ℕ)} is still not convertible to
\coqe{vec A (S (raise ℕ))}.
The reason is that \coqe{raise ℕ} behaves like an extra constructor of type \coqe{ℕ}, so
that \coqe{S (raise ℕ)} is itself a normal form,
and normal forms with different head constructors
– \coqe{S} and \coqe{raise} – are not convertible.

\section{Gradual Simple Types}
\label{sec:grad-simple}

Before going on with our exploration of the fundamental challenges in gradual dependent type
theory, let us go over some key concepts and expected properties,
in the context of simple types.

\subsection{Static semantics}

\AP \intro[gradual typing]{Gradually typed} languages introduce the
\reintro{unknown type}, written $\?$,
which is used to indicate the lack of static typing information \sidecite{Siek2006}.
One can understand such an unknown type as an abstraction of the
set of possible types that it stands for \sidecite{Garcia2016}.
This interpretation provides a naive but natural understanding of the meaning of
partially-specified types. For instance $\Bool \to \?$ denotes the set of all function types
with $\Bool$ as domain.
Given imprecise types, a gradual type system relaxes all type predicates and functions in order
to optimistically account for occurrences of $\?$.
In a simple type system, the main predicate on types is equality, whose relaxed counterpart is called \intro(grad){consistency}%
\sidenote{Not to be confused with \kl{logical consistency}!},
usually written $\cons$.
For instance, given a function $f$ of type $\Bool \to \?$, the expression $(f\ \true) + 1$
should be well-typed. Indeed, $f$ could \emph{plausibly} return a number,
given that its codomain is $\?$, which is \kl(grad){consistent} with $\Nat$.

Note that there are other ways to consider imprecise types, for instance by restricting the
unknown type to denote base types – in which case $\?$ would not be \kl(grad){consistent} with any
function type –, or by only allowing imprecision in certain parts of the syntax of types,
such as effects \sidecite{BanadosSchwerter2016}, security labels
\sidecite{Fennell2013,Toro2018}, annotations \sidecite{Thiemann2014},
or only at the top-level \sidecite{Bierman2010}.
Here, we do not consider these specialized approaches, which have benefits and challenges
of their own, and stick to the mainstream setting of gradual typing
in which the unknown type is \kl(grad){consistent} with any type and can occur
anywhere in the syntax of types.

\subsection{Dynamic semantics}

Having optimistically relaxed typing based on \kl(grad){consistency},
a gradual language must detect inconsistencies at runtime if it is to satisfy \kl{safety},
which therefore has to be formulated in a way that encompasses runtime errors.

\AP For instance, if the function $f$ above returns $\false$,
then an \kl{error} must be raised to avoid reducing to $\false + 1$ – a closed stuck term,
corresponding to a violation of safety.
The traditional approach to do so is to avoid giving a direct reduction semantics to gradual
programs, and, instead, to elaborate them to an intermediate language with runtime \kl{casts},
in which casts between inconsistent types raise \reintro{errors}%
\sidenote{We write those $\err$.}
\sidecite{Siek2006}.

In such a language, the notion of \kl{canonical form} used to phrase \kl{progress} –~and,
thus, \kl{safety} – has to account for these newly introduced errors. Indeed, $\err[A]$
is now a valid \kl{canonical form} at type $A$ – at least for some types such as $\Bool$,
since, as we explained in \cref{sec:extt},
\kl{call-by-name} errors are not normal forms of function types.

Alternatively – and equivalently from a semantics point of view – one can define \kl{reduction}
of gradual programs directly on gradual typing derivations augmented with evidence about
consistency judgments, and report errors when transitivity of such judgments is
unjustified \sidecite{Garcia2016}.
There are many ways to realize each of these approaches,
which vary in terms of efficiency and eagerness of checking \sidecite{Herman2010,TobinHochstadt2008,Siek2010,Siek2009,Toro2020,BanadosSchwerter2021}.

\subsection{Conservativity}
\AP A first important property of a gradual language is that it is a
\reintro{conservative extension} of a related static typing discipline:
the gradual and static systems should coincide on static terms.
This property is hereafter called \reintro{conservativity},
with respect to a given static system.
%For instance, we write that \GTLC satisfies \pconst{\STLC}.
Technically, \sidetextcite{Siek2006} prove that typing and reduction of \kl{GTLC} and
\kl{STLC} coincide on their common set of terms – \ie those which are fully precise.
An important aspect of \kl{conservativity} is that the type formation rules and typing
rules themselves are also preserved, up to the presence of $\?$ as a new type and the
adequate lifting of predicates and functions \sidecite{Garcia2016}.
While this aspect is often left implicit, it ensures that the gradual type system does not
behave in ad hoc ways on imprecise terms.

Note that, despite its many issues, \kl{CICax} (\cref{sec:axiom}) satisfies
\kl{conservativity} (with respect to \kl{CIC}):
all pure – \ie axiom-free – \kl{CIC} terms behave as they would in \kl{CIC}.
More precisely, two \kl{CIC} terms are convertible in \kl{CICax}
if and only if they are convertible in \kl{CIC}.
Importantly, this does not mean that \kl{CICax} is a conservative extension of
\kl{CIC} \emph{as a logic} – which it clearly is not!

\subsection{Gradual guarantees}
\AP The early accounts of gradual typing emphasized \kl(grad){consistency} as the central idea.
However, \sidetextcite{Siek2015} observed that this characterization left too many
possibilities for the impact of type information on program behaviour,
compared to what was originally intended \sidecite{Siek2006}.
%
Consequently, they brought forth type \intro{precision}%
\sidenote{Denoted $\intro*\pre$: $A \pre B$ means that $A$ is more precise than $B$,
\ie that $A$ contains more static information than $B$.}
as the key notion, from which consistency can be derived: two types $A$ and $B$
are consistent if and only if there exists $T$ such that $T \pre A$ and $T \pre B$.
The \kl{unknown type} $\?$ is the most imprecise type of all,
\ie $T \pre \?$ for any $T$.
%
Precision is a pre-order that can be used to capture the intended \emph{monotonicity} of
the static-to-dynamic spectrum afforded by gradual typing.
The static and dynamic \intro{gradual guarantees} respectively specify that typing
and reduction should be \emph{monotone with respect to precision}:
losing precision should not introduce new static or dynamic errors.
%
These properties require precision to be extended from types to terms.
\textcite{Siek2015} present a natural extension that is purely syntactic:
a term is more precise than another if they are \kl{α-equal}, except
for their type annotations, which can be more precise in the former.

\AP The \kl{static gradual guarantee} (\intro{SGG})
ensures that imprecision does not alter typeability.

\begin{minipage}{\textwidth}
\begin{property}[\intro{Static Gradual Guarantee}]
If $t \pre u$ and $\vdash t \ty T$, then $\vdash u \ty U$
for some $U$ such that $T \pre U$.
\end{property}
\end{minipage}

%
This \kl{SGG} captures the intuition that “sprinkling $\?$ over a term“
maintains its typeability. As such, the notion of \kl{precision} $\pre$ used to
formulate the \kl{SGG} is inherently syntactic,
over as-yet-untyped terms: typeability is the \emph{consequence} of the \kl{SGG} theorem.

\AP The \kl{dynamic gradual guarantee} (\intro{DGG}) is the key result that
links the syntactic notion of precision to reduction:
if $t \pre t'$ and $t$ reduces to some value $v$, then
$t'$ reduces to some value $v'$ such that $v \pre v'$;
and if $t$ diverges, then so does $t'$.
This  entails that $t \pre t'$ means that $t$ may \kl{error} more than $t'$,
but otherwise they should behave the same.
%
Instead of the original formulation of the DGG by
\textcite{Siek2015}, \sidetextcite{New2018} appeal to the
semantic notion of \kl{observational error-approximation} to capture
the relation between two terms that are contextually equivalent, except
that one may fail more:%
\sidenote{\kl{Observational error-approximation}
  does not mention the case where $\mathcal{C}[t]$
  reduces to $\true$ or $\false$, but the quantification
  over all contexts ensures that, in that case,
  $\mathcal{C}[t']$ must reduce to the same value.}

\begin{definition}[\intro{Observational error-approximation}]
\label{def:obsapprox}
  A term $\Gamma \vdash t \ty T$ \kl{observationally error-approximates}
  a term $\Gamma \vdash t' \ty T'$, noted $ t
  \intro*\obsApprox t'$, if for all boolean-valued observation contexts
  $\mathcal{C} : (\Gamma \vdash T) \Rightarrow (\vdash \Bool)$
  closing over all free variables, either
  \begin{itemize}
  \item $\mathcal{C}[t]$ and $\mathcal{C}[t']$ both diverge;
  \item otherwise if $\mathcal{C}[t'] \red \err[\Bool]$, then $\mathcal{C}[t] \red \err[\Bool]$.
  \end{itemize}

  Two terms $t$ and $t'$ are \intro{observationally equivalent}, written $t \intro*\obsEquiv t'$,
  if they are related by \kl{observational error-approximation} in both directions.
\end{definition}

Using this semantic notion, the \kl{DGG} simply states that term
precision implies \kl{observational error-approximation}:

\begin{property}[\intro{Dynamic Gradual Guarantee}]
If $t \pre t'$ then $t \obsApprox t'$.
\end{property}

While often implicit, it is important to highlight that the \kl{DGG} is relative to
both the notion of \kl{precision} $\pre$ and the notion of observations $\obsApprox$.
Indeed, it is possible to study alternative notions of precisions beyond the natural definition
stated by \sidetextcite{Siek2015}.
For instance, following the Abstracting Gradual Typing methodology \sidecite{Garcia2016},
\kl{precision} follows from the definition of gradual types through a concretization to sets
of static types. This opens the door to justifying alternative precisions,
\eg by considering that the unknown type only stands for specific static types, such as base types.
Additionally, variants of precision have been studied in more challenging typing disciplines where
the natural definition seems incompatible with the \kl{DGG}, see \eg \sidetextcite{Igarashi2017}.
As we will soon see, it can also be necessary in certain situations to consider another notion of observations.

\subsection{Graduality}

As we have seen, the \kl{DGG} is relative to a notion of \kl{precision},
but what should this relation be?
To go beyond a syntactic axiomatic definition of \kl{precision}, \sidetextcite{New2018}
characterize the good dynamic behaviour of a gradual language:
the runtime checking mechanism used to define it, such as casting,
should only perform type-checking, and not otherwise affect behaviour.

\AP Specifically, they mandate that precision gives rise
to \intro{embedding-projection pairs} (\reintro{ep-pairs}):
the cast induced by two types related by precision forms an adjunction,
which induces a retraction.
In particular, going to a less precise type and back is the identity:
for any term $a$ of type $A$, and assuming $A \pre B$,
$\asc{\asc{a}{B}}{A}$%
\sidenote{Recall that $\ascop$ is a type \kl{ascription}.}
should be observationally equivalent to $a$.
For instance, $\asc{\asc{1}{\?}}{\Nat}$ should be equivalent to $1$.
Dually, when gaining precision, there is the potential for \kl{errors}:
given a term $b$ of type $B$, $\asc{\asc{b}{A}}{B}$ may fail.
By considering \kl{error} as the most precise term, this can be stated as
$\asc{\asc{b}{A}}{B} \pre b$.
For instance, with the imprecise successor function $f$ of type $\? \to \?$,
defined as $\l n : \?.\ \asc{\S n}{\?}$,
we have $\asc{\asc{f}{\Nat \to \Bool}}{\? \to \?} \pre f$,
because the ascribed function will fail when applied.

Technically, the adjunction part states that if we have $A \pre B$, a term $a$ of type $A$,
and a term $b$ of type $B$, then $a \pre \asc{b}{A}$ if and only if $\asc{a}{B} \pre b$.
%
\AP The retraction part further states that $a$ is not only more \kl{precise}
than $\asc{\asc{a}{B}}{A}$ – which is given by the unit of the adjunction –
but is \reintro{equi-precise} to it – noted $t \intro*\equiprecise \asc{\asc{t}{B}}{A}$.
Because the \kl{DGG} dictates that precision implies \kl{observational error-approximation},
\kl{equi-precision} implies \kl{observational equivalence},
and so losing and recovering precision must produce a term that is \kl{observationally
equivalent} to the original one.

% A couple of additional observations need to be made here, as they will play a major role in the development that follows.
These two approaches to characterizing gradual typing highlight
the need to distinguish
\emph{syntactic} from \emph{semantic} notions of precision.
Indeed, with the usual syntactic \kl{precision} from \sidetextcite{Siek2015},
one cannot derive the \kl{ep-pair} property, in particular the \kl{equi-precision} stated above.
This is why \sidetextcite{New2018} introduce a semantic \kl{precision},
defined on well-typed terms. This semantic \kl{precision} serves
as a proxy between syntactic \kl{precision} and the desired
\kl{observational error-approximation}.
%
However, a type-based semantic \kl{precision} cannot be used for the \kl{SGG}.
Indeed, this theorem%
\sidenote{Not addressed by \textcite{New2018}.}
requires a notion of \kl{precision} that \emph{predates} typing:
well-typedness of the less precise term is the \emph{consequence} of the theorem.
Therefore, a full study of a gradual language that covers \kl{SGG}, \kl{DGG}, and
\kl{embedding-projection pairs} needs to consider both syntactic and semantic
notions of \kl{precision}.

Note also that the \kl{embedding-projection} property does not
\textit{per se} imply the \kl{DGG}: one could pick \kl{precision} to be the universal relation,
which trivially induces \kl{ep-pairs}, but does not imply \kl{observational error-approximation}.
Conversely, it appears that, in the simply-typed setting considered in prior work,
the \kl{DGG} implies the \kl{embedding-projection} property.
In fact, \textcite{New2018} essentially advocate \kl{ep-pairs} as an elegant and compositional
proof technique to establish the \kl{DGG}.
But as we uncover later on, it turns out that in certain settings – and in particular dependent types – the \kl{embedding-projection} property imposes \emph{more}
desirable constraints on the behaviour of casts than the \kl{DGG} alone.

\AP In regard of these two remarks, in what follows we use the term \intro{graduality}
for the \kl{DGG} established with respect to a notion of \kl{precision} which also
induces \kl{embedding-projection pairs}.

\section{Graduality and Dependent Types}
\label{sec:graduality}

Extending the gradual approach to a setting with full \kl(typ){dependent} types
requires reconsidering several aspects.

\subsection{Newcomers: the unknown term and the error type}[Unknown term and error type]
%
In the simply-typed setting, there is a clear stratification: $\?$ is at the type level,
$\err$ is at the term level. Likewise, type \kl{precision}, with $\?$ as greatest element,
is distinct from term \kl{precision}, with $\err$ as least element.
In the absence of a type/term syntactic distinction as in \kl{CIC},
this stratification cannot be kept.

Because types permeate terms, $\?$ is no longer only the \kl{unknown} \emph{type},
but it also acts as an “\kl{unknown term}”.
In particular, this makes it possible to consider unknown indices for types,
as in \cref{sec:indices}.
More precisely, there is a family of \kl{unknown terms} $\?[A]$, indexed by their type $A$.
The traditional \kl{unknown type} is just $\?[\uni]$, the \kl{unknown} of the universe $\uni$.

Dually, because terms permeate types, we also have the “\kl{error} type”, $\err[\uni]$.
We have to deal with \kl{errors} in types.

Finally, \kl{precision} must be unified as a single pre-order, with $\?$ at the top
and $\err$ at the bottom.
The most imprecise term of all%
\sidenote{More exactly, there is one such term per universe.}
is $\?[\?[\uni]]$ – $\?$ for short. At the bottom, $\err[A]$
is the most precise term of type $A$.

\subsection{Revisiting safety}

The notion of \kl{canonical forms} used for \kl{safety} needs to be extended not
only with errors as in the simply-typed setting, but also with \kl{unknown terms}.
Indeed, as there is an \kl{unknown term} $\?[A]$ inhabiting any type
$A$, we have one new canonical form for each type $A$. In particular,
$\?[\Bool]$ cannot possibly reduce to either $\true$, $\false$, or $\err[\Bool]$,
because doing so would collapse the precision order.
%
Therefore, $\?[\Bool]$ should propagate computationally, exactly
like $\rai[\Bool]$ in \cref{sec:extt} and $\err[\Bool]$.
%

The difference between \kl{errors} and \kl{unknown terms} is not on their dynamic behaviour,
but rather on their static interpretation.
%
In essence, the unknown term $\?[A]$ is a dual form of exceptions: it
propagates, but is optimistically comparable – \ie \kl(grad){consistent}
with – any other term of type $A$. Conversely, $\err[A]$ should not be consistent
with any term of type $A$.
%
Going back to the issues we identified with the axiomatic (\cref{sec:axiom})
and exceptional (\cref{sec:extt}) approaches when dealing with type-level comparison,
the term
\begin{coqcode}
  head ℕ (? ℕ) (filter ℕ 4 even [ 0 ; 1 ; 2 ; 3 ])
\end{coqcode}
is now well-typed: since \coqe{S (? ℕ)} is \kl(grad){consistent} with \coqe{? ℕ},
\coqe{vec A (? ℕ)} can be deemed \kl(grad){consistent} with
\coqe{vec A (S (? ℕ))}.
This newly-brought flexibility is the key to support the different scenarios from the introduction.
%
So let us now turn to the question of how to integrate \kl(grad){consistency} in
a dependently-typed setting.

\subsection{Relaxing conversion}

In the simply-typed setting, \kl(grad){consistency} is a relaxing of syntactic type equality
to account for imprecision.
In a dependent type theory, there is a more powerful notion than syntactic equality to compare types, namely \kl{conversion}.
The proper notion to relax in the gradual dependently-typed setting is therefore \kl{conversion},
not syntactic equality.

\AP \sidetextcite{Garcia2016} give a general framework for gradual typing that explains how to relax any type predicate to account for imprecision:
for a binary type predicate $P$, its \intro{consistent lifting} $\mathop{\tilde{P}}(A,B)$ holds
if there exist static types $A'$ and $B'$ in the denotation%
\sidenote{Concretization, in abstract interpretation parlance.}
of $A$ and $B$, respectively, such that $\mathop{P}(A',B')$.
As observed by \sidecite{Castagna2019}, when applied to equality,
this defines \kl(grad){consistency} as a unification problem.
Therefore, the \kl{consistent lifting} of \kl{conversion} ought to be that two terms
$t$ and $u$ are consistently convertible if they denote some static terms $t'$ and $u'$ such that $t' \conv u'$. This is essentially \kl{higher-order unification},
which is an undecidable problem.

It is therefore necessary to adopt some approximation of this relation
in order to be able to implement a gradual dependent type theory.
There lies an important challenge: because of the dependency of typing on \kl{conversion},
the \kl{static gradual guarantee} already demands monotonicity of the approximation
one chooses. But if this approximation is defined using reduction, this demand is
very close to that of the \kl{dynamic gradual guarantee}.%
\sidenote{In a dependently-typed programming language with separate typing and execution phases, this demand is called the normalization gradual guarantee \cite{Eremondi2019}.}%
\margincite{Eremondi2019}
In practice, this means that the \kl{SGG} essentially depends on the \kl{DGG}!

\subsection{Dealing with neutrals}
Previous work on gradual typing usually only considers reduction on \kl{closed} terms in order to establish results about the dynamic semantic, such as the \kl{DGG}.
%
But in dependent type theory, conversion must operate on \kl{open} terms,
and in particular \kl{neutral} terms such as $\asc{\asc{1}{X}}{\Nat}$,
where $X$ is a type variable, or $x + 1$ where $x$ is of type $\Nat$ or $\?[\uni]$.
%
Such \kl{neutral} terms cannot reduce further, and can occur in both terms and types.
Depending on the upcoming substitution, neutrals can fail, or not. For instance, in $\asc{\asc{1}{X}}{\Nat}$, if $\?[\uni]$ is substituted for $X$, the term should reduce to $1$,
but it should fail if $\Bool$ is substituted instead.

Importantly, less precise variants of \kl{neutrals} can reduce \emph{more}.
For instance, $\asc{\asc{1}{\?[\uni]}}{\Nat}$ and $\?[\Nat] + 1$ are respectively
less precise than the neutrals above, but do evaluate further – respectively to $1$
and to $\?[\Nat]$. This interaction between \kl{neutrals}, \kl{reduction}, and \kl{precision}
spices up the goal of establishing \kl{DGG} and \kl{graduality}.
In particular, this re-enforces the need to consider a semantic notion of \kl{precision},
because a too syntactic one is likely not to be stable by reduction:
$\asc{\asc{1}{X}}{\Nat} \pre \asc{\asc{1}{\?}}{\Nat}$ is obvious syntactically,
but $\asc{\asc{1}{X}}{\Nat} \pre 1$ is not.

\subsection{Dynamic Gradual Guarantee \vs graduality}[DGG \vs graduality]
In a dependently-typed setting, it is possible to satisfy the \kl{DGG} while not satisfying the \kl{embedding-projection pairs} requirement of \kl{graduality}.

To see why, consider a system in which any term of type $A$ that is not
fully-precise immediately reduces to $\?[A]$.
This system would satisfy \kl{conservativity}, \kl{safety}, \kl{normalization}…
and the \kl{DGG}. Indeed, recall that the \kl{DGG} only requires \kl{reduction}
to be monotone with respect to \kl{precision}, so using the most imprecise term
$\?$ as a universal reduct is surely valid. This collapse of the \kl{DGG}
is impossible in the simply-typed setting because there is no \kl{unknown term}:
it is only possible when $\?[A]$ exists \emph{as a term}.
It is therefore possible to satisfy the \kl{DGG} while being useless when
\emph{computing} with imprecise terms.

On the contrary, the degenerate system breaks the \kl{embedding-projection} requirement of graduality stated by \sidetextcite{New2018}.
For instance, $\asc{\asc{1}{\?[\uni]}}{\Nat}$ would be convertible to $\?[\Nat]$,
which is \emph{not} \kl{observationally equivalent} to $1$.
Therefore, the \kl{embedding-projection} requirement of graduality goes beyond the
\kl{DGG} in a way that is critical in a dependent type theory,
where it captures both the smoothness of the static-to-dynamic checking spectrum,
and the proper computational content of valid uses of imprecision.

\subsection{Observational refinement}

Let us come back to the notion of \kl{observational
error-approximation} used in the simply-typed setting to state the
\kl{DGG}.
\textcite{New2018} justify this notion because in
”gradual typing we are not particularly interested in
when one program diverges more than another, but rather when it
produces more type errors”.

%
This point of view is adequate in the simply-typed setting because
the addition of ascriptions may only produce more type errors; in particular,
adding ascriptions can never lead to divergence
when the original term does not diverge itself.
%
Thus, in that setting, the definition of \kl{observational error-approximation}
includes equi-divergence.
%

The situation in the dependent setting is however more
complicated if the theory admits divergence.%
\sidenote{
  There exist non-gradual dependently-typed programming languages that admit divergence, \eg \kl{Dependent Haskell} \cite{Eisenberg2016} or
  \kl{Idris} \cite{Brady2013}.
  We will also present one such theory in this article.
}%
\margincite{Eisenberg2016}%
\margincite{Brady2013}
In a gradual dependent type theory that admits divergence,
a diverging term is more precise than the
\kl{unknown term} $\?$. Because the unknown term does not diverge, this
breaks the left-to-right implication of
equi-divergence. Note that this argument does not rely on any specific definition of precision,
just on the fact that the unknown is a term, and not just a type.

Additionally, an error at a diverging type $X$ may be ascribed to $\?[\uni]$,
then back to $X$. Evaluating this
roundtrip requires evaluating $X$ itself, which makes the less
precise term diverge. This breaks the right-to-left implication of
equi-divergence.

To summarize,
the way to understand these counterexamples is that
in a dependent and non-terminating setting,
the motto of graduality ought to be adjusted: more precise programs produce
more type errors \emph{or diverge more}. This leads to the following definition
of \kl{observational refinement}.

\begin{definition}[\intro{Observational refinement}]
\label{def:obsref}
  A term $\Gamma \vdash t \ty A$ \kl{observationally refines} a term
  $\Gamma \vdash u \ty A$, noted $\intro* t \obsRef u$, if for all boolean-valued observation context
  $\mathcal{C} \ty (\Gamma \vdash A) \Rightarrow (\vdash \Bool)$ closing over all
  free variables, if $\mathcal{C}[u] \red \err[\Bool]$ or diverges,
  then either $\mathcal{C}[t] \red \err[\Bool]$ or $\mathcal{C}[t]$ diverges.
\end{definition}

The main difference with \kl{observational error-approximation} is that
in this definition, errors and divergence are collapsed.
In particular, equi-refinement does \emph{not} imply \kl{observational equivalence},
because one term might diverge while the other reduces to an error.
Happily, if the gradual dependent theory is strongly normalizing, both notions
\kl{observational error-approximation} $\obsApprox$ and \kl{observational refinement} $\obsRef$
coincide.

\section{The Fire Triangle of Graduality}[Fire Triangle of Graduality]
\label{sec:fire-triangle}

To sum up, we have so far seen four important properties that can be expected from a
gradual type theory:
\kl{safety}, \kl{conservativity} with respect to a given static system, \kl{graduality},
and \kl{normalization}. Any type theory ought to satisfy at least \kl{safety}.
Unfortunately, we now show that mixing the three other properties is impossible for \kl{STLC},
and \textit{a fortiori} for \kl{CIC}.

\subsection{Preliminary: regular reduction}
To derive this general impossibility result by relying only on the properties
and without committing to a specific language or theory,
we need to assume that the reduction system used to decide conversion is "regular".
This means that it only looks at the \kl(red){weak-head} normal forms of
sub-terms for reduction rules,
and does not magically shortcut reduction,
for instance based on the specific syntax of inner terms.
As an example, β-reduction is not allowed to look into the body of
the lambda term to decide how to proceed.

This property is satisfied in all actual systems we know of,
but formally stating it in full generality, in particular without devoting
to a particular syntax, is beyond our current scope.
Fortunately, in the following, we rely only on a much weaker hypothesis,
which is a slight strengthening of the retraction hypothesis of \kl{embedding-projection pairs}.
Recall that retraction says that when $A \pre B$, any term $t$ of type $A$
is equi-precise to $\asc{\asc{t}{B}}{A}$.

We additionally require that for any context $\mathcal{C}$, if $\mathcal{C}[t]$
reduces at least $k$ steps, then $\mathcal{C}[\asc{\asc{t}{B}}{A}]$ also reduces at
least $k$ steps.
Intuitively, this means that the reduction of $\mathcal{C}[\asc{\asc{t}{B}}{A}]$,
while free to decide when to get rid of the embedding-to-$B$-projection-to-$A$,
cannot use it to avoid reducing $t$.
This property is true in all gradual languages,
where type information at runtime is used only as a monitor.

\subsection{Gradualizing \kl(tit){STLC}}
Let us first consider the case of \kl{STLC}.
We show that $\Omega$ is \emph{necessarily} a well-typed, diverging term in any
gradualization of \kl{STLC} that satisfies the other properties.

\pagebreak

\begin{marginfigure}
  \includegraphics{Fire_triangle.pdf}
  \caption{The Fire Triangle of Graduality}
\end{marginfigure}

\begin{theorem}[\reintro{Fire Triangle of Graduality} for \kl{STLC}]
  \label{thm:triangle-STLC}

Suppose a gradual type theory that satisfies both \kl{conservativity} with respect to
\kl{STLC} and \kl{graduality}. Then it cannot be \kl{normalizing}.

\end{theorem}

\begin{proof}

  We pose $\Omega \coloneqq \delta\ (\asc{\delta}{\?})$ with
  $\delta \coloneqq \l x : \?.\ (\asc{x}{\? \to \?})~x$
  and show that it must necessarily be a well-typed, diverging term.
  %
  Because the unknown type $\?$ is consistent with any type (\cref{sec:grad-simple}) and
  $\? \to \?$ is a valid type (by \kl{conservativity}),
  the self-applications in $\Omega$ are well-typed,
  $\delta$ has type $\? \to \?$, and $\Omega$ has type $\?$.
  %
  Now, we remark that $\Omega = \mathcal{C}[\delta]$ with
  $\mathcal{C}[\cdot] \coloneqq [\cdot]~(\asc{\delta}{\?})$.
  %

  We show by induction on $k$ that $\Omega$ reduces at least $k$
  steps, the initial case being trivial.
  %
  Suppose that $\Omega$ reduces at least $k$ steps.
  % %
  By maximality of $\?$ with respect to precision, we have that
  $\? \to \? \pre \?$, so we can apply the strengthening of \kl{graduality}
  applied to $\delta$, which tells us that
  $\mathcal{C}[\asc{\asc{\delta}{\?}}{\?\to\?}]$
  reduces at least $k$ steps, because $\mathcal{C}[\delta]$ reduces at least $k$ steps.

  But $\Omega$ reduces in one step of β-reduction to
  $\mathcal{C}[\asc{\asc{\delta}{\?}}{\?\to\?}]$.
  So $\Omega$ reduces at least $k+1$ steps.

  This means that $\Omega$ diverges, which is a violation of \kl{normalization}.
\end{proof}

This result could be extended to all terms of the untyped lambda calculus, not only $\Omega$,
in order to obtain the embedding theorem of \kl{GTLC} \sidecite{Siek2015}.
Therefore, the embedding theorem is not an independent property, but rather a consequence of \kl{conservativity} and \kl{graduality}. This is why we have not included it in
our overview of the gradual approach in \cref{sec:grad-simple}.

\subsection{Gradualizing \kl(tit){CIC}}
We can now prove the same impossibility theorem for \kl{CIC}, by reducing
it to the case of \kl{STLC}.
In general, this theorem can be proven for type theories others than \kl{CIC},
as soon as they faithfully embed \kl{STLC}.

\begin{theorem}[\intro{Fire Triangle of Graduality} for \kl{CIC}]
\label{thm:triangle}

  A gradual dependent type theory cannot simultaneously satisfy
  \kl{conservativity} with respect to \kl{CIC}, \kl{graduality} and \kl{normalization}.
\end{theorem}

\begin{proof}
  We show that a gradual dependent type theory satisfying \kl{CIC} and \kl{graduality}
  must contain a diverging term, thus contravening \kl{normalization}.
  The typing rules of \kl{CIC} contain the typing rules of \kl{STLC},
  using only one universe $\uni[0]$,
  and the notions of reduction coincide, so \kl{CIC} embeds
  \kl{STLC}. This is a well-known result on \kl{Pure Type Systems} \sidecite{Barendregt1991}, of which \kl{CCω} is one of many examples.
  %
  This means that \kl{conservativity} with respect to \kl{CIC} implies \kl{conservativity}
  with respect to \kl{STLC}.

  Additionally, \kl{graduality} can be specialized to the simply-typed fragment of the theory,
  by setting the unknown type $\?$ to be $\?[\uni[0]]$.
  We can then apply \cref{thm:triangle-STLC},
  and get a diverging well-typed term, finishing the proof.
\end{proof}

\subsection{The Fire Triangle in practice}

In non-dependent settings, all gradual languages where $\?$ is universal
admit non-termination and therefore compromise \kl{normalization}.
\sidetextcite{Garcia2020} discuss the possibility to gradualize \kl{STLC}
without admitting non-termination, for instance by considering that $\?$ is not universal
and denotes only base types%
\sidenote{In such a case, $\? \to \? \not \pre \?$,
  so our argument involving $\Omega$ is invalid.}.
Without sacrificing the universal unknown type, one could design a variant of \kl{GTLC}
that uses some mechanism to detect divergence, such as termination contracts
\sidetextcite{Nguyen2019}. This would yield a language that certainly satisfies
\kl{normalization}, but it would break \kl{graduality}. Indeed, because the contract system is
necessarily under-approximating in order to be sound – and actually imply \kl{normalization} –,
there are effectively-terminating programs with imprecise variants that yield termination
contract errors.

\AP To date, the only related work that considers
the gradualization of full dependent types with
$\?$ as both a term and a type, is the work on \intro{GDTL} \sidecite{Eremondi2019}.
\kl{GDTL} is a programming language with a clear separation between the typing and execution
phases, like \kl{Idris} \sidecite{Brady2013}.
\kl{GDTL} adopts a different strategy in each phase:
for typing, it uses \intro{Approximate Normalization}, which always produces $\?[A]$ as a result
of going through imprecision and back. This implies that the system is \kl{normalizing} – and thus that conversion is decidable –, but it breaks \kl{graduality} for the same reason as the
degenerate system we discussed in \cref{sec:graduality}%
\sidenote{The example uses a gain of precision from the unknown type to $\Nat$,
  so it behaves just the same in \kl{GDTL}}.
In such a phased setting, the lack of computational content of Approximate Normalization is not
critical, because it only means that typing becomes overly optimistic.
To execute programs, \kl{GDTL} relies on standard \kl{GTLC}-like reduction semantics,
which is computationally precise, but not \kl{normalizing}.

\section{\kl(tit){GCIC}: An Overview}
\label{sec:gcic-overview}

Given the \kl{Fire Triangle of Graduality} (\cref{thm:triangle}),
we know that gradualizing \kl{CIC} implies making some compromise.
Instead of focusing on one possible solution, we actually develop
a common parametrized framework, \kl{GCIC}, where the parameters control
which of the three properties – \kl{normalization}, \kl{graduality} and \kl{conservativity} –
is compromised.
This section gives an informal, non-technical overview of this system,
highlighting the main challenges and results.

\subsection{Three in one}
\label{sec:gcic:-3-1}

\paragraph{Two parameters…}

To explore the spectrum of possibilities opened by the \kl{Fire Triangle of Graduality},
we develop a general approach to gradualizing \kl{CIC}, and use it to define three theories, corresponding to different resolutions of the triangular tension between \kl{normalization}, \kl{graduality} and \kl{conservativity} with respect to \kl{CIC}.

The crux of our approach is to recognize that, while there is not much to vary within \kl{STLC} itself to address the tension of the \kl{Fire Triangle of Graduality},
there are several variants of \kl{CIC} that can be considered by changing
the hierarchy of universes and its impact on typing –
after all, its core \kl{CCω}
is but a particular \kl{Pure Type System} \sidecite{Barendregt1991}.
Thus, we consider a parametrized version of a gradual \kl{CIC}, called
\kl{GCIC}, with two parameters%
\sidenote{This system is precisely detailed in \cref{fig:ccic-ty}}.

\AP The first parameter characterizes how the universe level of a Π-type is determined
in typing rules: either as taking the \emph{maximum} of the levels of the involved
types – as in standard \kl{CIC} – or as the \emph{successor} of that maximum.
The latter option yields a variant of \kl{CIC} that we call \intro{CICs} – read “\kl{CIC}-shift”.
\kl{CICs} is a subset of \kl{CIC}, with a stricter constraint on universe levels.
In particular \kl{CICs} loses the closure of universes under
dependent functions that \kl{CIC} enjoys.
As a consequence, some well-typed \kl{CIC} terms are not well-typed in \kl{CICs}.%
\sidenote{
  A typical example of a well-typed \kl{CIC} term that is ill typed in \kl{CICs} is
  $\narrow \ty \Nat \to \uni$, where $\narrow n$ is the type of functions that
  accept $n$ arguments. Such dependent arities violate the universe constraint of \kl{CICs}.}

The second parameter is the dynamic counterpart of the first parameter:
its role is to control universe levels during the reduction of type casts between Π-types.
We only allow this reduction parameter to be loose – \ie~using maximum –
if the typing parameter is also loose. Indeed, letting the typing parameter be strict
– \ie using successor of the maximum – while the reduction parameter is loose
breaks subject reduction, and hence \kl{safety}.

\paragraph{… and three meaningful theories.}

Based on these parameters, we develop the following three variants of \kl{GCIC},
whose properties are summarized in \cref{fig:gcic-summary}
% with pointers to the respective theorems
– because \kl{GCIC} is one common parametrized framework,
we are able to establish most properties for all variants at once.

\AP The first variant, \intro{GCICP},
is a theory that satisfies both \kl{conservativity} with respect to \kl{CIC}
and \kl{graduality}, but sacrifices \kl{normalization}.
This theory is a rather direct application of the
principles discussed in \cref{sec:graduality} by extending \kl{CIC}
with \kl{errors} and \kl{unknown terms}, and replacing \kl{conversion} with
\kl(grad){consistency}. This results in a theory that is not normalizing.

\AP Next, \intro{GCICs} satisfies both \kl{normalization} and \kl{graduality},
and supports \kl{conservativity}, but only with respect to \kl{CICs}.
This theory uses the universe hierarchy at the \emph{typing level} to detect and forbid
the potential non-termination induced by the use of \kl(grad){consistency}
instead of \kl{conversion}.

\AP Finally, \intro{GCICT} satisfies both \kl{conservativity} with respect to \kl{CIC}
and \kl{normalization}, but does not fully validate \kl{graduality}.
This theory uses the universe hierarchy at the \emph{computational level} to detect
potential divergence, eagerly raising errors.
Such runtime failures invalidate the \kl{DGG} for some terms,
and hence \kl{graduality}, as well as the \kl{SGG}, since in our dependent setting it depends
on the \kl{DGG}.

\begin{figure*}[h]
  \begin{tabular}{ccccccc}
   & \kl{Safety} & \kl{Normalization} & \kl{Conservativity} wrt. & \kl{Graduality} & \kl{SGG} & \kl{DGG} \\
  \kl{GCICP} \rule{0pt}{4ex}
    & {\checksymbol {\checksymbol ✓}} %\footnotesize{(Th.~\labelcref{thm:ccic-psafe})}
    & {\checksymbol ✗}
    & \kl{CIC} %\footnotesize{(Th.~\labelcref{thm:conservativity})}
    & {\checksymbol ✓} %\footnotesize{(Th. ~\labelcref{thm:GCICP-graduality})}
    & {\checksymbol ✓} %\footnotesize{(Th.~\labelcref{thm:static-graduality})}
    & {\checksymbol ✓} %\footnotesize{(Th.~\labelcref{thm:dgg})}\\
  \\
  \kl{GCICs} \rule{0pt}{4ex}
    & {\checksymbol ✓} %\footnotesize{(idem)}
    & {\checksymbol ✓} %\footnotesize{(Th.~\labelcref{thm:ccic-pnorm} \& \labelcref{thm:discrete-model})}
    & \kl{CICs}  %\footnotesize{(idem)}
    & {\checksymbol ✓} %\footnotesize{(Th.~\labelcref{thm:graduality-gcics})}
    & {\checksymbol ✓} %\footnotesize{(idem)}
    & {\checksymbol ✓} %\footnotesize{(Th.~\labelcref{thm:dgg})}\\
  \\
  \kl{GCICT} \rule{0pt}{4ex}
    & {\checksymbol ✓} %\footnotesize{(idem)}
    & {\checksymbol ✓} %\footnotesize{(idem)}
    & \kl{CIC} %$\mathsf{CIC}$\phantom{$^{\uparrow}$}    \footnotesize{(idem)}
    & {\checksymbol ✗}
    & {\checksymbol ✗}
    & {\checksymbol ✗}\\
  \end{tabular}\\

  \caption{\kl{GCIC} variants and their properties}
  \label{fig:gcic-summary}
\end{figure*}

\paragraph{Practical implications of \kl{GCIC} variants.}
Regarding our introductory examples, all three variants of \kl{GCIC}
support the exploration of the type-level precision spectrum.
In particular, we can define \coqe{filter} by giving it the imprecise type
\begin{coqcode}
  forall A n (p : A -> 𝔹), vec A n -> vec A (? ℕ)
\end{coqcode}
in order to bypass the difficulty of precisely characterizing the size of the output vector.
Any invalid optimistic assumption is detected during reduction and reported as an error.

Unsurprisingly, the semantic differences between the three \kl{GCIC} variants crisply manifest in the treatment of potential non-termination, more specifically, \emph{self application}.
%
Let us come back to the term $\Omega$
used in the proof of~\cref{thm:triangle}.
In all three variants, this term is well-typed. In \kl{GCICP}, it
reduces forever, as it would in the untyped lambda calculus:
\kl{GCICP} can embed the untyped lambda calculus, just as
\kl{GTLC} \sidecite{Siek2015}. In \kl{GCICT}, this term fails at runtime
because of the strict universe check in the reduction of casts, which
breaks graduality because $\?[\uni[i]] \to \?[\uni[i]] \pre \?[\uni[i]]$
tells us that the upcast-downcast coming from an \kl{ep-pair} should not fail.
%
In \kl{GCICs}, $\Omega$ fails in the same way as in \kl{GCICT}, but this
does not break graduality because of the shifted universe level on Π-types.
%
Indeed, a consequence of this stricter typing rule is that in \kl{GCICs},
$\?[\uni[i]] \to \?[\uni[i]] \pre \?[\uni[j]]$
for any $j > i$, but $\?[\uni[i]] \to \?[\uni[i]] \npre \?[\uni[j]]$.
Therefore, the casts performed in $\Omega$ do not come from an \kl{ep-pair}
any more, and can thus legitimately fail.
%
This is described in full details in \cref{sec:back-to-omega}.

Another scenario where the differences in semantics manifest is functions with
\emph{dependent arities}.
For instance, the well-known C function \printf{} can be embedded in a well-typed fashion in
\kl{CIC}: it takes as first argument a format string and computes from it both
the type and \emph{number} of later arguments.
In \kl{GCICP} it can be gradualized as much as one wants, without surprises.
%
This function, however, brings into light the limitation of \kl{GCICs}:
since the format string can specify an arbitrary number of arguments,
we need as many $\to$, and \printf{} cannot be well-typed
in a theory where universes are not closed under function types.
%
In \kl{GCICT}, \printf{} is well-typed, but the same problem will appear dynamically
when casting \printf{} to $\?$ and back to its original type: the result will be
a function that works only on format strings specifying no more arguments than
the universe level at which it has been typed.
%
Note that this constitutes an example of violation of graduality for
\kl{GCICT}, even of the dynamic gradual guarantee.

\paragraph{Which variant to pick?}
As explained in the introduction, the aim here is to shed light on the design space of gradual
dependent type theories, not to advocate for one specific design.
%
The appropriate choice indeed depends on the specific goals of the language designer,
or perhaps more pertinently, on the specific goals of a given project,
at a specific point in time.
The key characteristics of each variant are as follows.

\kl{GCICP} favours flexibility over decidability of type-checking. While this might appear
heretical in the context of proof assistants, this choice has been embraced by practical languages such as \kl{Dependent Haskell} \sidecite{Eisenberg2016},
where both divergence and runtime errors can happen at the type
level. The pragmatic argument is simplicity: by letting programmers be responsible,
there is no need for termination checking techniques and other restrictions.

\kl{GCICs} is theoretically pleasing as it enjoys both normalization and graduality.
In practice, though, the fact that it is not conservative with respect to full \kl{CIC}
means that one would not be able to simply import existing libraries as soon as they
fall outside the \kl{CICs} subset.
In \kl{GCICs}, the introduction of $\?$ should be done with an appropriate understanding of
universe levels. This might not be a problem for advanced programmers,
but would surely be harder to grasp for beginners.

Finally, \kl{GCICT} is normalizing and able to import existing libraries without restrictions,
at the expense of some surprises on the graduality front.
Programmers would have to be willing to accept that they cannot just sprinkle $\?$
as they see fit without further consideration,
as any dangerous usage of imprecision will be flagged during conversion.

In the same way that systems like \kl{Coq}, \kl{Agda} or \kl{Idris} support
different ways to customize their semantics regarding termination,%
\sidenote{With the possibility to allow $\uni : \uni$, switch off termination checking,
use the partial/total compiler flags…}
and of course, many programming languages implementations supporting some sort of customization%
\sidenote{GHC is a salient representative.}
one can imagine a flexible realization of \kl{GCIC} that give users the control over the two
parameters we identify in this work, and therefore lets them access all three \kl{GCIC} variants.
%
Considering the inherent tension captured by the \kl{Fire Triangle of Graduality},
such a pragmatic approach might be the most judicious choice,
making it possible to gather experience and empirical evidence about
the pros and cons of each in a variety of concrete scenarios.

\subsection{Typing, conversion and bidirectional elaboration}

As explained in \cref{sec:grad-simple},
in a gradual language, whenever we reclaim precision, we might be wrong and need to fail in order to preserve \kl{safety}.
%
In a simply-typed setting, the standard approach is to define typing on a
gradual source language, and then to translate terms via a type-directed elaboration
to a target \emph{cast calculus}, \ie a language with explicit runtime type
checks.
This elaboration inserts casts, needed for a well-behaved reduction \sidecite{Siek2006}.
For instance, in a call-by-value language, the upcast (loss of precision)
$\castrev{10}{\Nat}{\?}$ is considered a (tagged) value,
and the downcast (gain of precision) $\castrev{v}{\?}{\Nat}$ reduces successfully
if $v$ is such a tagged natural number, or to an error otherwise.

\AP We follow a similar approach for \kl{GCIC}, which is
elaborated in a type-directed manner to a second calculus,
named \reintro{CastCIC} (\cref{sec:cast-calculus}).
The interplay between typing and cast insertion is however more subtle in the
context of a dependent type theory. Because typing needs computation, and
reduction is only meaningful in the target language, \kl{CastCIC} is used
\emph{as part of the elaboration} in order to compare types (\cref{sec:elaboration}).
This means that \kl{GCIC} has no typing on its own, independent of its
elaboration to \kl{CastCIC}.%
\sidenote{This is similar to what happens in practice in proof assistants such as \kl{Coq}
\cite[Core language]{CoqManual}, where terms input by the user in the \kl{Gallina} language
are first elaborated in order to add implicit arguments, coercions, etc.
The computation steps required by conversion are
performed on the elaborated terms, never on the raw input syntax.}%
\margincite{CoqManual}

In order to satisfy \kl{conservativity} with respect to \kl{CIC}, ascriptions in \kl{GCIC}
are required to satisfy \kl(grad){consistency}. For instance, $\asc{\asc{\true}{\?}}{\Nat}$ is well-typed by \kl(grad){consistency} – used twice –, but $\asc{\true}{\Nat}$ is ill-typed.
Such ascriptions in \kl{CastCIC} are realized by casts.
For instance $\asc{\asc{\z}{\?}}{\Bool}$ in \kl{GCIC} elaborates
– up to desugaring and reduction – to
$\castrev{\castrev{\z}{\Nat}{\?[\uni]}}{\?[\uni]}{\Bool}$ in \kl{CastCIC}.
A major difference between ascriptions in \kl{GCIC} and casts in \kl{CastCIC} is
that casts are not required to satisfy \kl(grad){consistency}: a cast between any
two types is well-typed, although of course it might produce an
error.

This is where the bidirectional structure is crucial.
First, it is required in order to tame the non-transitive \kl(grad){consistency} relation.
Indeed, in the previous example of $\asc{\true}{\Nat}$, if one kept a free-standing rule like
\ruleref{rule:cic-conv} and simply replaced \kl{conversion} by \kl(grad){consistency}, one could
use the rule twice, through $\?$, and the term would be well-typed.
But \kl(grad){consistency} demands that only terms with explicitly-ascribed
imprecision enjoy its flexibility.
This observation is standard in the gradual typing literature
\sidecite{Siek2006,Siek2007,Garcia2016}, but becomes even more crucial in the context of
gradual dependent types \sidecite{Eremondi2019}.
Moreover, the bidirectional structure is very suited to the description of
a type-based elaboration, and directly translates to a deterministic typing/elaboration
algorithm for \kl{GCIC}.

\subsection{Precisions and properties}
\label{sec:precision-graduality}

As explained earlier (\cref{sec:graduality}), we need three different notions of
precision to deal with \kl{SGG} and \kl{graduality}.

\AP At the source level – \kl{GCIC} –,
we introduce a notion of \reintro{syntactic precision}, that captures the
intuition of a more imprecise term as "the same term with sub-terms and/or
type annotations replaced by $\?$", and is defined without any assumption of typing.
In \kl{CastCIC}, we define a notion of \reintro{structural precision},
which is mostly syntactic except that, in order to account for cast insertion during elaboration, it tolerates precision-preserving casts.
For instance, $\castrev{t}{A}{A}$ is related to $t$ by \kl{structural precision}.

Armed with these two notions of precision, we prove
% We prove that \GCIC satisfies static graduality.\km{forward ref?}
% However, because \GCIC does not have a type system, we rather prove
\kl{elaboration graduality} (\cref{thm:static-graduality}), which is
the equivalent of the \kl{static gradual guarantee} in our setting:
if a term $t$ of \kl{GCIC} elaborates to a term $t'$ of \kl{CastCIC},
then a term $u$ less syntactically precise than $t$ in \kl{GCIC} elaborates to
a term $u'$ less structurally precise than $t'$ in \kl{CCIC}.
%
Because \kl{DGG} is about the behaviour of terms during reduction,
it is technically stated and proven for \kl{CastCIC}.
We show in \cref{sec:gcic-theorems} that \kl{DGG} can be proven
for \kl{CastCIC} – in its variants \kl{CCICP} and \kl{CCICs} – on \kl{structural
precision}.

\AP However, as explained in \cref{sec:grad-simple}, we cannot expect to prove \kl{graduality}
for these \kl{CastCIC} variants with respect to \kl{structural precision} directly.
In order to overcome this problem, and to justify the design of \kl{CastCIC},
we build two kinds of models for \kl{CastCIC}. The first%
\sidenote{That we call the \reintro{discrete model}.} is a syntactic model
\sidecite{Boulier2018} – akin to a program translation or a compilation phase –,
and is used to justify the reduction rules and prove that they are terminating.
The second%
\sidenote{That we call the \reintro{monotone model}}
endows types with the structure of an ordered set, or poset. This makes it
possible to reason about the semantic notion of \reintro{propositional
precision} and prove that it gives rise to \kl{embedding-projection pairs},
thereby establishing \kl{graduality}.
%
% The monotone model only works for a normalizing gradual type theory,
% thus we then establish \pgrad for \CCICP using a variant of the
% monotone model based on Scott's
% model~\cite{scott76} of the untyped $\lambda$-calculus using $\omega$-complete
% partial orders (\cref{sec:grad-non-term}).
These models are described in \cref{sec:realizing-cast-calculus}.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Latex stylesheet for influence diagrams
%
% Version: 2021-01-11.3
%
% Copyright 2020 Tom Everitt
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
%     http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.

\documentclass{article}
\usepackage[decisionutilitycolor]{influence-diagrams}
\NewDocumentCommand\voci{O{}D<>{1}m}{\incentive{#3}{incentive, gray,#1}{#2}}

\begin{document}

\section{Simple Diagram}

\begin{influence-diagram}
      \node (A) [decision] {$A_1$};
      \node (X) [right = of A] {$X$};
      \node (U) [right = of X, utility] {$R_1$};

      \edge {A} {X};
      \edge {X} {U};
\end{influence-diagram}

\section{MDP}

\begin{influence-diagram}

  \node (S1) {$S_1$};
  \node (S2) [right = 2 of S1] {$S_2$};
  \node (S3) [right = 2 of S2] {$S_3$};

  \node (R1) [below = of S1, utility] {$R_1$};
  \node (R2) [below = of S2, utility] {$R_2$};
  \node (R3) [below = of S3, utility] {$R_3$};

  \node (A1) at ($(R1)!0.5!(R2)$) [decision] {$A_1$};
  \node (A2) at ($(R2)!0.5!(R3)$) [decision] {$A_2$};

  \node (thetaT) [above = of S1] {$\Theta_T$};
  \node (thetaR) [below = of R1] {$\Theta_R$};

  \edge {S1, thetaR} {R1};
  \edge {S2, thetaR} {R2};
  \edge {S3}         {R3};

  \edge {thetaT}         {S1};
  \edge {thetaT, A1, S1} {S2};
  \edge {thetaT, A2, S2} {S3};

  \edge[information] {S1, R1} {A1};
  \edge[information] {S2, R2} {A2};

  \path (thetaR) edge[->, bend right=10] (R3);

  \node (help) [minimum size=0mm, node distance=2mm, below left = of R1, draw=none] {};

  \draw[information]
  (S1) edge[ in=135, out=-120] (help.center)
  (help.center) edge[->, out=-45, in=-150] (A2);

\end{influence-diagram}
\vspace{1cm}

\begin{influence-diagram}
  \node (S1) {$S_1$};
  \node (S2) [right = 2 of S1] {$S_2$};
  \node (S3) [right = 2 of S2] {$S_3$};

  \node (R1) [below = of S1, utility] {$R_1$};
  \node (R2) [below = of S2, utility] {$R_2$};
  \node (R3) [below = of S3, utility] {$R_3$};

  \node (A1) at ($(R1)!0.5!(R2)$) [decision] {$A_1$};
  \node (A2) at ($(R2)!0.5!(R3)$) [decision] {$A_2$};

  \node (thetaT) [above = of S1] {$\Theta_T$};
  \node (thetaR) [below = of R1] {$\Theta_R$};

  \edge {S1, thetaR} {R1};
  \edge {S2, thetaR} {R2};
  \edge {S3}         {R3};

  \edge {thetaT}         {S1};
  \edge {thetaT, A1, S1} {S2};
  \edge {thetaT, A2, S2} {S3};

  \edge[information] {S1, R1} {A1};
  \edge[information] {S2, R2} {A2};

  \path (thetaR) edge[->, bend right=10] (R3);

  \node (help) [node distance=4mm, below left = of R1, phantom] {};

  % This bent edge sticks an invisible control point out too far and messes
  % with the bounding box so have the bounding box ignore it
  \begin{pgfinterruptboundingbox}
    \draw[information]
    (S1) edge[in=135, out=-120]
    % Bounding box helper
    % Place at the bend point or wherever the line is furthest past the
    % bounding box
    % Must be manually positioned using pos=(fraction of path length)
    % since the bend point is not necessary half way along the path.
    node[phantom, pos=0.75] (bbhelper) {}
    (help)
    (help) edge[->, out=-45, in=-150] (A2);
  \end{pgfinterruptboundingbox}

  % Place another node at the bbhelper; this time included by the bounding box
  % Manually adjust minimum size to compensate for any slight misalignment
  % with the bend point of the path and to fully include the path line width.
  \node[draw=none, minimum size=1pt, inner sep=0] at (bbhelper) {};

  \draw[black] (current bounding box.south west) rectangle (current bounding box.north east);

\end{influence-diagram}

\section{Legend}

\begin{influence-diagram}

    \cidlegend{
      \legendrow{}{chance node} \\
      \legendrow{decision}{decision node}\\
      \legendrow{utility}{utility node}\\
      \legendrow[causal]{draw=none}{causal link} \\
      \legendrow[information]{draw=none}{information link} \\
      \legendrow{value of information}{Value of Information}\\
      \legendrow{value of control}{Value of Control} \\
      \legendrow{response incentive}{Response Incentive}\\
      \legendrow{feasible control incentive}{Control Incentive}\\
    }

    \path (causal.west) edge[->] (causal.east);
    \path (information.west) edge[->, information] (information.east);

\end{influence-diagram}

\section{Incentives}

\begin{influence-diagram}
  \node (S1) {$S_1$};

  \voi<1>{S1}
  \ri<2>{S1}
  \fci<3>{S1}
  \voc<4>{S1}

  % newly defined
  \voci<5>{S1}
\end{influence-diagram}

\begin{influence-diagram}
  %\setcompactsize
  \node (A) [decision] {$A_1$};
  \node (X) [right = of A] {$X$};
  \node (U) [right = of X, utility] {$R_1$};

  \edge {A} {X};
  \edge {X} {U};

  \fci{X}
  \fci[rectangle]{A}
  \fci[diamond]<3>{U}
\end{influence-diagram}

\section{Multi-agent CIDs}

% MACID
\begin{influence-diagram}

  \node (help) [draw=none] {};
  \node (P1) [above = of help, decision, player1] {$D_1$};
  \node (P2) [below = of help, decision, player2] {$D_2$};
  \node (U1) [right = of help, utility, player1] {$U_1$};
  \node (U2) [left = of help, utility, player2] {$U_2$};
  \node (C) at (U2|-P1) {$C$};

  \edge[information] {C} {P1};
  \edge[information] {P1} {P2};
  \edge {P1,P2} {U1};
  \edge {C,P1,P2} {U2};
\end{influence-diagram}
% Relevance graph
\begin{influence-diagram}

  \node (D1) [relevanceb] {$D_1$};
  \node (D2) [below = of D1, relevanceb] {$D_2$};

  \path (D1) edge[->, bend right=15] (D2);
  \path (D2) edge[->, bend right=15] (D1);

\end{influence-diagram}

\section{Rectangular}

\begin{influence-diagram}
  \setrectangularnodes

  \node (R) [] {Race};
  \node (S) [below= of R] {High school};
  \node (E) [below= of S] {Education};
  \node (Gr) [below=of E] {Grade};
  \node (D) [right=of S,decision] {Predicted grade};
  \node (Ge) [above=of D] {Gender};
  \node (U) [utility] at (D|-Gr) {Accuracy};

  \edge {R} {S};
  \edge {S} {E};
  \edge[information] {S,Ge} {D};
  \edge {E} {Gr};
  \edge {D,Gr} {U};

%  \node [inner sep=4mm, fit = (E), feasible control incentive] {};

  \voi{S}
  \voi{E}
  \voi{Gr}
  \ri{R}
  \ri<2>{S}
\end{influence-diagram}

\section{Compact}

\begin{influence-diagram}
  \setcompactsize
  \node (A) [decision] {$A_1$};
  \node (X) [right = of A] {$X$};
  \node (U) [right = of X, utility] {$R_1$};

  \edge {A} {X};
  \edge {X} {U};

  \fci{X}
  \fci[rectangle]{A}
  \fci[diamond]<5>{U}
\end{influence-diagram}

\begin{influence-diagram}
  \setrectangularnodes
  \setcompactsize

  \node (R) [] {Race};
  \node (S) [below= of R] {High school};
  \node (E) [below= of S] {Education};
  \node (Gr) [below=of E] {Grade};
  \node (D) [right=of S,decision] {Predicted grade};
  \node (Ge) [above=of D] {Gender};
  \node (U) [utility] at (D|-Gr) {Accuracy};

  \edge {R} {S};
  \edge {S} {E};
  \edge[information] {S,Ge} {D};
  \edge {E} {Gr};
  \edge {D,Gr} {U};

  \voi{S}
  \voi{E}
  \voi{Gr}
  \ri{R}
  \ri<2>{S}
\end{influence-diagram}

\section{Putting it all together}

\begin{influence-diagram}

  \node (S1) {$S_1$};
  \node (S2) [right = 2 of S1] {$S_2$};
  \node (S3) [right = 2 of S2] {$S_3$};

  \node (R1) [below = of S1, utility] {$R_1$};
  \node (R2) [below = of S2, utility] {$R_2$};
  \node (R3) [below = of S3, utility] {$R_3$};

  \node (A1) at ($(R1)!0.5!(R2)$) [decision] {$A_1$};
  \node (A2) at ($(R2)!0.5!(R3)$) [decision] {$A_2$};

  \node (thetaR) [below = of R1] {$\Theta_R$};

  \edge {S1, thetaR} {R1};
  \edge {S2, thetaR} {R2};
  \edge {S3}         {R3};

  \edge {A1, S1} {S2};
  \edge {A2, S2} {S3};

  \edge[information] {S1, R1} {A1};
  \edge[information] {S2, R2} {A2};

  \path (thetaR) edge[->, bend right=10] (R3);

  \node (help) [minimum size=0mm, node distance=2mm, below left = of R1, draw=none] {};

  \draw[information]
  (S1) edge[ in=135, out=-120] (help.center)
  (help.center) edge[->, out=-45, in=-150] (A2);

  \fci{S2}
  \fci{S3}
  \ri{thetaR}

  \cidlegend[right=of S3.north east, anchor=north west]{
    \legendrow{}{chance node} \\
    \legendrow{decision}{decision node}\\
    \legendrow{utility}{utility node}\\
    \legendrow[causal]{draw=none}{causal link} \\
    \legendrow[information]{draw=none}{information link} \\
    \legendrow{response incentive}{Response Incentive}\\
    \legendrow{feasible control incentive}{Control Incentive}\\
  }

  \path (causal.west) edge[->] (causal.east);
  \path (information.west) edge[->, information] (information.east);

\end{influence-diagram}

\end{document}


\documentclass[12pt]{article}
\usepackage[margin=1in]{geometry}
\usepackage[T1]{fontenc}
\usepackage[USenglish]{babel}
\usepackage[nodayofweek,level]{datetime}
\usepackage{amsfonts}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{tikz}
\usetikzlibrary{intersections,arrows.meta}
\usepackage{pgfplots}
\usepackage[scr]{rsfso}
\usepackage{array}

\usepackage{tikz,pgfplots}

\pgfplotsset{compat=1.10}
\usepgfplotslibrary{fillbetween}
% Change due date below
\newcommand{\dueDate}{\formatdate{13}{10}{2017}}

\begin{document}

%\selectlanguage{USenglish}

\title{Homework: Week 2}
\author{Joseph Ismailyan}
\date{}
\maketitle
\begin{flushleft}
Math 100 \\
Due: \dueDate \\
Professor Boltje \\
MWF 9:20a-10:25a
\end{flushleft}

% Insert first section here
% Minipage creates the columns
\begin{minipage}[t]{0.40\textwidth}
\section*{Section 1.6}

\subsection*{6.}
\begin{tikzpicture}
\begin{axis}[
xmin=-2, xmax=2,
ymin=-1, ymax=2,
axis lines=center,
axis on top=true,
domain=0:1,
xlabel={$x$},
ylabel={$y$},
axis line style={latex-latex}
]
\addplot [
name path=A,
domain=-1.4:1.4,
samples=100,
color=black,
%dashed,
<->,
]
{x^2}
node [pos=0.85, below right]{$ y\geq x^2 $};
\addplot [name path=B,opacity=0,domain=-1.4:1.4] {1.96};
\addplot[gray!50] fill between[of=A and B];
\end{axis}
\end{tikzpicture}
\bigskip

\end{minipage}
% Creates verticle line
\hfill\vline\hfill
\begin{minipage}[t]{0.45\textwidth}

\section*{Section 1.7}

\begin{tikzpicture}[fill=gray!50]
% outline
\fill (-2,-2) rectangle (3,2);
\fill[white] (0,0) circle (1);
\fill[white] (1,0) circle (1);
\draw (0,0) circle (1) (0,1)  node [text=black,above] {$A$}
(1,0) circle (1) (1,1)  node [text=black,above] {$B$}
(-2,-2) rectangle (3,2) node [text=black,above left] {$U$};
\node[anchor=south] at (current bounding box.north) {$ \overline{A \cup B}$};
\end{tikzpicture}

\bigskip

\begin{tikzpicture}[fill=gray!50]
% outline
\fill (-2,-2) rectangle (3,2);
\fill[white] (0,0) circle (1);
\fill[white] (1,0) circle (1);
\draw (0,0) circle (1) (0,1)  node [text=black,above] {$A$}
(1,0) circle (1) (1,1)  node [text=black,above] {$B$}
(-2,-2) rectangle (3,2) node [text=black,above left] {$U$};
\node[anchor=south] at (current bounding box.north) {$\overline{A} \cap \overline{B}$};
\end{tikzpicture}
\\

Answer: From the two diagrams above, we can see that the sets are equal.
\end{minipage}
\pagebreak

\begin{minipage}[t]{0.40\textwidth}
	\section*{Section 1.8}
\subsection*{6(a).}
Answer:
$\bigcup\limits_{ i \in \mathbb{N}}[0,i+1]=[0,\infty)$

\subsection*{6(b).}
Answer:
$\bigcap\limits_{ i \in \mathbb{N}}[0,i+1]=[0,2]$

\section*{Section 2.1}
\subsection*{6.}
Question: Some sets are finite.
\\\\
Answer: It is statement because it can be proven definitely true or false.

\subsection*{14.}
Question: Call me Ishmael.
\\\\
Answer: It is a sentence because it isn't a mathematical expression.

\section*{Section 2.2}
\subsection*{8.}
Question: At least one of the
numbers $ x $ and $ y $ equals $ 0 $.
\\
$ P: x $ is equal to 0.\\
$ Q: x $ is equal to 0.\\\\
Answer: $ P\lor Q $

\end{minipage}
% Creates verticle line
\hfill\vline\hfill
\begin{minipage}[t]{0.45\textwidth}
\section*{Section 2.3}
\subsection*{2.}
Problem: Convert the following sentences to be in the form $ P \implies Q $
$ P: $ A function is differentiable.\\
$ Q: $ A function is continuous.\\\\
Answer: $ P \implies Q $
\section*{Section 2.4}
\subsection*{4.}
Problem: Convert to the form "$ P $ if and only if $ Q $". \\
$ P: a \in \mathbb{Q}$\\
$ Q: 5a \in \mathbb{Q}$\\\\
Answer: $ P \Leftrightarrow Q $\\
$ a \in \mathbb{Q} $ if and only if $ 5a \in \mathbb{Q} $

\section*{Section 2.5}
\subsection*{4.}
Problem: Write a truth table for the logical problem:
$ \sim (P \lor Q) \lor \sim(P) $\\
\[
\begin{array}{c|c|c|c|c}
P & Q &  \sim(P \lor Q) &  \sim(P)  & \sim(P \lor Q) \lor \sim(P)\\
\hline
T & T & F & F & F\\
T & F & F & F & F\\
F & T & F & T & T\\
F & F & T & T & T
\end{array}
\]

\end{minipage}
\pagebreak

\begin{minipage}[t]{0.40\textwidth}
\section*{Section 2.5 cont.}
\subsection*{8.}
Problem: Write a truth table for the logical problem:
$ P \lor (Q \lor \sim R)$\\
\[
\begin{array}{c|c|c|c|c}
P & Q & R &(Q \lor \sim R) & P \lor (Q \lor \sim R)\\
\hline
T & T & T & T & T\\
T & T & F & T & T\\
T & F & T & F & T\\
T & F & F & T & T\\
F & T & T & T & T\\
F & T & F & T & T\\
F & F & T & F & F\\
F & F & F & T & T
\end{array}
\]

\subsection*{10.}
Problem: Suppose the statement $ ((P \land Q) \lor R) \implies (R \lor S)$\\
is false. Find the truth values of $ P,Q,R $ and $ S. $\\\\
Asnwer: Suppose $ A $ and $ B $ are statements. The only way that $(A \implies B)=False$ is if $ A=True $ and $ B=False $. Therefore $ ((P \land Q) \lor R)$ must be $ True $ and $ (R \lor S) $ must be $ False $. For $ (R \lor S) $ to be $ False $, both $ R $ and $ S $ must be $ False $. Since $ R $ is false, the statement $ (P \land Q) \lor R) $ relies on $ (P \land Q) $ to be true so both $ P $ and $ Q $ must be true. In conclusion:
$$
\begin{array}{c|c|c|c}
	P & Q & R & S\\
	\hline
	T & T & F & F\\
\end{array}
$$

\end{minipage}
% Creates verticle line
\hfill\vline\hfill
\begin{minipage}[t]{0.45\textwidth}
\section*{Section 2.6}
\subsection*{2.}
Problem: Show that the following statements are logically equivalent.\\
$ a $: $ P \lor (Q \land R) $\\
$ b $: $ (P \lor Q) \land (P \lor R) $ \\
\[
\begin{array}{c|c|c|c|c}
P & Q & R &(Q \land R) & P \lor (Q \land R)\\
\hline
T & T & T & T & T\\
T & T & F & F & T\\
T & F & T & F & T\\
T & F & F & F & T\\
F & T & T & T & T\\
F & T & F & F & F\\
F & F & T & F & F\\
F & F & F & F & F
\end{array}
\]
\[
\begin{array}{c|c|c|c|c|c}
P & Q & R &(P \lor Q) & (P \lor R) & (P \lor Q) \land (P \lor R)\\
\hline
T & T & T & T & T & T\\
T & T & F & T & T & T\\
T & F & T & T & T & T\\
T & F & F & T & T & T\\
F & T & T & T & T & T\\
F & T & F & T & F & F\\
F & F & T & F & T & F\\
F & F & F & F & F & F
\end{array}
\]
\subsection*{10.}
Decide whether the following statements are logically equivalent:\\
$ a.\quad(P \implies Q) \lor R $\\
$ b. \sim((P \land \sim Q) \land \sim R) $\\
$1) \quad (P \implies Q) \lor R $ = $ (\sim P \lor Q) \lor R$ \\by definition of implication\\
$ 2) \quad (\sim P \lor Q) \lor R =  \enspace \sim((\sim P \lor Q) \lor R)$\\
by DeMorgan's Laws\\
$ 3) \sim((\sim P \lor Q) \lor R) = \sim(\sim P \lor Q) \land \sim R $\\
by DeMorgan's Laws\\
$ 4) \sim(\sim P \lor Q) \land \sim R = (P \land \sim Q) \land \sim R$\\
by DeMorgan's Laws\\
$ 5)\quad (P \land \sim Q) \land \sim R =\\ \sim ((P \land \sim Q) \land \sim R) = b$\\\\
$\therefore a \equiv b $, they're logically equivalent.
\end{minipage}

\end{document}


\subsection{Slidding ?}
It consists in finding $\alpha >0$ and $R \in \partial K_{\mu}$ such that $-\alpha \left(\begin{array}{l} 0\\ R_T\end{array}\right)=MR+q$. That is :
  \begin{equation}
\label{eq_quartic1}
\left[\begin{array}{c}
M+ \left(\begin{array}{ccc} 0&0&0\\ 0&\alpha&0 \\ 0&0&\alpha \end{array}\right)
\end{array}\right]R+q=0
\end{equation}

  \subsubsection{$R_T$ is on a conic}
  The first line of the system~\ref{eq_quartic1} and the $R \in \partial K_{\mu}$ is the intersection between a plan and a cone in $\mathbb{R}^3$, endeed:
  \begin{equation}
\label{eq_quartic2}
\begin{array}{l}
 \mu R_N =  \parallel R_T \parallel  \\
\frac{M_{11}}{\mu} \parallel R_T \parallel = -q_1-M_{12}R_{T1}-M_{13}R_{T2}
\end{array}
\end{equation}
That is:
\begin{equation}
\label{eq_quartic2}
\begin{array}{l}
\mu^2 R_N^2 =  (R_{T1}^2 +R_{T1}^2)  \\
\frac{M_{11}^2}{\mu^2} (R_{T1}^2 +R_{T1}^2)=(-q_1-M_{12}R_{T1}-M_{13}R_{T2})^2
\end{array}
\end{equation}
That means that $R_T$ is contained in a conic,  focus and directrice are:
\begin{equation}
\label{eq_quartic3}
\begin{array}{l}
\mathcal{D} : q_1+M_{12}R_{T1}+M_{13}R_{T2} =0  \\
focus : \mathcal{O}\\
\frac{M_{11}^2}{\mu^2}  Dist(\mathcal{O}, R_T) ^2=Dist(\mathcal{D},R_T)^2 (M_{12}^2+M_{13}^2)\\
\frac{Dist(\mathcal{O}, R_T)}{Dist(\mathcal{D},R_T)}=\frac{\mu\sqrt{(M_{12}^2+M_{13}^2)}}{M_{11} }=e
\end{array}
\end{equation}
The parametric equation is:
\begin{equation}
\label{eq_quartic4}
\begin{array}{l}
R_{T1}=r cos(\theta )\\
R_{T2}=r sin(\theta )\\
r=\frac{p}{1+ecos(\theta - \phi)}
\end{array}
\end{equation}
With $p$ an simple expression of $M_{11},M_{12},M_{13}$, and $\phi$ a constant angle between $\mathcal{D}$ and $(O,R_{T1})$
\subsubsection{The two last line of the system~\ref{eq_quartic1}}
\begin{equation}
\label{eq_quartic5}
\frac{\parallel R_T \parallel}{\mu} \tilde M_{1.} +\left(\tilde M+\left(\begin{array}{cc} \alpha&0 \\ 0&\alpha \end{array}\right)\right)R_T+\tilde q=0
\end{equation}
$\tilde M$ is symetric, so it exists a unitary matrix $V$ such that $V \tilde M V^T = \left(\begin{array}{cc} d_1&0 \\ 0&d_2 \end{array}\right)$.  One can get:
\begin{equation}
\label{eq_quartic6}
\frac{\parallel R_T \parallel}{\mu} V \tilde M_{1.} +V \left(\tilde M+\left(\begin{array}{cc} \alpha&0 \\ 0&\alpha \end{array}\right)\right)V^TVR_T+V\tilde q=0
\end{equation}
Rename:
\begin{equation}
\label{eq_quartic7}
  \frac{\parallel \bar R_T \parallel}{\mu} \bar M_{1.} +\left(\begin{array}{cc} d_1+\alpha&0 \\ 0&d_2+\alpha \end{array}\right)\overline R_T+\bar q=0
  \end{equation}
In the plan, either $V$ is a rotation or a symetrie. So $ \bar R_T=VR_T$ is a conic with the same focus and a rotated directrice, it means that it exists $\phi_1$ such that :

\begin{equation}
\label{eq_quartic8}
\begin{array}{l}
\bar R_{T1}=r cos(\theta )\\
\bar R_{T2}=r sin(\theta )\\
r=\frac{p}{1+ecos(\theta - \phi_1)}
\end{array}
\end{equation}
The equation~\ref{eq_quartic7} is :
\begin{equation}
\label{eq_quartic9}
\begin{array}{l}
  (d_1+\alpha)\bar R_{T1}=-\bar q_1+a_1 \parallel R_T \parallel\\
(d_2+\alpha)\bar R_{T2}=-\bar q_2+a_2 \parallel R_T \parallel
\end{array}
\end{equation}
The case ($\bar R_{T1} = 0$ or  $\bar R_{T2} = 0$) has to be examine. We try to eliminate $alpha$:
\begin{equation}
\label{eq_quartic10}
  \begin{array}{l}
    d_1 \bar R_{T1} \bar R_{T2}+\alpha \bar R_{T1} \bar R_{T2} =-\bar q_1\bar R_{T2}+a_1 \bar R_{T2} \parallel R_T \parallel\\
d_2 \bar R_{T1} \bar R_{T2}+\alpha \bar R_{T1} \bar R_{T2} =-\bar q_2\bar R_{T1}+a_2 \bar R_{T1} \parallel R_T \parallel
\end{array}
\end{equation}
that leads to:
\begin{equation}
\label{eq_quartic10}
  (d_1-d_2) \bar R_{T1} \bar R_{T2}=-\bar q_1\bar R_{T2}+\bar q_2\bar R_{T1}+(a_1 \bar R_{T2}-a_2 \bar R_{T1}) \parallel R_T \parallel\\
\end{equation}
The parametric expression of $\bar R_T$ leads to:
\begin{equation}
\label{eq_quartic11}
\begin{array}{l}
  (d_1-d_2)r^2cos(\theta )sin(\theta )=-\bar q_1rsin(\theta )+\bar q_2rcos(\theta )+r(a_1 rsin(\theta )-a_2 rcos(\theta )) \\
  \textrm{ie:}(d_1-d_2)rcos(\theta )sin(\theta )=-\bar q_1sin(\theta )+\bar q_2cos(\theta )+r(a_1 sin(\theta )-a_2 cos(\theta ))\\
  \end{array}
\end{equation}
with the expression of r:
\begin{equation}
\label{eq_quartic12}
\begin{array}{l}
(d_1-d_2)\frac{p}{1+ecos(\theta - \phi_1)}cos(\theta )sin(\theta )=\\-\bar q_1sin(\theta )+\bar q_2cos(\theta )+\frac{p}{1+ecos(\theta - \phi_1)}(a_1  sin(\theta )-a_2 cos(\theta ))\\\\
\textrm{ie:}(d_1-d_2)pcos(\theta )sin(\theta )=\\(1+ecos(\theta - \phi_1))(-\bar q_1sin(\theta )+\bar q_2cos(\theta ))+p(a_1  sin(\theta )-a_2 cos(\theta ))\\\\
\textrm{ie:}(d_1-d_2)pcos(\theta )sin(\theta )=\\(1+e(cos(\theta)cos(\phi_1)+sin(\theta)sin(\phi_1)))(-\bar q_1sin(\theta )+\bar q_2cos(\theta ))+p(a_1  sin(\theta )-a_2 cos(\theta ))\\\\
\textrm{ie:}(d_1-d_2)pcos(\theta )sin(\theta )+\\(1+ecos(\theta)cos(\phi_1)+esin(\theta)sin(\phi_1))(\bar q_1sin(\theta )-\bar q_2cos(\theta ))+p(-a_1  sin(\theta )+a_2 cos(\theta ))=0
 \end{array}
\end{equation}
rename :
\begin{equation}
\label{eq_quartic13}
\begin{array}{l}
Acos(\theta )^2+Bsin(\theta)^2+Csin(\theta )cos(\theta )+Dsin(\theta )+Ecos(\theta )=0
 \end{array}
\end{equation}
with
\begin{equation}
\label{eq_quartic12}
\begin{array}{l}
A=- e\bar q_2cos(\phi_1)\\
B=e \bar q_1sin(\phi_1)\\
C=(d_1-d_2)p+ecos(\phi_1)\bar q_1-esin(\phi_1)\bar q_2\\
D=\bar q_1-pa_1\\
E=-\bar q_2+pa_2\\
\end{array}
\end{equation}
rename :
Using the following set of unknown :
\begin{equation}
\label{eq_quartic14}
\begin{array}{l}
t=tan(\theta /2)\\
sin(\theta )=\frac{2t}{1+t^2}\\
cos(\theta )=\frac{1-t^2}{1+t^2}
 \end{array}
\end{equation}
leads to:
\begin{equation}
\label{eq_quartic13}
\begin{array}{l}
  A\frac{(1-t^2)^2}{1+t^2} +B\frac{4t^2}{1+t^2}+ C\frac{2t(1-t^2)}{1+t^2}+D2t+E(1-t^2)=0\\
\textrm{ie:}A(1-t^2)^2 + 4Bt^2+C2t(1-t^2)+2Dt(1+t^2)+E(1-t^2)(1+t^2)=0\\\\
\textrm{ie:}P_4=A-E\qquad P_3=-2C+2D \qquad P_2=4B-2A \qquad P_1=2C+2D \qquad P_0=A+E
 \end{array}
\end{equation}
Finally, we get 4 possible values for $R_T$, checking the sign of $\alpha$ and $R_N$ selects the solutions.

\subsubsection{case $R_{T12}=0$}
From~\ref{eq_quartic9}, $R_{T1}$ leads to:
\begin{equation}
\label{eq_quartic14}
\begin{array}{l}
  \parallel R_T \parallel=|\bar R_{T2}|=\frac{\bar q_1}{a_1}\\\\
  \bar R_T=\left(\begin{array}{c} 0 \\ \pm \frac{\bar q_1}{a_1} \end{array}\right)
 \end{array}
\end{equation}

From~\ref{eq_quartic9}, $R_{T2}$ leads to:
\begin{equation}
\label{eq_quartic14}
\begin{array}{l}
  \parallel R_T \parallel=|\bar R_{T1}|=\frac{\bar q_2}{a_2}\\\\
  \bar R_T=\left(\begin{array}{c}  \pm \frac{\bar q_2}{a_2} \\ 0 \end{array}\right)
 \end{array}
\end{equation}

From $\bar R_T$, we have to check the coherence with the equation~\ref{eq_quartic8}. If it is on the conic,  we compute R, and the sign condition of the equation~\ref{eq_quartic1} must be check.