\section{Design Entry Using Verilog Code}

\noindent
As a design example, we will use the two-way light controller circuit shown in
Figure~\ref{fig:11}. The circuit can be used to control a single light from either of the
two switches, $x_1$ and $x_2$, where a closed switch corresponds to the logic value 1.
The truth table for the circuit is also given in the figure. Note that
this is just the Exclusive-OR function of the inputs $x_1$ and $x_2$,
but we will specify it using the gates shown.

\begin{figure}[H]
   \begin{center}
      \includegraphics[scale=1]{figures/figure11.png}
   \caption{The light controller circuit.}
	 \label{fig:11}
	 \end{center}
\end{figure}

The required circuit is described by the Verilog code in Figure~\ref{fig:12}.
Note that the Verilog module is called {\it light} to match the name given in
Figure~\ref{fig:4}, which was specified when the project was created.
This code can be typed into a file by using any text editor
that stores ASCII files, or by using the Quartus Prime text editing facilities.
While the file can be given any name, it is a common designers' practice to
use the same name as the name of the top-level Verilog module.
The file name must include the extension $v$, which indicates a Verilog
file. So, we will use the name {\it light.v}.

\lstset{language=Verilog}
\begin{figure}[H]
\begin{center}
\begin{lstlisting}
module light (x1, x2, f);
	input x1, x2;
	output f;
	assign f = (x1 & ~x2)|(~x1 & x2);
endmodule
\end{lstlisting}
\end{center}
\vspace{-0.33in}
	\caption{Verilog code for the circuit in Figure 11.}
	\label{fig:12}
\end{figure}

\subsection{Using the Quartus\textsuperscript{\textregistered}	 Prime Text Editor}

\noindent
This section shows how to use the Quartus Prime Text Editor.
You can skip this section if you prefer to use some other text editor
to create the Verilog source code file, which we will name {\it light.v}.

Select {\sf File $>$ New} to get the window in Figure~\ref{fig:13},
choose {\sf Verilog HDL File}, and click {\sf OK}.
This opens the Text Editor window.
The first step is to specify a name
for the file that will be created. Select {\sf File $>$ Save As}
to open the pop-up box depicted in Figure~\ref{fig:14}.
In the box labeled {\sf Save as type} choose {\sf Verilog HDL File}.
In the box labeled {\sf File name} type {\it light}.
Put a checkmark in the box {\sf Add file to current project}.
Click {\sf Save}, which puts the file into the directory
{\it introtutorial} and leads to the Text Editor window shown
in Figure~\ref{fig:15}.
Enter the Verilog code in Figure~\ref{fig:12}
into the Text Editor and save the file by typing {\sf File $>$ Save}, or by typing
the shortcut {\sf Ctrl-s}.

Most of the commands available in the Text Editor are self-explanatory.
Text is entered at the {\it insertion point}, which is indicated by a thin
vertical line. The insertion point can be moved either by using the
keyboard arrow keys or by using the mouse. Two features of
the Text Editor are especially convenient for typing Verilog
code. First, the editor can display different types of Verilog
statements in different colors, which is the default choice.
Second, the editor can automatically
indent the text on a new line so that it matches the previous line.
Such options can be controlled by the settings
in {\sf Tools $>$ Options $>$ Text Editor}.

\begin{figure}[H]
   \begin{center}
      \includegraphics[scale=0.65]{figures/figure13.png}
   \caption{Choose to prepare a Verilog file.}
	 \label{fig:13}
	 \end{center}
\end{figure}

\begin{figure}[H]
   \begin{center}
      \includegraphics[scale=0.55]{figures/figure14.png}
   \caption{Name the file.}
	 \label{fig:14}
	 \end{center}
\end{figure}

\begin{figure}[H]
   \begin{center}
      \includegraphics[scale=0.40]{figures/figure15.png}
   \caption{Text Editor window.}
	 \label{fig:15}
	 \end{center}
\end{figure}

\subsubsection{Using Verilog Templates}

The syntax of Verilog code is sometimes difficult for a
designer to remember. To help with this issue, the Text Editor
provides a collection of {\it Verilog templates}. The templates provide
examples of various types of Verilog statements, such as a {\bf module}
declaration, an {\bf always} block, and assignment statements.
It is worthwhile to browse through the templates
by selecting {\sf Edit $>$ Insert Template $>$ Verilog HDL} to become
familiar with this resource.

\subsection{Adding Design Files to a Project}

As we indicated when discussing Figure~\ref{fig:6}, you can tell Quartus Prime software
which design files it should use as part of the current project.
To see the list of files already included in the {\it light} project,
select {\sf Assignments $>$ Settings}, which leads to the window in Figure~\ref{fig:16}.
As indicated on the left side of the figure, click on the item {\sf Files}.
An alternative way of making this selection is to choose
{\sf Project $>$ Add/Remove Files in Project}.

If you used the Quartus Prime Text Editor to create the file and checked
the box labeled {\sf Add file to current project},
as described in Section 5.1, then the {\it light.v}
file is already a part of the project and will be listed in
the window in Figure~\ref{fig:16}.
Otherwise, the file must be added to the project.
So, if you did not use the Quartus Prime Text Editor, then place a copy of the
file {\it light.v}, which you created using some other text editor, into
the directory {\it introtutorial}.
To add this file to the project, click on the {\sf ...} button next to the
box labeled {\sf File name} in
Figure~\ref{fig:16} to get the pop-up window in Figure~\ref{fig:17}.
Select the {\it light.v} file and click {\sf Open}.
The selected file is now indicated in the {\sf File name} box in Figure~\ref{fig:16}.
Click {\sf Add} then {\sf OK} to include the {\it light.v} file in the project.
We should mention that in many cases the Quartus Prime software is able to
automatically find the right files to use for each entity
referenced in Verilog code, even if the file has not been
explicitly added to the project. However, for complex projects that
involve many files it is a good design practice to specifically
add the needed files to the project, as described above.

\begin{figure}[H]
   \begin{center}
      \includegraphics[scale=0.55]{figures/figure16.png}
   \caption{Settings window.}
	 \label{fig:16}
	 \end{center}
\end{figure}

\begin{figure}[H]
   \begin{center}
      \includegraphics[scale=0.65]{figures/figure17.png}
   \caption{Select the file.}
	 \label{fig:17}
	 \end{center}
\end{figure}


\subsection{Combining transformation functions}
\label{subsec:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions}

The previous sections discussed the combination of instance models and instance graphs. In this section, the combination of transformation functions between instance models and instance graphs is discussed. This combination is the last key element shown in \cref{fig:transformation_framework:instance_models_and_instance_graphs:structure_instance_models_graphs}. If it is possible to combine $f_A$ and $f_B$ into $f_{A} \sqcup f_{B}$, then it is possible to build transformation functions between instance models and instance graphs iteratively.

Before it is possible to define a definition for the combination of two transformation functions, it is essential to define what functions are considered to be transformation functions.

\begin{defin}[Transformation function from an instance model to an instance graph]
\label{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_model_instance_graph}
Let $f$ be a function from instance models to instance graphs, $Im$ be an instance model and $IG$ the corresponding instance graph. $f$ is a transformation function iff:
\begin{itemize}
    \item $f$ projects $Im$ onto $IG$: $f(Im) = IG$;
    \item After combination with another instance model, $f$ preserves the type graph;
    \item After combination with another instance model, $f$ preserves the nodes:\\$\forall Im_x\!: N_{f(Im)} \subseteq N_{f(\mathrm{combine}(Im, Im_x))}$;
    \item After combination with another instance model, $f$ preserves the edges:\\$\forall Im_x\!: E_{f(Im)} \subseteq E_{f(\mathrm{combine}(Im, Im_x))}$;
    \item For all identities in the projected instance graph, $f$ preserves the value of the identity if the instance model is combined with another instance model:\\$\forall Im_x\!: \forall i \in \mathrm{dom}\ \mathrm{ident}_{f(Tm)}\!: \mathrm{ident}_{f(Im)}(i) = \mathrm{ident}_{f(\mathrm{combine}(Im, Im_x))}(i)$.
\end{itemize}
\isabellelref{ig_combine_mapping_function}{Ecore-GROOVE-Mapping.Instance_Model_Graph_Mapping}
\end{defin}

As expected, a transformation must project some instance model $Im$ to its corresponding instance graph $IG$. Furthermore, it has to preserve properties of the projection, even after $Im$ is combined with some other instance model. The rationale behind these properties is that after combining $Im$ with some other instance model, there must still be a way to transform the elements that originated from $Im$. If that is possible, it is possible to use the transformation function as the basis for the combined transformation function, which can transform the combined instance model to a combined instance graph.

The following definition will describe how two transformation functions from instance models to instance graphs can be combined into a new transformation function, which projects the combination of two instance models onto the combination of the two corresponding instance graphs.

\begin{defin}[Combination of transformation functions from an instance model to an instance graph]
\label{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:combination_transformation_function_instance_model_instance_graph}
Let $f_A$ and $f_B$ be a transformation functions in the sense of \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_model_instance_graph}. $f_A$ projects an instance model $Im_A$ onto instance graph $IG_A$. $f_B$ projects an instance model $Im_B$ onto instance graph $IG_B$. Then the combination of $f_A$ and $f_B$ is defined as:
\begin{align*}
f_{A} \sqcup f_{B}(Im) =\ &\langle&
N =\ &\{n \mid n \in N_{f_{A}(Im)} \land n \in N_{IG_A} \} \cup \{n \mid n \in N_{f_{B}(Im)} \land n \in N_{IG_B} \} \\&&
E =\ &\{e \mid e \in E_{f_{A}(Im)} \land e \in E_{IG_A} \} \cup \{e \mid e \in E_{f_{B}(Im)} \land e \in E_{IG_B} \} \\&&
\mathrm{ident} =\ &\mathrm{ident\_\!mapping}(f_A, IG_A, f_B, IG_B, Im)
\rangle
\end{align*}
In which $\mathrm{ident\_\!mapping}$ is given as part of \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:ident_mapping}
\isabellelref{ig_combine_mapping}{Ecore-GROOVE-Mapping.Instance_Model_Graph_Mapping}
\end{defin}

Like the combination of transformations functions from a type model to a type graph, the combination of transformations functions from an instance model to an instance graph follows the combination of instance graphs closely. The definition is an alternation of \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_graphs:combine}. As shown for type models and type graphs, this is the desired behaviour, as the combination of the transformation functions should be able to transform the combination of two instance models to the combination of the two corresponding instance graphs.

Unsurprisingly, the definition of the identity function of $f_{A} \sqcup f_{B}$ is very similar to \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_graphs:ident_combine}.

\begin{defin}[Combination of the identity function for two transformation functions]
\label{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:ident_mapping}
$\mathrm{ident\_\!mapping}(f_A, IG_A, f_B, IG_B, Im)$ is a partial function on two transformation functions $f_A$ and $f_B$, their corresponding projections $IG_A$ and $IG_B$ and an instance model $Im$ which returns a new function \\$Id \Rightarrow (N_{f_{A} \sqcup f_{B}(Im)} \cap Node_t)$. It is defined as follows:
\begin{multline*}
    \mathrm{ident\_\!combine}(f_A, IG_A, f_B, IG_B, Im, i) = \\
    \begin{cases}
        \mathrm{ident}_{f_A(Im)}(i) & \mathrm{if }\ i \in \{i \mid i \in \mathrm{dom}\ \mathrm{ident}_{f_{A}(Im)} \land i \in \mathrm{dom}\ \mathrm{ident}_{IG_A} \}\ \cap\\&\quad \{i \mid i \in \mathrm{dom}\ \mathrm{ident}_{f_{A}(Im)} \land i \in \mathrm{dom}\ \mathrm{ident}_{IG_A} \} \land \mathrm{ident}_{f_A(Im)}(i) = \mathrm{ident}_{IG_B}(i) \\
        \mathrm{ident}_{f_A(Im)}(i) & \mathrm{if }\ i \in \{i \mid i \in \mathrm{dom}\ \mathrm{ident}_{f_{A}(Im)} \land i \in \mathrm{dom}\ \mathrm{ident}_{IG_A} \}\ \setminus\\&\quad\{i \mid i \in \mathrm{dom}\ \mathrm{ident}_{f_{A}(Im)} \land i \in \mathrm{dom}\ \mathrm{ident}_{IG_A} \} \\
        \mathrm{ident}_{f_B(Im)}(i) & \mathrm{if }\ i \in \{i \mid i \in \mathrm{dom}\ \mathrm{ident}_{f_{A}(Im)} \land i \in \mathrm{dom}\ \mathrm{ident}_{IG_A} \}\ \setminus\\&\quad\{i \mid i \in \mathrm{dom}\ \mathrm{ident}_{f_{A}(Im)} \land i \in \mathrm{dom}\ \mathrm{ident}_{IG_A} \}
    \end{cases}
\end{multline*}
\end{defin}

With these definitions in place, it is possible to provide the necessary theorems for the correctness of the combined function $f_{A} \sqcup f_{B}$.

\begin{thm}[The projection of a combined transformation function from an instance model to an instance graph]
\label{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:ig_combine_mapping_correct}
Let $f_A$ and $f_B$ be a transformation functions in the sense of \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_model_instance_graph}. $f_A$ projects an instance model $Im_A$ onto instance graph $IG_A$. $f_B$ projects an instance model $Im_B$ onto instance graph $IG_B$. Then the combination of $f_A$ and $f_B$, $f_{A} \sqcup f_{B}$ projects $\mathrm{combine}(Im_A, Im_B)$ onto $\mathrm{combine}(IG_A, IG_B)$, so:
\begin{equation*}
    f_{A} \sqcup f_{B}(\mathrm{combine}(Im_A, Im_B)) = \mathrm{combine}(IG_A, IG_B)
\end{equation*}
\isabellelref{ig_combine_mapping_correct}{Ecore-GROOVE-Mapping.Instance_Model_Graph_Mapping}
\end{thm}

\begin{proof}
The corresponding proof follows directly from \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:combination_transformation_function_instance_model_instance_graph} as well as \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_model_instance_graph}. Since the individual transformation functions $f_A$ and $f_B$ preserve the elements of their instance graphs when the instance model is combined with another one, we can establish that the definition of $f_{A} \sqcup f_{B}$ is equal to the definition of $\mathrm{combine}(IG_A, IG_B)$. Therefore, $f_{A} \sqcup f_{B}(\mathrm{combine}(Im_A, Im_B)) = \mathrm{combine}(IG_A, IG_B)$.
\end{proof}

Although the presented theorem is a large step towards being able to build transformation functions from instance models to instance graphs iteratively, there is still one key element missing. It should be formally argued that $f_{A} \sqcup f_{B}$ is once again an transformation function in the sense of \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_model_instance_graph}. If this is formally argued, it becomes possible to easily combine $f_{A} \sqcup f_{B}$ with yet another transformation function. The following theorem states this property.

\begin{thm}[A combined transformation function from an instance model to an instance graph is a transformation function]
\label{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:ig_combine_mapping_function_correct}
Let $f_A$ and $f_B$ be a transformation functions in the sense of \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_model_instance_graph}. $f_A$ projects an instance model $Im_A$ onto instance graph $IG_A$. $f_B$ projects an instance model $Im_B$ onto instance graph $IG_B$. Then the combination of $f_A$ and $f_B$, $f_{A} \sqcup f_{B}$ is again a transformation function in the sense of \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_model_instance_graph} which projects $\mathrm{combine}(Im_A, Im_B)$ onto $\mathrm{combine}(IG_A, IG_B)$.
\isabellelref{ig_combine_mapping_function_correct}{Ecore-GROOVE-Mapping.Instance_Model_Graph_Mapping}
\end{thm}

\begin{proof}
Use \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_model_instance_graph}. Since the individual transformation functions $f_A$ and $f_B$ preserve the elements of their instance graphs when the instance model is combined with another one, we can establish that the definition of $f_{A} \sqcup f_{B}$ will also preserve these elements. This can be shown using the commutativity and associativity of the combination of instance models, see \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_models:imod_combine_commute} and \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_models:imod_combine_assoc} respectively.
\end{proof}

This last theorem completes the recursive behaviour of combining transformation functions and therefore allows for building transformation functions from instance models to instance graphs iteratively.

The definitions and theorems that are presented so far only work in one direction: for transforming instance models into instance graphs. As visually shown in \cref{fig:transformation_framework:instance_models_and_instance_graphs:structure_instance_models_graphs}, it must also be possible to transform instance graphs back into instance models. The definitions and theorems needed for this transformation are similar and will be presented in the remaining part of this section.

\begin{defin}[Transformation function from an instance graph to an instance model]
\label{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_graph_instance_model}
Let $f$ be a function from instance graphs to instance models, $IG$ be an instance graph and $Im$ the corresponding instance model. $f$ is a transformation function iff:
\begin{itemize}
    \item $f$ projects $IG$ onto $Im$: $f(IG) = Im$;
    \item After combination with another instance graph, $f$ preserves the type model;
    \item After combination with another instance graph, $f$ preserves the objects:\\$\forall IG_x\!: Object_{f(IG)} \subseteq Object_{f(\mathrm{combine}(IG, IG_x))}$;
    \item For all objects in the projected instance model, $f$ preserves the object class if the instance graph is combined with another instance graph:\\$\forall IG_x\!: \forall o \in Object_{f(IG)}\!: \mathrm{ObjectClass}_{f(IG)}(o) = \mathrm{ObjectClass}_{f(\mathrm{combine}(IG, IG_x))}(o)$;
    \item For all objects in the projected instance model, $f$ preserves the object identifier if the instance graph is combined with another instance graph:\\$\forall IG_x\!: \forall o \in Object_{f(IG)}\!: \mathrm{ObjectId}_{f(IG)}(o) = \mathrm{ObjectId}_{f(\mathrm{combine}(IG, IG_x))}(o)$;
    \item For all objects in the projected instance model and all fields in the type model corresponding to the projected instance model, $f$ preserves the field value if the instance graph is combined with another instance graph:\\$\forall IG_x\!: \forall o \in Object_{f(IG)}\!: \forall d \in Field_{Tm_{f(IG)}}\!:$\\$ \mathrm{FieldValue}_{f(IG)}(( o, d )) = \mathrm{FieldValue}_{f(\mathrm{combine}(IG, IG_x))}(( o, d ))$;
    \item For all constants in the type model corresponding to the projected instance model, $f$ preserves the default value if the instance graph is combined with another instance graph:\\$\forall IG_x\!: \forall c \in Constant_{Tm_{f(IG)}}\!: \mathrm{DefaultValue}_{f(IG)}(c) = \mathrm{DefaultValue}_{f(\mathrm{combine}(IG, IG_x))}(c)$;
\end{itemize}
\isabellelref{imod_combine_mapping_function}{Ecore-GROOVE-Mapping.Instance_Model_Graph_Mapping}
\end{defin}

Just like \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_model_instance_graph}, the definition of transformation functions from an instance graph to an instance model preserves all elements if the instance graph is combined with another instance graph. This will once more be the key to having the property of iterative building of transformation functions.

The following definition will describe how two transformation functions from instance graphs to instance models can be combined into a new transformation function, which projects the combination of two instance graphs onto the combination of the two corresponding instance models.

\begin{defin}[Combination of transformation functions from an instance graph to an instance model]
\label{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:combination_transformation_function_instance_graph_instance_model}
Let $f_A$ and $f_B$ be a transformation functions in the sense of \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_graph_instance_model}. $f_A$ projects an instance graph $IG_A$ onto instance model $Im_A$. $f_B$ projects an instance graph $IG_B$ onto instance model $Im_B$. Then the combination of $f_A$ and $f_B$ is defined as:
\begin{align*}
f_{A} \sqcup f_{B}(IG) =\ &\langle&
Object =\ &\{o \mid o \in Object_{f_{A}(IG)} \land o \in Object_{Im_A} \}\ \cup\\&&&
\{o \mid o \in Object_{f_{B}(IG)} \land o \in Object_{Im_B} \} \\&&
\mathrm{ObjectClass} =\ &\mathrm{objectclass\_\!mapping}(f_A, Im_A, f_B, Im_B, IG) \\&&
\mathrm{ObjectId} =\ &\mathrm{objectid\_\!mapping}(f_A, Im_A, f_B, Im_B, IG) \\&&
\mathrm{FieldValue} =\ &\mathrm{fieldvalue\_\!mapping}(f_A, Im_A, f_B, Im_B, IG) \\&&
\mathrm{ConstType} =\ &\mathrm{consttype\_\!mapping}(f_A, Im_A, f_B, Im_B, IG) \\&
\rangle
\end{align*}
In which $\mathrm{objectclass\_\!mapping}$ is given as part of \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:objectclass_mapping}, $\mathrm{objectid\_\!mapping}$ as part of \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:objectid_mapping}, $\mathrm{fieldvalue\_\!mapping}$ as part of \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:fieldvalue_mapping} and $\mathrm{defaultvalue\_\!mapping}$ as part of \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:defaultvalue_mapping}.
\isabellelref{imod_combine_mapping}{Ecore-GROOVE-Mapping.Instance_Model_Graph_Mapping}
\end{defin}

As expected, the definition for the combination of transformation functions from an instance graph to an instance model is an alternation of \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_models:combine}. This alternation will once more allow the combined transformation function to project the combination of the instance graphs to the combination of the corresponding instance models.

The following four definitions will provide the remaining functions, which will closely follow their counterparts from \cref{subsec:transformation_framework:instance_models_and_instance_graphs:combining_instance_models}.

\begin{defin}[Combination of the object class function for two transformation functions]
\label{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:objectclass_mapping}
$\mathrm{objectclass\_\!mapping}(f_A, Im_A, f_B, Im_B, IG)$ is a partial function on two transformation functions $f_A$ and $f_B$, their corresponding projections $Im_A$ and $Im_B$ and an instance model $IG$ which returns a new function $Object_{f_{A} \sqcup f_{B}(IG)} \Rightarrow Class_{Tm_{f_{A} \sqcup f_{B}(IG)}}$. It is defined as follows:
\begin{multline*}
    \mathrm{objectclass\_\!mapping}(f_A, Im_A, f_B, Im_B, IG, o) = \\
    \begin{cases}
        \mathrm{ObjectClass}_{f_{A}(IG)}(o) & \mathrm{if }\ o \in \{o \mid o \in Object_{f_{A}(IG)} \land o \in Object_{Im_A} \}\ \cap \\&\qquad\{o \mid o \in Object_{f_{B}(IG)} \land o \in Object_{Im_B} \}\ \land \\&\quad \mathrm{ObjectClass}_{f_{A}(IG)}(o) = \mathrm{ObjectClass}_{f_{B}(IG)}(o) \\
        \mathrm{ObjectClass}_{f_{A}(IG)}(o) & \mathrm{if }\ o \in \{o \mid o \in Object_{f_{A}(IG)} \land o \in Object_{Im_A} \}\ \setminus \\&\qquad\{o \mid o \in Object_{f_{B}(IG)} \land o \in Object_{Im_B} \} \\
        \mathrm{ObjectClass}_{f_{B}(IG)}(o) & \mathrm{if }\ o \in \{o \mid o \in Object_{f_{B}(IG)} \land o \in Object_{Im_B} \}\ \setminus \\&\qquad\{o \mid o \in Object_{f_{A}(IG)} \land o \in Object_{Im_A} \}
    \end{cases}
\end{multline*}
\isabellelref{imod_combine_object_class_mapping}{Ecore-GROOVE-Mapping.Instance_Model_Graph_Mapping}
\end{defin}

\begin{defin}[Combination of the object identifier function for two transformation functions]
\label{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:objectid_mapping}
$\mathrm{objectid\_\!mapping}(f_A, Im_A, f_B, Im_B, IG)$ is a partial function on two transformation functions $f_A$ and $f_B$, their corresponding projections $Im_A$ and $Im_B$ and an instance model $IG$ which returns a new function $Object_{f_{A} \sqcup f_{B}(IG)} \Rightarrow Name$. It is defined as follows:
\begin{multline*}
    \mathrm{objectid\_\!mapping}(f_A, Im_A, f_B, Im_B, IG, o) = \\
    \begin{cases}
        \mathrm{ObjectId}_{f_{A}(IG)}(o) & \mathrm{if }\ o \in \{o \mid o \in Object_{f_{A}(IG)} \land o \in Object_{Im_A} \}\ \cap \\&\qquad\{o \mid o \in Object_{f_{B}(IG)} \land o \in Object_{Im_B} \}\ \land \\&\quad \mathrm{ObjectId}_{f_{A}(IG)}(o) = \mathrm{ObjectId}_{f_{B}(IG)}(o) \\
        \mathrm{ObjectId}_{f_{A}(IG)}(o) & \mathrm{if }\ o \in \{o \mid o \in Object_{f_{A}(IG)} \land o \in Object_{Im_A} \}\ \setminus \\&\qquad\{o \mid o \in Object_{f_{B}(IG)} \land o \in Object_{Im_B} \} \\
        \mathrm{ObjectId}_{f_{B}(IG)}(o) & \mathrm{if }\ o \in \{o \mid o \in Object_{f_{B}(IG)} \land o \in Object_{Im_B} \}\ \setminus \\&\qquad\{o \mid o \in Object_{f_{A}(IG)} \land o \in Object_{Im_A} \}
    \end{cases}
\end{multline*}
\isabellelref{imod_combine_object_id_mapping}{Ecore-GROOVE-Mapping.Instance_Model_Graph_Mapping}
\end{defin}

\begin{defin}[Combination of the default value function for two transformation functions]
\label{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:defaultvalue_mapping}
$\mathrm{defaultvalue\_\!mapping}(f_A, Im_A, f_B, Im_B, IG)$ is a partial function on two transformation functions $f_A$ and $f_B$, their corresponding projections $Im_A$ and $Im_B$ and an instance model $IG$ which returns a new function $Constant_{Tm_{f_{A} \sqcup f_{B}(IG)}} \Rightarrow Value_{f_{A} \sqcup f_{B}(IG)}$. It is defined as follows:
\begin{multline*}
    \mathrm{defaultvalue\_\!mapping}(f_A, Im_A, f_B, Im_B, IG, c) = \\
    \begin{cases}
        \mathrm{DefaultValue}_{f_{A}(IG)}(c) & \mathrm{if }\ c \in \{c \mid c \in Constant_{Tm_{f_{A}(IG)}} \land c \in Constant_{Tm_A} \}\ \cap \\&\qquad \{c \mid c \in Constant_{Tm_{f_{B}(IG)}} \land c \in Constant_{Tm_B} \}\ \land\\&\quad \mathrm{DefaultValue}_{f_{A}(IG)}(c) = \mathrm{DefaultValue}_{f_{B}(IG)}(c) \\
        \mathrm{DefaultValue}_{f_{A}(IG)}(c) & \mathrm{if }\ c \in \{c \mid c \in Constant_{Tm_{f_{A}(IG)}} \land c \in Constant_{Tm_A} \}\ \setminus \\&\qquad \{c \mid c \in Constant_{Tm_{f_{B}(IG)}} \land c \in Constant_{Tm_B} \} \\
        \mathrm{DefaultValue}_{f_{B}(IG)}(c) & \mathrm{if }\ c \in \{c \mid c \in Constant_{Tm_{f_{B}(IG)}} \land c \in Constant_{Tm_B} \}\ \setminus \\&\qquad \{c \mid c \in Constant_{Tm_{f_{A}(IG)}} \land c \in Constant_{Tm_A} \}
    \end{cases}
\end{multline*}
\isabellelref{imod_combine_default_value_mapping}{Ecore-GROOVE-Mapping.Instance_Model_Graph_Mapping}
\end{defin}

\begin{defin}[Combination of the field value function for two transformation functions]
\label{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:fieldvalue_mapping}
$\mathrm{fieldvalue\_\!mapping}(f_A, Im_A, f_B, Im_B, IG)$ is a partial function on two transformation functions $f_A$ and $f_B$, their corresponding projections $Im_A$ and $Im_B$ and an instance model $IG$ which returns a new function $(Object_{f_{A} \sqcup f_{B}(IG)} \times Field_{Tm_{f_{A} \sqcup f_{B}(IG)}}) \Rightarrow Value_{f_{A} \sqcup f_{B}(IG)}$. It is defined as follows:
\begin{multline*}
    \mathrm{fieldvalue\_\!mapping}(f_A, Im_A, f_B, Im_B, IG, ( o, d )) = \\
    \begin{cases}
        \mathrm{FieldValue}_{f_{A}(IG)}(( o, d )) & \mathrm{if}\ o \in \{o \mid o \in Object_{f_{A}(IG)} \land o \in Object_{Im_A} \}\ \cap \\&\qquad\{o \mid o \in Object_{f_{B}(IG)} \land o \in Object_{Im_B} \}\ \land\\&\quad d \in \{d \mid d \in \mathrm{fields}_{Tm_{f_{A}(IG)}}(\mathrm{ObjectClass}_{f_{A}(IG)}(o))\ \land \\&\qquad\quad d \in \mathrm{fields}_{Tm_A}(\mathrm{ObjectClass}_{f_{A}(IG)}(o)) \}\ \land\\&\quad d \in \{d \mid d \in \mathrm{fields}_{Tm_{f_{B}(IG)}}(\mathrm{ObjectClass}_{f_{B}(IG)}(o))\ \land \\&\qquad\quad d \in \mathrm{fields}_{Tm_B}(\mathrm{ObjectClass}_{f_{B}(IG)}(o)) \}\ \land\\&\quad \mathrm{FieldValue}_{f_{A}(IG)}(( o, d )) = \mathrm{FieldValue}_{f_{B}(IG)}(( o, d )) \\
        \mathrm{FieldValue}_{f_{A}(IG)}(( o, d )) & \mathrm{if}\ o \in \{o \mid o \in Object_{f_{A}(IG)} \land o \in Object_{Im_A} \}\ \land \\&\quad d \in \{d \mid d \in \mathrm{fields}_{Tm_{f_{A}(IG)}}(\mathrm{ObjectClass}_{f_{A}(IG)}(o))\ \land \\&\qquad\quad d \in \mathrm{fields}_{Tm_A}(\mathrm{ObjectClass}_{f_{A}(IG)}(o)) \}\ \land\\&\quad (o \not\in \{o \mid o \in Object_{f_{B}(IG)} \land o \in Object_{Im_B} \}\ \lor \\&\quad d \not\in \{d \mid d \in \mathrm{fields}_{Tm_{f_{B}(IG)}}(\mathrm{ObjectClass}_{f_{B}(IG)}(o))\ \land \\&\qquad\quad d \in \mathrm{fields}_{Tm_B}(\mathrm{ObjectClass}_{f_{B}(IG)}(o)) \} \\
        \mathrm{FieldValue}_{f_{B}(IG)}(( o, d )) & \mathrm{if}\ o \in \{o \mid o \in Object_{f_{B}(IG)} \land o \in Object_{Im_B} \}\ \land \\&\quad d \in \{d \mid d \in \mathrm{fields}_{Tm_{f_{B}(IG)}}(\mathrm{ObjectClass}_{f_{B}(IG)}(o))\ \land \\&\qquad\quad d \in \mathrm{fields}_{Tm_B}(\mathrm{ObjectClass}_{f_{B}(IG)}(o)) \}\ \land\\&\quad (o \not\in \{o \mid o \in Object_{f_{A}(IG)} \land o \in Object_{Im_A} \}\ \lor \\&\quad d \not\in \{d \mid d \in \mathrm{fields}_{Tm_{f_{A}(IG)}}(\mathrm{ObjectClass}_{f_{A}(IG)}(o))\ \land \\&\qquad\quad d \in \mathrm{fields}_{Tm_A}(\mathrm{ObjectClass}_{f_{A}(IG)}(o)) \}
    \end{cases}
\end{multline*}
\isabellelref{imod_combine_field_value_mapping}{Ecore-GROOVE-Mapping.Instance_Model_Graph_Mapping}
\end{defin}

The definitions of most of these combination functions are straightforward. Only the $\mathrm{fieldvalue\_\!mapping}$ seems significantly more complicated. However, a careful ready will still be able to see that the definition is an alternation of \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_models:fieldvalue_combine}. The definition seems more complicated because of the combination of objects and fields in the domain of the function.

With these definitions in place, it is possible to provide the necessary theorems for the correctness of the combined function $f_{A} \sqcup f_{B}$.

\begin{thm}[The projection of a combined transformation function from an instance graph to an instance model]
\label{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:imod_combine_mapping_correct}
Let $f_A$ and $f_B$ be a transformation functions in the sense of \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_graph_instance_model}. $f_A$ projects an instance graph $IG_A$ onto instance model $Im_A$. $f_B$ projects an instance model $IG_B$ onto instance graph $Im_B$. Then the combination of $f_A$ and $f_B$, $f_{A} \sqcup f_{B}$ projects $\mathrm{combine}(IG_A, IG_B)$ onto $\mathrm{combine}(Im_A, Im_B)$, so:
\begin{equation*}
    f_{A} \sqcup f_{B}(\mathrm{combine}(IG_A, IG_B)) = \mathrm{combine}(Im_A, Im_B)
\end{equation*}
\isabellelref{imod_combine_mapping_correct}{Ecore-GROOVE-Mapping.Instance_Model_Graph_Mapping}
\end{thm}

\begin{proof}
The corresponding proof follows directly from \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:combination_transformation_function_instance_graph_instance_model} as well as \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_graph_instance_model}. Since the individual transformation functions $f_A$ and $f_B$ preserve the elements of their instance models when the instance graph is combined with another one, we can establish that the definition of $f_{A} \sqcup f_{B}$ is equal to the definition of $\mathrm{combine}(Im_A, Im_B)$. Therefore, $f_{A} \sqcup f_{B}(\mathrm{combine}(IG_A, IG_B)) = \mathrm{combine}(Im_A, Im_B)$.
\end{proof}

Like the combined transformation function from instance models to instance graphs, the combined transformation function from instance graphs to instance models is also a transformation function, but in the sense of \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_graph_instance_model}. This is stated in the following theorem.

\begin{thm}[A combined transformation function from an instance graph to an instance model is a transformation function]
\label{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:imod_combine_mapping_function_correct}
Let $f_A$ and $f_B$ be a transformation functions in the sense of \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_graph_instance_model}. $f_A$ projects an instance graph $IG_A$ onto instance model $Im_A$. $f_B$ projects an instance graph $IG_B$ onto instance model $Im_B$. Then the combination of $f_A$ and $f_B$, $f_{A} \sqcup f_{B}$ is again a transformation function in the sense of \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_graph_instance_model} which projects $\mathrm{combine}(IG_A, IG_B)$ onto $\mathrm{combine}(Im_A, Im_B)$.
\isabellelref{imod_combine_mapping_function_correct}{Ecore-GROOVE-Mapping.Instance_Model_Graph_Mapping}
\end{thm}

\begin{proof}
Use \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_graph_instance_model}. Since the individual transformation functions $f_A$ and $f_B$ preserve the elements of their instance models when the instance graph is combined with another one, we can establish that the definition of $f_{A} \sqcup f_{B}$ will also preserve these elements. This can be shown using the commutativity and associativity of the combination of instance graphs, see \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_graphs:ig_combine_commute} and \cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_graphs:ig_combine_assoc} respectively.
\end{proof}


\documentclass[twocolumn,10pt]{article}

\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{geometry}

\geometry{left=2cm,right=2cm,top=3cm,bottom=2.5cm}

\renewcommand{\vec}[1]{\mathbf{#1}}
\newcommand{\omegap}{\omega_{\mathrm{pe}}}
\newcommand{\ncrit}{n_{\mathrm{cr}}}
\newcommand{\vth}{v_{\mathrm{th}}}
\newcommand{\ldebye}{\lambda_{\mathrm{D}}}

\title{Units in VPIC}
\author{A.~G.~Seaton \& S.~V.~Luedtke}
\begin{document}
\maketitle

Units in \textsc{vpic} can be confusing.
They are user-defined, which can make inheriting a deck confusing for new users.
The reason for this flexibility is that common unit systems, such as SI, are not suitable for use in \textsc{vpic} because of its use of IEEE 754 single precision floating point numbers.
In single precision, the smallest number representable with full precision is $2^{-126} \approx 1.2\times 10^{-38}$.
As an example, the SI value for $\hbar$, $1.05\times 10^{-34}$, is only four orders of magnitude away from losing precision.  Multiply it by the electron mass, and you are hopelessly lost.
%
%	\begin{itemize}
%		\item $l_{\mathrm{deck}}$: an implicit unit of length for the spatial grid
%		\item $c_{\mathrm{deck}}$: the speed of light in vacuum
%		\item $\varepsilon_{0,\mathrm{deck}}$: the vacuum permittivity
%		\item $r_{\alpha,\mathrm{deck}} \equiv (q_{\alpha}/m_{\alpha})_{\mathrm{deck}}$: The charge/mass ratio of species $\alpha$.
%	\end{itemize}

To set up a simulation, the user provides \textsc{vpic} with values for the time step, cell dimensions, speed of light in vacuum, and vacuum permittivity.
This is either done by directly assigning to the \texttt{grid} struct or by using the functions \texttt{define\_units}, \texttt{define\_timestep}, and (for example) \texttt{define\_periodic\_grid}.
Usually one or more species are defined too, which each require values for the species mass and charge.
These are normally set using the \texttt{define\_species} function.
It is important to understand that \textsc{vpic} solves the same equations regardless of which values it is given and the chosen unit system.

We will assume here that two unit systems are in use.
The first of these we will refer to as the `user' unit system, and is the user's preferred unit system.
This is often used initially to define parameters of interest to the user, such as the temperature and density of the plasma.
The second we will refer to as the `code' unit system, which is used for values passed to \textsc{vpic} itself.
This document is concerned primarily with the code unit system.

We will list some common unit systems for values supplied to \textsc{vpic} later, but for now the primary concerns for choosing a system of units are twofold:
\begin{enumerate}
	\item The units must be compatible with the SI \emph{equation form} that is solved by \textsc{vpic}, meaning that Gaussian units cannot be used.
    \item Values used by the code (including within calculations) should never exceed $\pm1.7\times 10^{38}$, and a value smaller than $\pm1.2\times 10^{-38}$ should not be meaningfully different from zero.
\end{enumerate}

\section{Unit Conversions}

In order to calculate values in the code unit system to supply to \textsc{vpic}, we need to know the unit conversions.
Taking the base units as length, time, mass, and charge, we define conversion factors $L$, $T$, $M$, and $Q$ so that a quantity $f_c$ in the code unit system is converted to a value $f_u$ in the user unit system using $f_u = Ff_c$.

Each value supplied to \textsc{vpic} can be used to constrain the unit system by writing an equation for its conversion from the user unit system to code units in terms of the base unit conversion factors.
Therefore by picking a subset of these values, we can fully determine the unit system.

To determine what the four base unit conversion factors are, we need four constraining equations.
There are multiple sets of values we could choose.
Given the base units, a straightforward choice would be the timestep, cell size, and species mass and charge.
Here instead we pick the cell size $h$, speed of light $c$, vacuum permittivity $\varepsilon_0$, and the charge-mass ratio $r_{\alpha}$ of some species $\alpha$.
This is motivated by many common unit systems setting $\varepsilon_{0,\mathrm{c}} = 1$ or $c_{\mathrm{c}} = 1$, as will be seen later.

The constraining equations are then:

\begin{align*}
	h_{\mathrm{c}}L                               &= h_{\mathrm{u}},             &
	c_{\mathrm{c}}\frac{L}{T}                     &= c_{\textrm{u}},             \\
    \varepsilon_{0,\mathrm{c}}\frac{Q^2T^2}{ML^3} &= \varepsilon_{0,\textrm{u}}, &
    r_{\alpha,\mathrm{c}}\frac{Q}{M}              &= r_{\alpha,\textrm{u}}.
\end{align*}

\noindent Solving for the conversion factors we find:
\begin{align}
	L &= \frac{h_{\mathrm{u}}}{h_{\mathrm{c}}}, \\
	T &= \frac{h_{\mathrm{u}}}{h_{\mathrm{c}}}\frac{c_{\mathrm{c}}}{c_{\mathrm{u}}}, \\
	M &= \frac{h_{\mathrm{u}}}{h_{\mathrm{c}}}\left(\frac{c_{\mathrm{u}}}{c_{\mathrm{c}}}\right)^2\frac{\varepsilon_{0,\mathrm{u}}}{\varepsilon_{0,\mathrm{c}}}\left(\frac{r_{\alpha,\mathrm{c}}}{r_{\alpha,\mathrm{u}}}\right)^2, \\
	Q &= \frac{h_{\mathrm{u}}}{h_{\mathrm{c}}}\left(\frac{c_{\mathrm{u}}}{c_{\mathrm{c}}}\right)^2\frac{\varepsilon_{0,\mathrm{u}}}{\varepsilon_{0,\mathrm{c}}}\frac{r_{\alpha,\mathrm{c}}}{r_{\alpha,\mathrm{u}}}.
\end{align}

\noindent These can then be combined into factors for other quantities.
For example, the electric and magnetic field conversion factors $E$ and $B$ are given by
\begin{align}
	E &= \frac{ML}{QT^2} = \frac{h_{\mathrm{c}}}{h_{\mathrm{u}}}\frac{r_{\alpha,\mathrm{c}}}{r_{\alpha}}\left(\frac{c_{\mathrm{u}}}{c_{\mathrm{c}}}\right)^2, \\
	B &= E\frac{T}{L} = \frac{h_{\mathrm{c}}}{h_{\mathrm{u}}}\frac{r_{\alpha,\mathrm{c}}}{r_{\alpha,\mathrm{u}}}\frac{c_{\mathrm{u}}}{c_{\mathrm{c}}}.
\end{align}

\subsection{Exceptions}

In addition to calculating the above conversion factors, the user should be aware of how \textsc{vpic} normalises variables internally.

\subsubsection{Particle Momenta}

\textsc{vpic} stores relativistic momentum rather than velocity (which would cause numerical issues) for each particle.
The momentum is stored in dimensionless form given by
\begin{equation}
    p_{\textrm{norm}} = \frac{p}{m_\alpha c},
\end{equation}
where $m_\alpha$ is the mass assigned to species $\alpha$ and $c$ is the speed of light in a vacuum.
This is what must be supplied by the user when performing the particle load.

\subsubsection{Magnetic Fields}

For performance reasons, and due to the use of single-precision floating point numbers, \textsc{vpic} stores the scaled magnetic field $c\vec{B}$ rather than $\vec{B}$.

\section{Species \& Particle Weighting}

To define a particle species in \textsc{vpic}, the user specifies the species mass $m_{\mathrm{s}}$ and charge $q_{\mathrm{s}}$. Additionally, each particle is individually assigned a weighting factor $w$. These must be consistent with each other and the above unit system to produce the desired behavior.

\subsection{Choosing Charge Mass Ratio}

The motion of a physical particle with charge $q_{\mathrm{p}}$ and mass $m_{\mathrm{p}}$ in the EM fields only has explicit dependence on the charge-to-mass ratio $r \equiv q_{\mathrm{p}}/m_{\mathrm{p}}$. This is also the case for macroparticles in \textsc{vpic}'s particle push. Therefore the corresponding macroparticle species must be defined such that its charge $q_{\mathrm{s}}$ and mass $m_{\mathrm{s}}$ satisfy $q_{\mathrm{s}}/m_{\mathrm{s}}=r$.

\subsection{Choosing Macroparticle Weight}
When calculating the fields generated by a macroparticle, the code uses the species charge and macroparticle weight to calculate a total charge for the macroparticle:
\begin{equation}
	q_{\mathrm{MP}} = wq_{\mathrm{s}}.
\end{equation}
For this to result in an amount of current deposition consistent with the desired physical particle density, the macroparticle weight should be defined such that the charge contained in volume $V$ is the same for the macroparticles as for physical particles, i.e.
\begin{align*}
	q_{\mathrm{p}}n_{\mathrm{p}}V &= q_{\mathrm{MP}}n_{\mathrm{MP}}V \\
		&= wq_{\mathrm{s}}n_{\mathrm{MP}}V,
\end{align*}
where $n_{\mathrm{p}}$ and $n_{\mathrm{MP}}$ are the physical particle and macroparticle number densities (macroparticles per unit volume) respectively. So, the particle weight must satisfy
\begin{align}
	w = \frac{q_{\mathrm{p}}n_{\mathrm{p}}}{q_{\mathrm{s}}n_{\mathrm{MP}}} = \frac{\rho_{\mathrm{p}}}{\rho_{\mathrm{s}}}.
\end{align}
This illustrates that there is a degree of freedom available in that the species charge defined in the deck does not have to be the same as the physical species charge.

\subsection{Consequences of $q_{\mathrm{s}} \neq q_{\mathrm{p}}$}

The possibility of $q_{\mathrm{s}} \neq q_{\mathrm{p}}$ means that the code has no way of calculating numbers of physical particles since it doesn't store the true particle charge.
This for example is why the hydro dumps contain charge density rather than number density.
Users should therefore also ensure that any custom diagnostics do not assume $q_{\mathrm{s}} = q_{\mathrm{p}}$.

\section{Examples of Common Unit Systems}

Various choices are often made for the unit system, and we discuss a few of them here.
In general, aside from ensuring that values do not exceed the limits for single-precision floating point numbers, it is often desirable to choose a unit system that eases interpretation of simulation results.
Many of these unit systems allow the governing equations to be written in simpler form, which are convenient in theoretical analysis, and we will illustrate some of these cases here.
As discussed above, the unit system has no bearing on the calculations performed by \textsc{vpic} -- it always solves the full system of equations.

\subsection{Electrostatic Plasma Units}

In an electrostatic problem simulating an electron plasma, the natural length and time-scales are the Debye length $\ldebye$ and inverse plasma frequency $\omegap^{-1}$.
These are also the typical scales for the grid and time-step.
Then choosing the electron charge/mass ratio so that $e/m_e$ becomes unity reduces the equation of motion of an electron to
\begin{equation*}
	\ddot{\vec{r}} = \vec{E}.
\end{equation*}
Finally setting $\varepsilon_0=1$ means that Gauss' law is also simplified
\begin{equation*}
	\nabla \cdot \vec{E} = \rho.
\end{equation*}

\noindent In the deck we would specify
\begin{align*}
	h_{\mathrm{c}}             &= \frac{h_{\mathrm{u}}}{\ldebye}, &
	c_{\mathrm{c}}             &= \frac{c}{\vth},    \\
	\varepsilon_{0,\mathrm{c}} &= 1,                              &
	r_{e,\mathrm{c}}           &= -1,
\end{align*}

\noindent giving the unit conversions as
\begin{align*}
	L &= \ldebye,                  &
	T &= \omegap^{-1},             &
	M &= N_{\mathrm{D}}m_e,        \\
	Q &= N_{\mathrm{D}}e,          &
	E &= \frac{m_e}{e}\vth\omegap, &
	B &= \frac{m_e}{e}\omegap,
\end{align*}

\noindent where $N_{\mathrm{D}} \equiv n_e\ldebye^3$ is the number of electrons in a `Debye cube'.

This unit system allows for some convenient sanity checks.
As mentioned above, the cell size and time-step must be around $1$.
Additionally, if the electron mass in these units is not significantly smaller than 1, then the plasma is not ideal, and simulating it with \textsc{vpic} is not appropriate.
Interpretation of simulation results may also be more convenient.
For example, the normalized electric field $E_c$ is the electron quiver velocity in a plasma wave divided by the thermal velocity -- an important parameter for determining whether wavebreaking will occur.
Similarly, the wavenumber of a plasma wave is normalised such that $k_c = k\ldebye$, which determines the Landau damping rate.

\subsection{Electromagnetic Plasma Units}

For an electromagnetic problem, the electrostatic units above might be modified so that the length scale becomes the electron skin depth $l_e=c/\omegap$.
The Lorentz force and Maxwell's equations become
\begin{equation*}
	\ddot{\vec{r}} = \vec{E} + \vec{v} \times \vec{B},
\end{equation*}

\noindent and
\begin{align*}
	\nabla \times \vec{E} &= -\partial_t \vec{B}, \\
	\nabla \times \vec{B} &= \left(\vec{J} + \partial_t \vec{E}\right).
\end{align*}

\noindent The deck assignments become:
\begin{align*}
	h_{\mathrm{c}}             &= h_{\mathrm{u}}\frac{\omegap}{c}, &
	c_{\mathrm{c}}             &= 1, \\
	\varepsilon_{0,\mathrm{c}} &= 1, &
	r_{e,\mathrm{c}}           &= -1,
\end{align*}

\noindent so that the conversion factors are now
\begin{align*}
	L &= \frac{c}{\omega_{\mathrm{pe}}}, &
	T &= \frac{1}{\omega_{\mathrm{pe}}}, \\
	M &= n_e\frac{c^3}{\omegap^3}m_e,    &
	Q &= n_e\frac{c^3}{\omegap^3}e,      \\
	E &= \frac{m_e}{e}\omegap c,         &
	B &= \frac{m_e}{e}\omegap.
\end{align*}

\noindent Note that by removing $\ldebye$ from the unit system, there is no longer any dependence on the electron temperature used to calculate it.

\subsection{Laser-Plasma Units}

For laser-plasma interaction problems, the unit system can again be modified by replacing the time-scale with the inverse laser frequency, so that the unit system no longer depends on the electron density used to calculate $\omega_{\mathrm{pe}}$ and is instead dependent purely on the laser frequency.
In the deck the assignments are
\begin{align*}
	h_{\mathrm{c}}             &= h_{\mathrm{u}}k_0, &
	c_{\mathrm{c}}             &= 1,             \\
	\varepsilon_{0,\mathrm{c}} &= 1,             &
	r_{e,\mathrm{c}}           &= -1,
\end{align*}

\noindent where $k_0 \equiv \omega_0/c$ is the vacuum laser wavenumber.

The conversion factors then become
\begin{align*}
	L &= \frac{1}{k_0},           &
	T &= \frac{1}{\omega_0},      \\
	M &= \frac{\ncrit}{k_0^3}m_e, &
	Q &= \frac{\ncrit}{k_0^3}e,   \\
	E &= \frac{m_e}{e}\omega_0 c, &
	B &= \frac{m_e}{e}\omega_0,
\end{align*}

where $\ncrit \equiv m_e\varepsilon_0\omega_0^2/e^2$ is the critical density.
In this unit system the simulation cell size and time step should satisfy $\Delta x \ll 1$ and $\Delta t \ll 1$ in order for the field solver to accurately model the laser.
It is also necessary to verify that the cell size resolves the Debye length, which is often a more restrictive condition.
Additionally, the normalized electric (or magnetic) field is the parameter $a_0$.
For $a_0 \ll 1$, this is the electron quiver velocity divided by the speed of light, while $a_0 \gtrsim 1$ indicates a relativistic field intensity which will lead to effects such as relativistically induced transparency and relativistic self-focusing.

\end{document}


\section{Introduction}
\label{sec:intro}

In this paper we design numerical methods to solve a two-moment model that governs the transport of particles obeying Fermi-Dirac statistics (e.g., neutrinos), with the ultimate target being nuclear astrophysics applications (e.g., neutrino transport in core-collapse supernovae and compact binary mergers).
The numerical method is based on the discontinuous Galerkin (DG) method for spatial discretization and implicit-explicit (IMEX) methods for time integration, and it is designed to preserve certain physical constraints of the underlying model.
The latter property is achieved by considering the spatial and temporal discretization together with the closure procedure for the two-moment model.

In many applications, the particle mean free path is comparable to or exceeds other characteristic length scales in the system under consideration, and non-equilibrium effects may become important.
In these situations, a kinetic description based on a particle distribution function may be required.
The distribution function, a phase space density $f$ depending on momentum $\vect{p}\in\bbR^{3}$ and position $\vect{x}\in\bbR^{3}$, is defined such that $f(\vect{p},\vect{x},t)$ gives at time $t\in\bbR^{+}$ the number of particles in the phase space volume element $d\vect{p}\,d\vect{x}$ (i.e., $d\cN=f\,d\vect{p}\,d\vect{x}$).
The evolution of the distribution function is governed by the Boltzmann equation, which states a balance between phase space advection and particle collisions (see, e.g., \cite{braginskii_1965,chapmanCowling_1970,lifshitzPitaevskii_1981}).

Solving the Boltzmann equation numerically for $f$ is challenging, in part due to the high dimensionality of phase space.
To reduce the dimensionality of the problem and make it more computationally tractable, one may instead solve (approximately) for a finite number of angular moments $\vect{m}_{N}=(m^{(0)},m^{(1)},\ldots,m^{(N)})^{T}$ of the distribution function, defined as
\begin{equation}
  m^{(k)}(\varepsilon,\vect{x},t)=\f{1}{4\pi}\int_{\bbS^{2}}f(\omega,\varepsilon,\vect{x},t)\,g^{(k)}(\omega)\,d\omega,
\end{equation}
where $\varepsilon=|\vect{p}|$ is the particle energy, $\omega$ is a point on the unit sphere $\bbS^{2}$ indicating the particle propagation direction, and $g^{(k)}$ are momentum space angular weighing functions.
In problems where collisions are sufficiently frequent, solving a \emph{truncated moment problem} can provide significant reductions in computational cost since only a few moments are needed to represent the solution accurately.
On the other hand, in problems where collisions do not sufficiently isotropize the distribution function, more moments may be needed.
In the two-moment model considered here ($N=1$), angular moments representing the particle density and flux (or energy density and momentum) are solved for.
Two-moment models for relativistic systems appropriate for nuclear astrophysics applications have been discussed in, e.g., \cite{lindquist_1966,andersonSpiegel_1972,thorne_1981,shibata_etal_2011,cardall_etal_2013a}.
However, in this paper, for simplicity (and clarity), we consider a non-relativistic model, leaving extensions to relativistic systems for future work.

In a truncated moment model, the equation governing the evolution of the \mbox{$N$-th} moment $m^{(N)}$ contains higher moments $\{m^{(k)}\}_{k=N+1}^{M}$ ($M>N$), which must be specified in order to form a closed system of equations.
For the two-moment model, the symmetric rank-two Eddington tensor (proportional to the pressure tensor) must be specified.
Approaches to this \emph{closure problem} include setting $m^{(k)}=0$, for $k>N$ ($P_N$ equations \cite{brunnerHolloway_2005} and filtered versions thereof \cite{mcclarrenHauck_2010,laboure_etal_2016}), Eddington approximation (when $N=0$) \cite{mihalasMihalas_1999}, Kershaw-type closure \cite{kershaw_1976}, and maximum entropy closure \cite{minerbo_1978,cernohorskyBludman_1994,olbrant_etal_2013}.
The closure procedure often results in a system of nonlinear hyperbolic conservation laws, which can be solved using suitable numerical methods (e.g., \cite{leveque_1992}).

One challenge in solving the closure problem is constructing a sequence of moments that are consistent with a positive distribution function, which typically implies algebraic constraints on the moments \cite{kershaw_1976,levermore_1984}.
Moments satisfying these constraints are called \emph{realizable moments} (e.g., \cite{levermore_1996}).
When evolving a truncated moment model numerically, maintaining realizable moments is challenging, but necessary in order to ensure the well-posedness of the closure procedure \cite{levermore_1996,junk_1998,hauck_2008}.
In addition to putting the validity of the numerical results into question, failure to maintain moment realizability in a numerical model may, in order to continue a simulation, require ad hoc post-processing steps with undesirable consequences such as loss of conservation.

Here we consider a two-moment model for particles governed by Fermi-Dirac statistics.
It is well known from the two-moment model for particles governed by Maxwell-Boltzmann statistics (``classical'' particles with $f\ge0$), that the particle density is nonnegative and the magnitude of the flux vector is bounded by the particle density.
(There are further constraints on the components of the Eddington tensor \cite{levermore_1984}.)
Furthermore, the set of realizable moments generated by the particle density and flux vector constitutes a convex cone \cite{olbrant_etal_2012}.
In the fermionic case, there is also an upper bound on the distribution function (e.g., $f\le1$) because Pauli's exclusion principle prevents particles from occupying the same microscopic state.
The fermionic two-moment model has recently been studied theoretically in the context of maximum entropy closures \cite{lareckiBanach_2011,banachLarecki_2013,banachLarecki_2017b} and Kershaw-type closures \cite{banachLarecki_2017a}.
Because of the upper bound on the distribution function, the algebraic constraints on realizable moments differ from the classical case with no upper bound, and can lead to significantly different dynamics when the occupancy is high (i.e., when $f$ is close to its upper bound).
In the fermionic case, the set of realizable moments generated by the particle density and flux vector is also convex.
It is ``eye-shaped'' (as will be shown later; cf. Figure~\ref{fig:RealizableSetFermionic} in Section~\ref{sec:realizability}) and tangent to the classical realizability cone on the end representing low occupancy, but is much more restricted for high occupancy.

In this paper, the two-moment model is discretized in space using high-order Discontinuous Galerkin (DG) methods (e.g., \cite{cockburnShu_2001,hesthavenWarburton_2008}).
DG methods combine elements from both spectral and finite volume methods and are an attractive option for solving hyperbolic partial differential equations (PDEs).
They achieve high-order accuracy on a compact stencil; i.e., data is only communicated with nearest neighbors, regardless of the formal order of accuracy, which can lead to a high computation to communication ratio, and favorable parallel scalability on heterogeneous architectures has been demonstrated \cite{klockner_etal_2009}.
Furthermore, they can easily be applied to problems involving curvilinear coordinates (e.g., beneficial in numerical relativity \cite{teukolsky_2016}).
Importantly, DG methods exhibit favorable properties when collisions with a background are included, as they recover the correct asymptotic behavior in the diffusion limit, characterized by frequent collisions (e.g., \cite{larsenMorel_1989,adams_2001,guermondKanschat_2010}).
The DG method was introduced in the 1970s by Reed \& Hill \cite{reedHill_1973} to solve the neutron transport equation, and has undergone remarkable developments since then (see, e.g., \cite{shu_2016} and references therein).

We are concerned with the development and application of DG methods for the fermionic two-moment model that can preserve the aforementioned algebraic constraints and ensure realizable moments, provided the initial condition is realizable.
Our approach is based on the constraint-preserving (CP) framework introduced in \cite{zhangShu_2010a}, and later extended to the Euler equations of gas dynamics in \cite{zhangShu_2010b}.
(See, e.g., \cite{xing_etal_2010,zhangShu_2011,olbrant_etal_2012,cheng_etal_2013,zhang_etal_2013,endeve_etal_2015,wuTang_2015} for extensions and applications to other systems.)
The main ingredients include (1) a realizability-preserving update for the cell averaged moments based on forward Euler time stepping, which evaluates the polynomial representation of the DG method in a finite number of quadrature points in the local elements and results in a Courant-Friedrichs-Lewy (CFL) condition on the time step; (2) a limiter to modify the polynomial representation to ensure that the algebraic constraints are satisfied point-wise without changing the cell average of the moments; and (3) a time stepping method that can be expressed as a convex combination of Euler steps and therefore preserves the algebraic constraints (possibly with a modified CFL condition).
As such, our method is an extension of the realizability-preserving scheme developed by Olbrant el al. \cite{olbrant_etal_2012} for the classical two-moment model.

The DG discretization leaves the temporal dimension continuous.
This semi-discretization leads to a system of ordinary differential equations (ODEs), which can be integrated with standard ODE solvers (i.e., the method of lines approach to solving PDEs).
We use implicit-explicit (IMEX) Runge-Kutta (RK) methods \cite{ascher_etal_1997,pareschiRusso_2005} to integrate the two-moment model forward in time.
This approach is motivated by the fact that we can resolve time scales associated with particle streaming terms in the moment equations, which will be integrated with explicit methods, while terms associated with collisional interactions with the background induce fast time scales that we do not wish to resolve, and will be integrated with implicit methods.
This splitting has some advantages when solving kinetic equations since the collisional interactions may couple across momentum space, but are local in position space, and are easier to parallelize than a fully implicit approach.

The CP framework of \cite{zhangShu_2010a} achieves high-order (i.e., greater than first-order) accuracy in time by employing strong stability-preserving explicit Runge-Kutta (SSP-RK) methods \cite{shuOsher_1988,gottlieb_etal_2001}, which can be written as a convex combination of forward Euler steps.
Unfortunately, this strategy to achieve high-order temporal accuracy does not work as straightforwardly for standard IMEX Runge-Kutta (IMEX-RK) methods because implicit SSP Runge-Kutta methods with greater than first-order accuracy have time step restrictions similar to explicit methods \cite{gottlieb_etal_2001}.
To break this ``barrier,'' recently proposed IMEX-RK schemes \cite{chertock_etal_2015,hu_etal_2018} have resorted to first-order accuracy in favor of the SSP property in the standard IMEX-RK scheme, and recover second-order accuracy with a correction step.

We consider the application of the correction approach to the two-moment model.
However, with the correction step from \cite{chertock_etal_2015} we are unable to prove the realizability-preserving property without invoking an overly restrictive time step.
With the correction step from \cite{hu_etal_2018} the realizability-preserving property is guaranteed with a time step comparable to that of the forward Euler method applied to the explicit part of the scheme, but the resulting scheme performs poorly in the asymptotic diffusion limit.
Because of these challenges, we resort to first-order temporal accuracy, and propose IMEX-RK schemes that are convex-invariant with a time step equal to that of forward Euler on the explicit part, perform well in the diffusion limit, and reduce to a second-order SSP-RK scheme in the streaming limit (no collisions with the background material).

The realizability-preserving property of the DG-IMEX scheme depends sensitively on the adopted closure procedure.
The explicit update of the cell average can, after employing the simple Lax-Friedrichs flux and imposing a suitable CFL condition on the time step, be written as a convex combination.
Realizability of the updated cell average is then guaranteed from convexity arguments \cite{zhangShu_2010a}, provided all the elements in the convex combination are realizable.
Realizability of individual elements in the convex combination is conditional on the closure procedure (components of the Eddington tensor must be computed to evaluate numerical fluxes).
We prove that each element in the convex combination is realizable provided the moments involved in expressing the elements are moments of a distribution function satisfying the bounds implied by Fermi-Dirac statistics (i.e., $0\le f \le 1$).
For algebraic two-moment closures, which we consider, the so-called Eddington factor is given by an algebraic expression depending on the evolved moments and completely determines the components of the Eddington tensor.
Realizable components of the Eddington tensor demand that the Eddington factor satisfies strict lower and upper bounds (e.g., \cite{levermore_1984,lareckiBanach_2011}).
We discuss algebraic closures derived from Fermi-Dirac statistics that satisfy these bounds, and demonstrate with numerical experiments that the DG-IMEX scheme preserves realizability of the moments when these closures are used.
We also demonstrate that further approximations to algebraic two-moment closures for modeling particle systems governed by Fermi-Dirac statistics may give results that are incompatible with a bounded distribution and, therefore, unphysical.
The example we consider is the Minerbo closure \cite{minerbo_1978}, which can be obtained as the low occupancy limit of the maximum entropy closure of Cernohorsky \& Bludman \cite{cernohorskyBludman_1994}.

The paper is organized as follows.
In Section~\ref{sec:model} we present the two-moment model.
In Section~\ref{sec:realizability} we discuss moment realizability for the fermionic two-moment model, while algebraic moment closures are discussed in Section~\ref{sec:algebraicClosure}.
In Section~\ref{sec:dg} we briefly introduce the DG method for the two-moment model, while the (convex-invariant) IMEX time stepping methods we use are discussed in Section~\ref{sec:imex}.
The main results on the realizability-preserving DG-IMEX method for the fermionic two-moment model are worked out in Sections~\ref{sec:realizableDGIMEX} and \ref{sec:limiter}.
In Section~\ref{sec:limiter} we also discuss the realizability-enforcing limiter.
Numerical results are presented in Section~\ref{sec:numerical}, and summary and conclusions are given in Section~\ref{sec:conclusions}.
Additional details on the IMEX schemes are provided in Appendices.


\section{Experiments and results}
\subsection{Model training}
The LSTM network was trained by optimizing the cross-entropy loss between the true annotation distribution and the predicted annotation distribution. We used the Adam optimiser~\cite{Kingma2014} to train the parameters in the network, which had the best overall performances on sparse training data, according to~\cite{Ruder2016}.

To make the trained models less prone to overfitting, we applied dropout on the outputs of the word embedding layer, on the outputs of the LSTM encoding layer, as well as on the outputs of the recurrent layer. To reduce the space of hyper-parameter searching, we set $d_0$ to $500$, set $d_1$ to $64$, set a dropout rate of $0.2$ on the outputs of the word embedding layer, set a dropout rate of 0.3
on the outputs of the LSTM encoding layer, based on our former
neural network training experiences.

We initialized the word embedding matrix $W_E$ with the 500-dimension pre-trained Glove embeddings of Wikipedia data. The word embedding matrix was updated during the training process, to be adjusted for the clickbait detection scenario.

We implemented the LSTM network using Keras~\cite{Keras}.

\subsection{Results}
We trained the network on 2000 titles with 10 epochs. The dynamic of the accuracy of predictions is shown on figure~\ref{fig:results_training}.

\begin{figure}[H]
    \centering
  \begin{tikzpicture}
    \begin{axis}[
      xlabel={Epoch},
      ylabel={Accuracy},
      xmin=0,xmax=10,ymin=0,ymax=1
    ]
      \addplot
          coordinates {
              (0,0.718) [0]
              (1,0.734) [1]
              (2,0.785) [2]
              (3,0.802) [3]
              (4,0.800) [4]
              (5,0.817) [5]
              (6,0.824) [6]
              (7,0.841) [7]
              (8,0.845) [8]
              (9,0.853) [9]
          };
    \end{axis}
  \end{tikzpicture}
  \caption{Dynamic of the accuracy}
  \label{fig:results_training}
\end{figure}

The evaluation was performed on a MacBook Pro 2018. The Clickbait Detector achieved  an accuracy of $0.853$ (run time $\approx 30$ sec.) unofficially ranked top 20 in The Clickbait Challenge~\cite{Clickbait2016}. Thus, the detector achieved consistent and competitive performance across multiple evaluation metrics, a with very low computational cost.