\documentclass[conc-doc]{subfiles}

\begin{document}

	\chapter[Operators]{Operators}
	\label{ch:Operators}

Operators are an integral part of modern programming, Concurnas dedicates much of its syntax to supporting operators. Most of these operators are 'universal' and widely used outside of conventional programming, such as those concerning arithmetic and basic mathematics, some are more specific to programming in general such as bit shift related operators and some are unique to modern programming languages such as the null safety related operators.

Concurnas also dedicates much support to operator overloading, this helps facilitate the construction of domain specific languages within Concurnas.

\section{Supported Operators}

Concurnas supports the following extensive set of operators:

{\fontsize{3.5pt}{0pt}\selectfont
\begin{longtable}[hbt!]{| l | l | l | l | l | l | l | l |}

	\hline
	Class&Operator&Token&Description&Example&Input types&Return type&Associativity\\
	\hline
	\endhead

	\hline
	\endfoot
Sizeof&Sizeof&sizeof&Calculate the off heap size of the operand&sizeof "myString" => 128&Object&Long&Left to right\\ \hline
Contains& In& in, not in& Check if the left hand operand is in the right hand operand& 1 in [1 2 3 4 5] => true& Any Array or Collection of Component type& Boolean& Left to right\\ \hline
Not& Not& not& Flips boolean value of right hand operand& not true => false& Boolean& Boolean& Right to left\\ \hline
Postfix& Increment& ++& Increments operand by 1& expr++& Integral& Integral& Left to right\\
& Decremement& --& Decrements operand by 1& expr--& Integral& Integral& Left to right\\ \hline
Prefix& Increment& ++& Increments operand by 1& ++epxr& Integral& Integral& Right to left\\
& Decremement& --& Decrements operand by 1& --expr& Integral& Integral& Right to left\\
& Positive& +& Positive value of operand& +10 => 10& Integral& Integral& Right to left\\
& Negative& -& Negative value of operand& -10 => -10& Integral& Integral& Right to left\\ \hline
Multiplicative& Multiplication& *& Multiplies left and right hand side operands& 2*2 => 4& Integral& Integral& Left to right\\
& Power& **& Raises left operand to the power of right operand& 3**2 => 9& Integral& Integral& Right to left\\
& Division& /& Divides left hand operand by right hand operand& 10/3 => 3& Integral& Integral& Left to right\\
& Modulus& mod& The remainder of the division operator applied to the operands as above& 10 mod 3 => 1& Integral& Integral& Left to right\\ \hline
Additive& Addition& +& Adds the left and right hand side operands& 2 + 2 => 4, "hi" + "there" => "hi there"& Integral or String& Integral or String& Left to right\\
& Subtraction& -& Subtracts the right hand operand from the left hand operand& 2 - 4 => -2& Integral& Integral& Left to right\\ \hline
Bitshift& Left shift& <<& The left operands value is moved left by the number of bits specified by the right operand.& 0b001 << 2 => 4 (0b100)& Integral& Integral& Left to right\\
& Right Shift& >>& The left operands value is moved right by the number of bits specified by the right operand.& 0b100 >> 2 => 7 (0b111)& Integral& Integral& Left to right\\
& Unsigned right shift& >>>& As above but shifted values are filled with zeros& 0b100 >> 2 => 1 (0b001)& Integral& Integral& Left to right\\
& Complement& comp& Complement of a single expression& comp 0b0001 => 14 (0b1110)& Integral& Integral& Right to left\\ \hline
Relational& Less than& <& Check if the left hand operand is less than the right hand operand& 2 < 4 => true& Integral& Integral& Left to right\\
& Greater than& >& Check if the left hand operand is greater than the right hand operand& 2 > 4 => false& Integral& Integral& Left to right\\
& Less than or equal& <==& Check if the left hand operand is less than or equal to the right hand operand& 2 <== 2 => true& Integral& Integral& Left to right\\
& Greater than or equal& >==& Check if the left hand operand is greater than or equal to the right hand operand& 2 >== 2 => true& Integral& Integral& Left to right\\ \hline

Instance of& Instance of& is, isnot, is not& Check if the left handoperand is (or is not) a subtype of the right hand type operand& expr is not Object => false& Object, Type& Boolean& Left to right\\ \hline

Cast& Cast& as& Cast left operand to be type of right hand type operand& expr as MyClass => expr is now of type MyClass& Object, Type& Object& Left to right\\ \hline
Equality& Structurally equal& ==& Check if the value of the left and right hand operands are equal& 10 == 10 => true& Any& Boolean& Left to right\\
& Structurally not equal& <>& Check if the value of the left and right hand operands are not equal& 10 <> 9 => true& Any& Boolean& Left to right\\
& Referential equality& \&==& Check if the object on the left and right hand operands are the same& Integer(1) \&== Integer(1) => false& Any& Boolean& Left to right\\
& Referentially not equal& \&<>& Check if the object on the left and right hand operands are not the same& Integer(1) \&<> Integer(1) => true& Any& Boolean& Left to right\\ \hline
Bitwise& Bitwise and& band& Compares each bit of the operands and returns 1 for each if they are both 1& 0b110 band 0b101 => 0b100& Integral& Integral& Left to right\\
& Bitwise or& bor& Compares each bit of the operands and returns 1 for each if either equals 1& 0b110 bor 0b101 => 0b111& Integral& Integral& Left to right\\
& Bitwise exclusive or& bxor& Compares each bit of the operands and returns 1 for each if either but not both equals 1& 0b110 bxor 0b101 => 0b011& Integral& Integral& Left to right\\ \hline
Logical and& and& and& Check if the left and right hand operands both resolve to true& true and false => false& Boolean& Boolean& Left to right\\ \hline
Logical or& or& or& Check if either the left and right hand operands both resolve to true& true or false => true& Boolean& Boolean& Left to right\\ \hline

Ternary& If expression& x if y else z& Return x operand if y operand resolves to true otherwise return z operand& 8 if true else 9 => 8& Any, Boolean, Any& Any& Left to right\\ \hline

Invoke& Invoke& obj(args?) & Call the invoke method on object with provided methods&afunc(); afunc2(1, 'arg2')& Object& Any& Left to right\\ \hline

Null Safety&Not null assertion&??&Throws a Null Pointer Exception if left hand side is null, otherwise returns no null type&maybeNull??&Object?&Object& Left to right\\
&Elvis operator\footnote{So called as the token looks like the emoticon for Elvis Presley}&?:&Returns left hand side if it is not null, otherwise the right hand side expression will be evaluated and returned&maybeNull?:otherwise&Object?&Object& Left to right\\ \hline

Assignment& Assignment& =& Vanilla assignment& a = 10& Integral& Integral& Right to left\\ \hline

Compound Assignment& Addition Assign& +=& Apply addition operator to left and right operands and set value to left operand& a += 10& Integral or String& Integral or String& Right to left\\
& Subtract Assign& -=& As above but subtraction& a -= 10& Integral& Integral& Right to left\\
& Mutliply Assign& *=& As above but multiplication& a *= 2& Integral& Integral& Right to left\\
& Divide Assign& /=& As above but division& a /= 13& Integral& Integral& Right to left\\
& Power Assign& **=& As above but power& a **= 2& Integral& Integral& Right to left\\
& Mod Assign& mod=& As above but mod& a mod= 15& Integral& Integral& Right to left\\
& Bitwise And Assign& band=& As above but bitwise and& a bor= 16& Integral& Integral& Right to left\\
& Bitwise Or Assign& bor=& As above but bitwise or& a bor= 17& Integral& Integral& Right to left\\
& Bitwise Xor Assign& bxor=& As above but bitwise xor& a bxor= 17& Integral& Integral& Right to left\\
& Complement Assign& comp=& As above but complement& a comp= 19& Integral& Integral& Right to left\\
& Left shift Assign& <<=& As above but left shift& a <<= 20& Integral& Integral& Right to left\\
& Right Shift Assign& >>=& As above but right shift& a >>= 21& Integral& Integral& Right to left\\
& Unsigned right shift Assign& >>>=& As above but unsigned right shift& a >>>= 22& Integral& Integral& Right to left\\
\end{longtable}
}

The majority of these operators operate upon primitive or boxed primitive types. The integral (or 'numerical') types are defined as: \lstinline{int}, \lstinline{long}, \lstinline{short}, \lstinline{char} and \lstinline{byte} and their equivalent boxed object variants: \lstinline{Integer}, \lstinline{Long}, \lstinline{Short}, \lstinline{Character} and \lstinline{Byte} respectfully.

\subsection{Sizeof}
The \lstinline{sizeof} operator is designed for working with off heap memory. It provides us an indication of the size in bytes that any object (including arrays) will consume when serialized into a byte format as par the scheme referenced within its optional qualifier. For example, when working on the gpu we can use a qualifier as follows:

\begin{lstlisting}
leAr = [1 2 3 4 5 6 7 8 9 10]
gpusize = sizeof<gpus.gpusizeof> leAr//size of leAr on the gpu
\end{lstlisting}

If no qualifier is provided then the default off heap serialization built into Concurnas is used:

\begin{lstlisting}
leAr = [1 2 3 4 5 6 7 8 9 10]
gpusize = sizeof leAr//size of leAr as par default scheme
\end{lstlisting}

\subsubsection{Defining a sizeof qualifier}
If we were to design a customized object serialization scheme, it can be beneficial to implement a sizeof qualifier such that clients of our custom scheme are able to know the size in bytes that objects will consume if serialized via our scheme. This can be easily achieved by defining a function taking a single Object as input and returning a value of type \lstinline{int}. For example:

\begin{lstlisting}
def sizeofCustomScheme(some Object) int{
	//some logic...
	return 1//in this example every object is 1 byte large
}
\end{lstlisting}

This can then be used via qualification of the sizeof operator as par above.

\subsection{Contains}
The contains class of operator consists of two variants, \lstinline{in} and \lstinline{not in}. \lstinline{in} can be used with common data collection structures including: lists, sets and arrays to test to see if a value on its left hand side is within the expression of one of the aforementioned data structures on the right hand side. If it's present a \lstinline{boolean} value of \lstinline{true} is returned, otherwise \lstinline{false}. \lstinline{not in} returns \lstinline{true} if the value on the left is not present within the data structure.

\begin{lstlisting}
alist = [1,2,3,4,5]
within = 2 in alist
\end{lstlisting}

\lstinline{in} may be used in a similar way with maps in order to examine whether a key is present within the map. For example:

\begin{lstlisting}
amap = {2 -> 23, 3 -> 67. 1 -> 55}
within = 2 in amap
\end{lstlisting}

The \lstinline{in} keyword has special meaning when used within the context of an iterator style for loop, this is documented in the \hyperref[subsec:IteratorStyleFor]{Iterator style for} section.

\subsubsection{Supporting contains}
Any class may support the operator \lstinline{in} by providing a contains method, this is discussed in more detail in the \hyperref[sec:OperatorOverloading]{operator overloading section}.

\subsection{Not}
The \lstinline{not} keyword simply flips the booleanarity of a value of \lstinline{boolean} type. \lstinline{true} becomes \lstinline{false} and vice versa.

\subsection{Postfix}
Concurnas supports the usual set of postfix operators one would expect from a modern programming language. Namely the increment \lstinline{++} and decrement \lstinline{--} operators appearing on the right hand side of an integral expression consisting of a variable, list or array reference. These operators are applied in place. The operators may be used in a place where a value is expected to be returned from it, in which case the previous value of the variable prior to the increment or decrement operator being applied will be returned:

\begin{lstlisting}
avar = 10
anarray = [1 2 3 4 5]

avar++
anarray[0]--

prevvar = avar++
prevarray = anarray[0]--
\end{lstlisting}

\subsection{Prefix}
The prefix operators behave in a similar manner as the postfix operators though with the addition of the negation: \lstinline{-} operator. Unlike the others, the negation: \lstinline{-} operator is not applied in place and will always return a value. The operators may be used in a place where a value is expected to be returned from it, in which case the value of the variable post operator application will be returned:

\begin{lstlisting}
avar = 10
anarray = [1 2 3 4 5]

++avar
--anarray[0]

newvar = ++avar
newarray = --anarray[0]

anothervar = 10
negative = -anothervar//negative == -10
\end{lstlisting}

\subsection{Multiplicative}
Concurnas supports the standard set of multiplicative operators which can act upon two, potentially differing, integral types, multiplication: \lstinline{*}, division: \lstinline{/}, power: \lstinline{**} and modulus: \lstinline{mod}. For example:

\begin{lstlisting}
mul = 3*2 //==6
div = 12/2 //==6
pow = 3**2 //==9
pow = 9**-2 //square root
modu = 10 mod 4 //==2
\end{lstlisting}

Attempting to divide by zero with two non floating point (either \lstinline{float} or \lstinline{double}) values will result in an exception of type \lstinline{java.lang.ArithmeticException} being thrown. Attempting to divide by zero with at least one floating point value will result in: \lstinline{Infinity} being returned. \lstinline{0./0.} will resolve to \lstinline{NaN}.

In situations where the left and right types of the multiplicative operator differ, the more general type shall be used for the return type. For example:

\begin{lstlisting}
div1 = 13/2f //==6.5 (float)
div2 = 13/2. //==6.5 (double)
div3 = 13f/2. //==6.5 (double)
mulong = 100*10L //1000L (long)
mulong = 100L*10. //1000. (double)
\end{lstlisting}

\subsubsection{Division and power gotacha}
Often new and even experienced programmers will come across the following sort of problem:
\begin{lstlisting}
assert 13/2 == 6.5 //fails!
\end{lstlisting}

The above fails because \lstinline{13/2} for integers resolves to \lstinline{6} and not \lstinline{6.5}. Perhaps this is the answer desired, but to obtain the 'correct answer' of \lstinline{6.5}, what we are looking for is a floating point calculation and this can be achieved by casting either of the arguments to the division operator to a floating point type, either float or double:

\begin{lstlisting}
assert 13./2 == 6.5 //expected asnwer
\end{lstlisting}

\subsection{Additive}
Concurnas supports addition: \lstinline{+} and subtraction \lstinline{-}. These are straightforward and the rules concerning generalization of numerical types as par the multiplicative operators above apply. Examples:

\begin{lstlisting}
addition = 1+1
subtraction = 1-1
\end{lstlisting}

Additionally, the addition operator \lstinline{+} can be used for String concatenation. This is described in more detail in the \hyperref[subsec:StringConcat]{The String concatenation operator \lstinline!+!} section.

\subsection{Bitshift}
Concurnas supports bit shift operators for integral types. They operate on a bit pattern, given by the left hand operand and a number of positions to shift by the right hand operand.

\begin{itemize}
	\item \lstinline{<<} - Left shift. Shifts a bit pattern to the left.
	\item \lstinline{>>>} - Unsigned right shift. Shifts a bit pattern to the right. Shifts a zero to the leftmost position.
	\item \lstinline{>>} - Right shift. Shifts a bit pattern to the right. Leftmost bit is shifted contingent on sign extension.
\end{itemize}

Example:
\begin{lstlisting}
def shifty(){
	a = 17
	x1 = a << 2
	x2 = a >> 2
	x3 = a >>> 2
	[x1, x2, x3]
}

shifty() //resolves to => [68, 4, 4]
\end{lstlisting}

\subsection{Relational}
The main relational operators in Concurnas are less than: \lstinline{<}, greater than: \lstinline{>}, less than or equal:\lstinline{<==} and greater than or equal: \lstinline{>==}. These operate upon two integral types. And return a \lstinline{boolean} type. Examples:

\begin{lstlisting}
lt = 1 < 2
gt = 3 > 2
lteq = 1 <== 2
gteq = 3 ==> 2
\end{lstlisting}

\subsection{Instance of and Cast}
The instance of or cast operators may not be overloaded. They are covered in more detail in the\hyperref[ch:castAndcheck]{Casting and Checking Types} chapter.

\subsection{Equality}
Concurnas supports two variants of equality, structural equality (as: equal: \lstinline{==} and not equal: \lstinline{<>}) and referential equality (denoted by prefixing the equality operator with an ampersand: \lstinline{&}). The structural equality operators may operate upon any type, whereas the referential quality operators may only operate upon Objects. For all operator variants, they return a boolean value indicating equality. Let's look at some examples of structural equality:

\begin{lstlisting}
eq = 10 == 10 //true
eq2 = 10 <> 12 //true
eq3 (1>3) == false //resolves to true
\end{lstlisting}

When it comes to structural equality for objects this is achieved by calling the equals method on the left hand side object and passing it the object on the right hand side as an argument. Note that in Concurnas this equality method is automatically created for all Objects and it resolves to provide structural equality, this behaviour can be user overridden to provide different behaviour. More details of this can be found in the \hyperref[autoGeneqAndHash]{Automatically generated equals and hashcode methods} section. Examples:

\begin{lstlisting}
class Person(name String)

d1 = Person('dave')
d2 = Person('dave')
f3 = Person('freddy')

assert d1 == d2 //struturally equal
assert d1 <> f3 //struturally not equal
assert d1 &== d1 //object is referentially equal to itself!
assert d1 &<> d2 //d1 and d2 though structurally equal (above) are not referentially equal
\end{lstlisting}

\subsection{Bitwise operators}
The major bitwise operators take two integral types as input. The following operators are supported:
\begin{itemize}
	\item \lstinline{band} - bitwise and
	\item \lstinline{bor} - bitwse or
	\item \lstinline{bxor} - bitwise exclusive or
\end{itemize}

These operators are commonly used in order to apply masks. Example:

\begin{lstlisting}
def pprint(xx int) => '0x' + String.format("%8s", Integer.toBinaryString((xx+256) % 256)).replace(" ", "0")

value = 0b00010101
bitmask = 0b00000001

pprint(value band bitmask) // -> 0x00000001
pprint(value bor bitmask)// -> 0x00010101
pprint(value bxor bitmask)// -> 0x00010100
\end{lstlisting}

\subsubsection{Complement}
The \lstinline{comp} operator can be used on an integral type in order to derive the complement of a single expression. Every \lstinline{0} is flipped to a \lstinline{1} and vice versa. Example:

\begin{lstlisting}
orig byte = 0b00000011
complement= comp orig

Integer.toBinaryString((complement+256) % 256) // resolves to: '11111100' - which is the complement of the input byte.
\end{lstlisting}

\subsection{Logical and/or}
Concurnas supports the logical \lstinline{and} and \lstinline{or} operators which can be used in order to chain together \lstinline{boolean} expressions. Naturally, both arguments to these operators must be of \lstinline{boolean} type. More then one \lstinline{and} or \lstinline{or} may be chained together. The operators both return \lstinline{boolean} values. Examples:

\begin{lstlisting}
orand1 = 2 == 3 or 3>1
orand2 = 2 == 3 or 3>1 or 22>1 or 3 < 9
orand3 = 2>1 and 4>1
\end{lstlisting}

\subsubsection{Short circuiting}
Short circuiting is a logical optimization in which the second argument to an operator is executed or evaluated only if the first argument does not suffice to determine the value of the expression. This sometimes catches people out when they expect all arguments of an operator to be evaluated.

For a chain of \lstinline{or} operators, evaluated left to right, as soon as one argument evaluates to \lstinline{true}, the value \lstinline{true} is returned (otherwise \lstinline{false}), similarly for the \lstinline{and} operator, evaluated left to right, as soon as an argument evaluates to \lstinline{false}, \lstinline{false} is returned (otherwise \lstinline{true}).

\begin{lstlisting}
def eval1(toRet boolean) => toRet
def eval2(toRet boolean) => toRet
def toCall(toRet boolean) => toRet

shortcir = eval1(false) or eval1(true) or toCall(true)//toCall will never be called!
shortcir = eval1(true) and eval1(false) and toCall(true)//toCall will never be called!
\end{lstlisting}

\subsection{Ternary}
The Ternary operator \lstinline{x if test else z} can be thought of as a handy shorthand for the slightly more verbose: \lstinline!if(test){ x }else{ z }! (in fact, under the hoot the Ternary operator is translated into this more verbose form). \lstinline{x} and \lstinline{z} must both return a value (of any type) and \lstinline{test} must resolve to a value of \lstinline{boolean} type. Example:

\begin{lstlisting}
def test() => true

result = 12 if test() else 99
\end{lstlisting}

\subsection{Invoke}
Concurnas allows an \lstinline{invoke} method to be defined for all objects, this permits the following syntax to be used in order to call this \lstinline{invoke} method as an operator, with optional arguments:

\begin{lstlisting}
class FormatPlus{
	def invoke(a int, b int) => "{a} + {b}"
}

fmt = FormatPlus()
fmt(12, 13)//returns: "12 + 13"
\end{lstlisting}

This can occasionally be useful tool to use when defining domain specific languages.

\subsection{Null safety}
The null safety operators are documented in detail in the \hyperref[ch:nullsafe]{Null Safety} section.

\section{Assignment}
Variable assignment is covered in detail in the \hyperref[ch:assignment]{Variable assignment} chapter. The assignment operator may be overloaded, this is described in the \hyperref[subsec:overloadassignmentop]{Overloading the assignment operator} section, in the case of an overloaded assignment operator being defined for a type, the escaped assign of: \lstinline{\\=} will suppress this behaviour when a value is assigned.

\section{Compound assignment}
Here we concern ourselves with compound assignment applied to a variable which has already been defined. These are: \lstinline{+=}, \lstinline{-=}, \lstinline{*=}, \lstinline{/=}, \lstinline{**=}, \lstinline{mod=}, \lstinline{or=}, \lstinline{and=}, \lstinline{<<=}, \lstinline{>>=}, \lstinline{>>>=}, \lstinline{band=}, \lstinline{bor=}, \lstinline{bxor=}. Taking the addition assignment operator, \lstinline{+=} as an example, the following two statements are functionally identical:

\begin{lstlisting}
a1 = a2 = 10

a1 += 1
a2 = a2 + 1

assert a1 == a2
\end{lstlisting}

That is to say, \lstinline{a1 += 1} is essentially shorthand for: \lstinline{a1 = a1 + 1}.

The compound assignment operators may be applied to array reference operations as follows:

\begin{lstlisting}
a1 = [1 2 3]

a1[0] += 1

assert a1 == [2 2 3]
\end{lstlisting}

Again, \lstinline{a1[0] += 1} is essentially shorthand for: \lstinline{a1[0] = a1[0] + 1}.

\subsection{Parentheses}
In Concurnas, parentheses can be used or order disambiguate expressions composed of multiple operators. They may also be used in a "no operation" capacity in order to make code easier to read. For example:

\begin{lstlisting}
orand4 = not (2>1 and 4>1)
\end{lstlisting}

\section{Operator Overloading}
\label{sec:OperatorOverloading}
Concurnas provides a mechanism by which the aforementioned operators can be supported for object types in addition to the primitives (and boxed versions thereof) above. This functionality can be extremely useful when implementing Domain Specific Languages. The following operators can be overloaded:

{\tiny
	\begin{longtable}[hbt!]{| l | l | l | l | l | l | l | }

		\hline
		Class&Operator&Normal Token&Method name&Alt Name&Type overloaded&Notes\\
		\hline
		\endhead

		\hline

		\endfoot
		Assign&Assignment&=&assign&=&Left&\bettershortstack{Use \= variant of assign\\to avoid calling\\overloaded operator}\\
		&Unassign& &unassign& &Left&\bettershortstack{Where variable of type x implements\\ unassign, use x: to avoid calling unassign operator}\\ \hline
		Compound Assign&Addition Assign&+=&plusAssign&+=&Left&\\
		&Negation Assign&-=&minusAssign&-=&Left&\\
		&Multiply Assign&*=&mulAssign&*=&Left&\\
		&Divide Assign&/=&divAssign&/=&Left&\\
		&Power Assign&**=&powAssign&**=&Left&\\
		&mod Assign&mod=&modAssign&mod=&Left&\\
		&or Assign&or=&orAssign&or=&Left&\\
		&and Assign&and=&andAssign&and=&Left&\\
		&left shift Assign&<<=&leftShiftAssign&<<=&Left&\\
		&right shift Assign&>>=&rightShiftAssign&>>=&Left&\\
		&unsigned right shift Assign&>>>=&rightShiftU&>>>=&Left&\\
		&bitwise and Assign&band=&bandAssign&band=&Left&\\
		&bitwise or Assign&bor=&borAssign&bor=&Left&\\
		&bitwise xor Assign&bxor=&bxorAssign&bxor=&Left&\\ \hline
		Not&Not&not&not& &Unary&\\ \hline
		Postfix&Increment&++&inc&++&Unary&\\
		&Decremement&--&dec&--&Unary&\\ \hline
		Prefix&Increment&++&inc&++&Unary&\\
		&Decremement&--&dec&--&Unary&\\
		&Positive&+&plus&+&Unary&No arguments specified\\
		&Negative&-&neg&-&Unary&No arguments specified\\
		&Complement&comp&comp& &Unary&\\ \hline
		Multiplicative&Multiplication&*&mul&*&Left&\\
		&Power&**&pow&**&Left&\\
		&Division&/&div&/&Left&\\
		&Modulus&mod&mod& &Left&\\ \hline
		Additive&Addition&+&plus&+&Left&\\
		&Subtraction&-&minus&-&Left&\\ \hline
		Bitshift&Left shift&<<&leftShift&<<&Left&\\
		&Right Shift&>>&rightShift&>>&Left&\\
		&Unsigned right shift&>>>&rightShiftU&>>>&Left&\\ \hline
		Relational&Less than&<&compareTo& &Left&a.compareTo(b) < 0\\
		&Greater than&>&compareTo& &Left&a.compareTo(b) > 0\\
		&Less than or equal&<==&compareTo& &Left&a.compareTo(b) <== 0\\
		&Greater than or equal&>==&compareTo& &Left&a.compareTo(b) >== 0\\ \hline
		Equality&Structurally equal&==&equals& &Left&a.equals(b)\\
		&Structurally not equal&<>&equals& &Left&not a.equals(b)\\ \hline
		Bitwise&Bitwise and&band&band& &Left&\\
		&Bitwise or&bor&or& &Left&\\
		&Bitwise exclusive or&bxor&bxor& &Left&\\ \hline
		Logical and&and&and&and& &Left&\\ \hline
		Logical or&or&or&or& &Left&\\ \hline
		Invoke&Invoke&a()&invoke& &Left&Any number of arguments may be specified\\ \hline
		Lists, Arrays, Maps&Get&a[y]&get& &Left&\\
		&Put&a[y] = z&put& &Left&\\
		&Sublist&a[y1 ... y2]&sub& &Left&a.sub(y1, y2)\\
		&Sublist from&a[y1 ...]&subfrom& &Left&a.subfrom(y1)\\
		&Sublist to&a[... y2]&subto& &Left&a.subto(y2)\\
		&Put sublist&a[y1 ... y2] = z&subAssign& &Left&a.subAssign(y1, y2, z)\\
		&Put sublist from&a[y1 ...] = z&subfromAssign& &Left&a.subfromAssign(y1, z)\\
		&Put sublist to&a[... y2] = z&subtoAssign& &Left&a.subtoAssign(y2, z)\\
		&In&in&contains& &Right&b.contains(a)\\
		&Not in&not in&contains& &Right&not b.contains(a)

	\end{longtable}
}

\subsection{Implementing and using overloaded operators}
Overloaded operators operate upon the left hand element of an expression unless it is unary where there is only one expression the operator is being applied to, or for the \lstinline{int} and \lstinline{not in} operators where the right hand expression must have the relevant method implemented. The left hand element must support the operator being invoked. For non alphanumerical named operators (e.g. \lstinline{+}, \lstinline{**} etc) the raw alphanumerical operator token may be defined as a method name, or it's alternative longhand name may be used (\lstinline{plus} for \lstinline{+}, \lstinline{mul} for \lstinline{*} etc).

\begin{lstlisting}
class Complex(real double, imag double){
	def +(other Complex) => new Complex(this.real + other.real, this.imag + other.imag)
	def +(other double) => new Complex(this.real + other, this.imag)
	def +=(other Complex) => this.real += other.real;  this.imag += other.imag
	def +=(other double) => this.real += other
	override toString() => "Complex({real}, {imag})"
}

c1 = Complex(2, 3)
c2 = c1@
c3 = c1@
c4 = Complex(3, 4)

result1 = c1 + c4
result2 = c1 + 10.
c2 += c4 //compound plus assignment
c3 += 10.//compound plus assignment

//result1 == Complex(5.0, 7.0)
//result2 == Complex(12.0, 3.0)
//c2 == Complex(5.0, 7.0)
//c3 == Complex(12.0, 3.0)
\end{lstlisting}

Above we see the plus and compound plus assignment operator have been overloaded for the object class: Complex. Note that operator overloading methods themselves may be overloaded with differing argument types(just like regular methods).

\subsection{Operator overloading via extension functions}
It's possible to implement operator overloading via use of extension functions. this is documented in the \hyperref[sec:extfunAsOpOver]{Extension functions as operator overloaders} section.

\subsection{Overloading the assignment operator}
\label{subsec:overloadassignmentop}
The assignment operator, \lstinline{=} can be overloaded. Example:
\begin{lstlisting}
class AssignOPOverload(value int){
	def =(a int){ value = a; }

	override toString() => "AssignOPOverload: {value}"
}

obj= new AssignOPOverload(100)
obj= 66
//thing == AssignOPOverload: 66
\end{lstlisting}

If the overloaded assign method returns a value then this will be ignored. If you wish to suppress invoking the assign operator then using the escaped assign of: \lstinline{\\=} will suppress this behaviour, and will cause the assignment to behave a normal, assigning whatever is on the right hand side to the variable expressed on the left hand side:
\begin{lstlisting}
class AssignOPOverload(value int){
	def =(a AssignOPOverload){ value = a.value + 10000; }

	override toString() => "AssignOPOverload: {value}"
}

inst1 = new AssignOPOverload(100)
inst2 = new AssignOPOverload(100)

inst1 = new AssignOPOverload(22)
inst2 \= new AssignOPOverload(22) //bypass overloaded = operator

//inst1  == AssignOPOverload: 10022
//inst2  == AssignOPOverload: 22
\end{lstlisting}

Overloading of the assignment operator is used to great effect with off heap memory and gpu memory interaction.

\subsection{Unassign}
Just as we can overload the assignment operator, so too can be implicitly overload the 'unassignment operator', consisting of a zero argument method named \lstinline{unassign} returning any non void type. This is best illustrated with an example:
\begin{lstlisting}
class MyUnassignable{
	myvar int
	def assign(anint int) => myvar = anint;;
	def unassign() => myvar
}

inst = MyUnassignable()
inst  = 56
res = inst

//res == 56
\end{lstlisting}

If we wish to suppress the unassignment operation this can be achieved by using the \lstinline{:} operator as follows:

\begin{lstlisting}
class MyUnassignable{
	myvar int
	def assign(anint int) => myvar = anint;;
	def unassign() => myvar
	override toString() => 'MyUnassignable {myvar}'
}

inst = MyUnassignable()
inst  = 56
res1 = ''+ inst
res2 = '' + inst: //suppress calling of unassign()
res3 = inst:tostring() //suppress calling of unassign()

//res1 == '56'
//res2 == 'MyUnassignable 56'
//res3 == 'MyUnassignable 56'
\end{lstlisting}

If we wish to create a ref to a variable of type implementing the \lstinline{unassign()} method, and we wish to avoid 'unassigning' it then we must use an extra \lstinline{:}.

\begin{lstlisting}
class MyUnassignable{
	myvar int
	def assign(anint int) => myvar = anint;;
	def unassign() => myvar
	override toString() => 'MyUnassignable {myvar}'
}

inst = MyUnassignable()
inst  = 56

ref MyUnassignable: = inst:: //ordinarily we'd just use 'inst:' to create a ref
\end{lstlisting}

Overloading of unassignment is used to great effect with lazy variables.

\subsection{Assignment operators}
If there is an object returned from an overloaded assignment operator which happens to be a ref type, then Concurnas will await for the assignment on the ref type to take place before continuing with execution. similarly, if the operator overload method being invoked is tagged with the \lstinline{@com.concurnas.lang.DeleteOnUnusedReturn} annotation, then delete will be called on the object returned before continuing with execution.

This applies to the following assignment operators:
\begin{itemize}
	\item \textbf{The assignment operator:} \lstinline{=}
	\item \textbf{The in place assignment operators:} \lstinline{+=, -=, *=, /=, **=, mod=, band=, bor=, bxor=, comp=, <<=, >>=, >>>=}
	\item \textbf{The sublist assignment operators:} \lstinline{[a ... b ] = z, [a ... ] = z, [ ... b ] = z}
\end{itemize}

The escaped assignment operator: \lstinline{\=} is excluded from this behaviour.

\end{document}


\section{Fuentes de apoyo y consulta:}
\subsection{Fuentes de apoyo y consulta}
\subsubsection{B\'{a}sicas}

\begin{itemize}[itemsep=0em]

\item{T.\ {\sc Hastie}, R.\ {\sc Tibshirani} \& J.\ {\sc Friedman}: {\em
      The elements of statistical learning: data mining, inference,
      and prediction}. Springer; 2nd edition, 2016.}

\item{R.S.\ {\sc Michalski}, J.G.\ {\sc Carbonell} \& T.M.\ {\sc
      Mitchell}, eds.: {\em Machine learning: An artificial
      intelligence approach}. Springer Science \& Business Media,
    2013.}

\item{I.H.\ {\sc Witten}, et al.: {\em Data Mining: Practical machine learning
      tools and techniques}. Morgan Kaufmann, 2016.}

\item{S.\ {\sc Marsland}: {\em Machine learning: an algorithmic
      perspective}. CRC press, 2015.}

\end{itemize}

\input{compl.tex}


\subsection{Atom Transition Moments}\index{Transition!dipole moments}\index{Polarizability!atomic transition}
\index{Dipole!transition}\index{Exponents!transition dipole}
\index{Polarizability}\label{oscil}
\index{Oscillator}
A system can go from the ground state to an excited  state as the result of the
absorption of a photon.  The probability of this happening, $\kappa$, is
given\footnote{\samepage Wilson Decius and Cross,  ``Molecular Vibrations'', p
163, McGraw-Hill (1955)} in terms of the  oscillator integral:
\begin{eqnarray}
<\!\Psi_{0}|\stackrel{\rightharpoonup}{r}|\Psi_{*}\!> \label{os1},
\end{eqnarray}
by
$$
\kappa = \frac{8\pi^3}{3ch}\nu_{n'n''}(N_{n'}-N_{n''})
<\!\Psi_{0}|\stackrel{\rightharpoonup}{r}|\Psi_{*}\!>^2 .
$$
For electronic photoexcitations, $\Psi_A$ are state functions:
$$
\Psi_A = \sum_ic_i\Psi_i,
$$
and the $\Psi_i$ are microstates; see p.~\pageref{sd} for a
definition of microstates.
\subsubsection*{Some Mathematical tools}
In order to evaluate \ref{os1}, a property of integrals of the type:
$$
<\!\psi_{i}|\stackrel{\rightharpoonup}{r}|\psi_{j}\!>
$$
will be used several times.  This property is:
$$
<\!\psi_{i}|\stackrel{\rightharpoonup}{r}|\psi_{i}\!> = 0.
$$
From this, it follows that, if
$$
<\!\psi_{j}|\stackrel{\rightharpoonup}{r}|\psi_{i}\!> \neq 0,
$$
then
$$
<\!\psi_{i}|\stackrel{\rightharpoonup}{r}|\psi_{j}\!> =
-<\!\psi_{j}|\stackrel{\rightharpoonup}{r}|\psi_{i}\!> .
$$
To prove this relationship, consider the integral
$$
<\!(\psi_i+\psi_j)|\stackrel{\rightharpoonup}{r}|(\psi_i+\psi_j)\!>.
$$
Obviously, this integral has a value of zero, therefore
$$
<\!\psi_i|\stackrel{\rightharpoonup}{r}|\psi_i\!>  +
<\!\psi_j|\stackrel{\rightharpoonup}{r}|\psi_i\!>  +
<\!\psi_i|\stackrel{\rightharpoonup}{r}|\psi_j\!>  +
<\!\psi_j|\stackrel{\rightharpoonup}{r}|\psi_j\!>  =0.
$$
In this expression, the first and fourth terms are obviously zero, therefore
$$
<\!\psi_j|\stackrel{\rightharpoonup}{r}|\psi_i\!>  =
-<\!\psi_i|\stackrel{\rightharpoonup}{r}|\psi_j\!> .
$$

\subsubsection{Evaluation of Transition Dipole}

\begin{table}
\caption{\label{transx} ``$x$" Transition Integrals}
\begin{center}
\begin{tabular}{l|ccccccccc} \hline
& $s$  &  $p_x$  &  $p_y$  &  $p_z$  &  $d_{x^2-y^2}$  & $d_{xz}$  &
$d_{z^2}$  &  $d_{yz}$  &  $d_{xy}$ \\ \hline
$s$ & X$_A$\\
$p_x$ & sp & X$_A$\\
$p_y$  & 0 & 0 & X$_A$ \\
$p_z$  & 0 & 0 & 0 & X$_A$\\
$d_{x^2-y^2}$ & 0 & pd & 0 & 0 & X$_A$\\
$d_{xz}$      & 0 & 0 & 0 & pd & 0 & X$_A$\\
$d_{z^2}$     & 0 & -$\frac{1}{\sqrt{3}}$pd & 0 & 0 & 0 & 0 & X$_A$\\
$d_{yz}$      & 0 & 0 & 0 & 0 & 0 & 0 & 0 & X$_A$\\
$d_{xy}$      & 0 & 0 & pd & 0 & 0 & 0 & 0 & 0 & X$_A$\\  \hline

\end{tabular}\\
\hspace{-0.3in}Note: X$_A$ = $<\! \phi_{\lambda}|\stackrel{\rightharpoonup}{x}|\phi_{\lambda}\! >$;
sp = $<\! ns|\stackrel{\rightharpoonup}{r}|np\! >$; pd = $<\! np|\stackrel{\rightharpoonup}{r}|nd\! >$ (see below).
\end{center}
\end{table}

The probability, $B_{0\rightarrow *}$, that a photon will be absorbed by a system that has a
ground state $\Psi_0$ and an excited state $\Psi_*$ separated by an energy $\epsilon$ when
irradiated by an energy density $\rho_{\epsilon}$
is given by
$$
B_{0\rightarrow *} = \frac{2\pi}{3\hbar^2}|R_{0*}|^2\rho_{\epsilon},
$$
in which
$$
|R_{0*}|^2 = |X_{0*}|^2 + |Y_{0*}|^2 + |Z_{0*}|^2.
$$

$X_{0*}$ is the matrix element for the $x$ component of the dipole moment:
$$
X_{0*} = \int \Psi_0|e\sum_j \stackrel{\rightharpoonup}{x_j} |\Psi_* d\tau.
$$

Evaluation of this integral requires evaluating the effect of the operators  $\stackrel{\rightharpoonup}{x_j}$,
$\stackrel{\rightharpoonup}{y_j}$, and $\stackrel{\rightharpoonup}{z_j}$
acting on an atomic orbital.  Tables \ref{transx}, \ref{transy}, and \ref{transz} show
the integrals of the type $<\! \phi_{\lambda}
 |\stackrel{\rightharpoonup}{r_j}|\phi_{\sigma}\!>$, where $\phi_{\lambda}$ and $\phi_{\sigma}$ are
 pairs of atomic orbitals.

The integral
 $<\! \phi_{\lambda}|\stackrel{\rightharpoonup}{r}|\phi_{\lambda}\! >$ is simply the appropriate Cartesian coordinate,
that is, the $x$, $y$, or $z$ coordinate of the atom that $\phi_{\lambda}$ is on.

\begin{table}
\caption{\label{transy} ``$y$" Transition Integrals}
\begin{center}
\begin{tabular}{l|ccccccccc} \hline
& $s$  &  $p_x$  &  $p_y$  &  $p_z$  &  $d_{x^2-y^2}$  & $d_{xz}$  &
$d_{z^2}$  &  $d_{yz}$  &  $d_{xy}$ \\ \hline
$s$ & Y$_A$\\
$p_x$ & 0 & Y$_A$\\
$p_y$  & sp & 0 & Y$_A$ \\
$p_z$  & 0 & 0 & 0 & Y$_A$\\
$d_{x^2-y^2}$ & 0 & 0 & -pd & 0 & Y$_A$\\
$d_{xz}$      & 0 & 0 & 0 & 0 & 0 & Y$_A$\\
$d_{z^2}$     & 0 & 0 & -$\frac{1}{\sqrt{3}}$pd & 0 & 0 & 0 & Y$_A$\\
$d_{yz}$      & 0 & 0 & 0 & pd & 0 & 0 & 0 & Y$_A$\\
$d_{xy}$      & 0 & pd & 0 & 0 & 0 & 0 & 0 & 0 & Y$_A$\\  \hline

\end{tabular}\\
\end{center}
\end{table}

 $<\! ns|\stackrel{\rightharpoonup}{r}|np\! >$
 and  $<\! np|\stackrel{\rightharpoonup}{r}|nd\! >$
 can be evaluated using the following expressions:

$$
<\! ns|\stackrel{\rightharpoonup}{r}|np\! > = a_0\frac{(2n+1).2^{2n+1}.(\xi_s\xi_p)^{n+1/2}}{\sqrt{3}(\xi_s+\xi_p)^{2n+2}}
$$

$$
<np|\stackrel{\rightharpoonup}{r}|nd>=a_0\frac{(n_p+n_d+1)!.2^{n_p+n_d+1}.\xi_p^{n_p+1/2}.\xi_d^{n_d+1/2}}
{\sqrt{5}(\xi_p+\xi_d)^{n_p+n_d+2}.\sqrt{(2n_p)!(2n_d)!}},
$$
where $ns$, $np$, and $nd$ are $s$, $p$, and $d$ quantum numbers, respectively.
For the $sp$ transition, $n=ns=np$.
The Slater orbital exponents, $\xi_s$, $\xi_p$, and $\xi_d$, are usually
given in atomic units, that is, in
inverse Bohr, therefore they must converted to \AA ngstroms before use, hence the
presence of the $a_0=0.529$ in these expressions.

All integrals of the type used here are in \AA ngstroms, therefore the units of the integral
of the dipole operator on a M.O. is also in \AA ngstroms:
$$
<\! \psi_i|\stackrel{\rightharpoonup}{r}|\psi_j\! > =\sum_{\lambda}\sum_{\sigma}c_{\lambda i}c_{\sigma j}
<\! \phi_{\lambda}\stackrel{\rightharpoonup}{r}\phi_{\sigma} \!>,
$$
 Once the value of the integral is known,
the phase to be used must be determined. The simplest way to achieve this
is to reverse the sign of the oscillator whenever the second M.O.\ has a
higher index than the first.

\begin{table}
\caption{\label{transz} ``$z$" Transition Integrals}
\begin{center}

\begin{tabular}{l|ccccccccc} \hline
& $s$  &  $p_x$  &  $p_y$  &  $p_z$  &  $d_{x^2-y^2}$  & $d_{xz}$  &
$d_{z^2}$  &  $d_{yz}$  &  $d_{xy}$ \\ \hline
$s$ & Z$_A$\\
$p_x$ & 0 & Z$_A$\\
$p_y$  & 0 & 0 & Z$_A$ \\
$p_z$  & sp & 0 & 0 & Z$_A$\\
$d_{x^2-y^2}$ & 0 & 0 & 0 & 0 & Z$_A$\\
$d_{xz}$      & 0 & pd & 0 & 0 & 0 & Z$_A$\\
$d_{z^2}$     & 0 & 0 & 0 & $\frac{2}{\sqrt{3}}$pd & 0 & 0 & Z$_A$\\
$d_{yz}$      & 0 & 0 & pd & 0 & 0 & 0 & 0 & Z$_A$\\
$d_{xy}$      & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & Z$_A$\\  \hline
\end{tabular}\\
\end{center}
\end{table}

  Evaluation of the integrals over microstates is straightforward,
in that all integrals are zero, unless the number of differences between the microstates is exactly two,
in which case the integral is equal to that of the two M.O.s involved, times a phase factor.  That is,
for each pair of microstates that are identical, except for $\psi_i$
in $\Psi_a$ and  $\psi_j$ in $\Psi_b$, the integral is:.

$$
<\! \Psi_a|\stackrel{\rightharpoonup}{r}|\Psi_b\! > =<\! \psi_i|\stackrel{\rightharpoonup}{r}|\psi_j\! >*(-1)^n,
$$
where $n$ is the number of permutations necessary to move $\psi_i$ in microstate $\Psi_a$ to the position
occupied by $\psi_j$ in microstate $\Psi_b$. This is
similar to the `b' option on page~\pageref{b}.  As with
the molecular orbitals, the oscillators for microstates change sign
when the order of the microstates is reversed.  The simplest way to
achieve this is to use the same device that was used with the M.O.s;
that is, to reverse the sign of the oscillator whenever the second
microstate has a higher index than the first.

For completeness, the sign of $R_{0*}$ should be reversed if $k>l$, but
since only the modulus is used, this operation does not need to be done.

Finally, the state transition dipole can be calculated from:
$$
<\! \Psi_A|\stackrel{\rightharpoonup}{r}|\Psi_B\! > =\sum_a\sum_bc_{A a}c_{B b}<\! \Psi_a\stackrel{\rightharpoonup}{r}\Psi_b \!>,
$$

Although the transition dipole is normally regarded as involving the ground and an excited state, it is
possible to calculate the transition between two excited states.  The initial state is, by default, the
ground state, however if \comp{ROOT=n} $n\neq 1$, or any other keyword that specifies
a state other than the ground state, then the initial state will be an excited state.

For degenerate states, the transition dipole is the sum over all states involved.


\hypertarget{optimize}{%
\section{Optimize}\label{optimize}}

The \texttt{optimize} package contains a number of functions and classes
to perform shape optimization.

\hypertarget{optimizationproblem}{%
\section{OptimizationProblem}\label{optimizationproblem}}

An \texttt{OptimizationProblem} object defines an optimization problem,
which may include functionals to optimize as well as global and local
constraints.

Create an \texttt{OptimizationProblem} with a mesh:

\begin{lstlisting}
var problem = OptimizationProblem(mesh)
\end{lstlisting}

Add an energy:

\begin{lstlisting}
var la = Area()
problem.addenergy(la)
\end{lstlisting}

Add an energy that operates on a selected region, and with an optional
prefactor:

\begin{lstlisting}
problem.addenergy(la, selection=sel, prefactor=2)
\end{lstlisting}

Add a constraint:

\begin{lstlisting}
problem.addconstraint(la)
\end{lstlisting}

Add a local constraint (here a onesided level set constraint):

\begin{lstlisting}
var ls = ScalarPotential(fn (x,y,z) z, fn (x,y,z) Matrix([0,0,1]))
problem.addlocalconstraint(ls, onesided=true)
\end{lstlisting}

\hypertarget{optimizer}{%
\section{Optimizer}\label{optimizer}}

\texttt{Optimizer} objects are used to optimize \texttt{Mesh}es and
\texttt{Field}s. You should use the appropriate subclass:
\texttt{ShapeOptimizer} or \texttt{FieldOptimizer} respectively.

\hypertarget{shapeoptimizer}{%
\section{ShapeOptimizer}\label{shapeoptimizer}}

A \texttt{ShapeOptimizer} object performs shape optimization: it moves
the vertex positions to reduce an overall energy.

Create a \texttt{ShapeOptimizer} object with an
\texttt{OptimizationProblem} and a \texttt{Mesh}:

\begin{lstlisting}
var sopt = ShapeOptimizer(problem, m)
\end{lstlisting}

Take a step down the gradient with fixed stepsize:

\begin{lstlisting}
sopt.relax(5) // Takes five steps
\end{lstlisting}

Linesearch down the gradient:

\begin{lstlisting}
sopt.linesearch(5) // Performs five linesearches
\end{lstlisting}

Perform conjugate gradient (usually gives faster convergence):

\begin{lstlisting}
sopt.conjugategradient(5) // Performs five conjugate gradient steps.
\end{lstlisting}

Control a number of properties of the optimizer:

\begin{lstlisting}
sopt.stepsize=0.1 // The stepsize to take
sopt.steplimit=0.5 // Maximum stepsize for optimizing methods
sopt.etol = 1e-8 // Energy convergence tolerance
sopt.ctol = 1e-9 // Tolerance to which constraints are satisfied
sopt.maxconstraintsteps = 20 // Maximum number of constraint steps to use
\end{lstlisting}

\hypertarget{fieldoptimizer}{%
\section{FieldOptimizer}\label{fieldoptimizer}}

A \texttt{FieldOptimizer} object performs field optimization: it changes
elements of a \texttt{Field} to reduce an overall energy.

Create a \texttt{FieldOptimizer} object with an
\texttt{OptimizationProblem} and a \texttt{Field}:

\begin{lstlisting}
var sopt = FieldOptimizer(problem, fld)
\end{lstlisting}

Field optimizers provide the same options and methods as Shape
optimizers: see the \texttt{ShapeOptimizer} documentation for details.


% !TEX root=/home/tavant/these/manuscript/src/manuscript.tex

\section{Axial convection of the particles}
  \label{sec-reinjectionnoise}

  As introduced in the previous section, the \ac{2D} radial-azimuthal simulation does not model the axial convection of the particles.
  This results in an ever increasing particle energy \citep{lafleur2016a,heron2013}.
  We present in this section an algorithm to model the convection of the particle.
  Its drawbacks are discussed, and we propose a way to reduce them.

  \subsection{Lafleur's model of convection}

    \citet{lafleur2016a} proposed a way to model the axial convection of the particles in \ac{1D} purely azimuthal simulation.
    \Cref{fig-Fake_1d_1} shows a schematic illustration of the model.
    The principle is as follows
    \begin{itemize}
      \item We set a finite axial length, noted $L_z$ in \cref{fig-Fake_1d_1}.
      \item We follow the positions of the particle in the axial direction $z$
      \item When a particle crosses the boundary, it is removed.
      \item A new particle is created
      \begin{itemize}
        \item at $z=0$ for the ions
        \item  at $z=L_z$ for the electrons
      \end{itemize}
    \end{itemize}

    We create a new particle in order to conserve the charge in the simulation.
    The new particle has a random velocity following a Maxwellian flux distribution function of a given temperature.
    The azimuthal position of the particle is chosen uniformly at random.

    The Maxwellian flux distribution is the velocity distribution of the particles crossing a surface if the particles follow a Maxwellian distribution function. Thus we have
    \begin{equation} \label{eq-Maxwflux}
      f_{\rm flux}(\vect{v}) = \vect{v} \cdot \vect{n} f_{\rm M}(\vect{v}),
    \end{equation}
    with $f_{\rm M}$ the Maxwellian distribution function defined in \cref{eq-Maxwellian} and $\vect{n}$ the vector normal to the surface.

    \begin{figure}[hbt]
      \centering
      \includegraphics[width=\defaultwidth]{Fake_1d_2}
      \caption{Schematic representation of Lafleur's convection model \citep{lafleur2016a}. The red particle is removed of the simulation, and the green particle is created. In this illustration, the particle is an ion, and the reinjection is at $z=0$. The x direction corresponds to the azimuthal direction.}
      \label{fig-Fake_1d_1}
    \end{figure}

    Lafleur's model of convection has been adopted in \ac{2D} by \citet{croes2017a}.
    The principle is exactly similar.
    The particles are followed in the three directions, and a finite length is used to close the axial direction.
    It is important to note that even if the particles are followed in the three directions, the meshed domain is only \ac{2D}.
    The simulation is not \ac{3D}-\ac{3V}, but only \ac{2D}-\ac{3V}.

    In \citet{croes2017a}, the authors have observed that if the newly created particle has a radial position chosen uniformly at random, it will affect the sheath.
    Hence, they decided to use the same radial position as the removed particle.
    \Cref{fig-Fake_2d} presents a schematic representation of the convection model in \ac{2D}.

    \begin{figure}[hbt]
      \centering
      \includegraphics[width=\defaultwidth]{2_5D_dielectric_PPS_small}
      \caption{Schematic representation of the Lafleur's convection model adapted in \acs{2D}. The new particle radial position corresponds to the removed particle, but its azimuthal position is chosen uniformly at random. }
      \label{fig-Fake_2d}
    \end{figure}

    \Cref{fig-energy_convection} shows the evolution as a function of time of the electron mean energy in a typical \ac{2D} radial-azimuthal simulation, adapted from \citet{croes2017}.
    We can see that without the convection, the mean energy quickly rises to unphysical values.
    When the convection is modeled, using an axial length of $L_z=1$ cm, the energy reaches a steady-state.
    \nomenclature[Q]{\ensuremath{ L_z}}{ Axial length}
    \begin{figure}[hbt]
      \centering
      \includegraphics[width=\defaultwidth]{energy}
      \caption{Time evolution of the electron mean energy when the convection is not modeled ($L_z \rightarrow \infty$) and with Lafleur's convection model used, $L_z = 1$ cm. Adapted from \citet{croes2017}.}
      \label{fig-energy_convection}
    \end{figure}

  \subsection{Numerical artifacts}
    \citet{lafleur2016a} studied the impact of the convection model on the simulation results.
    The authors observed in particular that changing the azimuthal length of the simulation domain could affect the simulation results.

    \Cref{fig-convection_numerical} shows the time evolution of the azimuthal electric field $E_{\theta}$ from the \ac{1D} simulation \citep{lafleur2016a}.
    \nomenclature[Q]{\ensuremath{ E_{\theta}}}{ Azimuthal electric field}

    On the first row (\cref{fig-convection_numerical}.{\bf a} and {\bf b}), the length of the periodic azimuthal direction is $L_{\theta}=0.5$~cm.
    \cref{fig-convection_numerical}.{\bf a} corresponds to the case without axial convection.
    We see that the \ac{ECDI} rises and does not saturate.
    The wavelength is short, of the order of $\lambda = 1.5$~mm.
    \nomenclature[Q]{\ensuremath{ \lambda}}{ Wave length}
    \cref{fig-convection_numerical}.{\bf b} corresponds to the same case as \cref{fig-convection_numerical}.{\bf a} but this time with the axial convection modeled.
    We observe this time a saturation of the oscillation's amplitude, and the wavelength is close to $\lambda \simeq 1.5$~mm.

    On the second row (\cref{fig-convection_numerical}.{\bf c} and {\bf d}), the length of the periodic azimuthal direction is $L_{\theta}=1$~cm.
    \cref{fig-convection_numerical}.{\bf c} corresponds to the case without axial convection, and \cref{fig-convection_numerical}.{\bf d} corresponds to the same case but with the axial convection modeled.
    In \cref{fig-convection_numerical}.{\bf c}, we can see that increasing the azimuthal length compared to \cref{fig-convection_numerical}.{\bf a} did not affect the \ac{ECDI}, as expected.
    However, in  \cref{fig-convection_numerical}.{\bf d}, the instability is clearly affected.
    A single oscillation is observed, corresponding to $\lambda=10$~mm, which seems almost undoubtedly unphysical.

    \begin{figure}[hbt]
      \centering

      \begin{tabular}{@{} cc @{}}
        \subfigure{Lafleur_NoLz_1}{a}{20, 20}  &
        \subfigure{Lafleur_Lz_1}{b}{20, 20} \\
        \subfigure{Lafleur_NoLz_2}{c}{20, 20} &
        \subfigure{Lafleur_Lz_2}{d}{20, 20} \\
      \end{tabular}
      \caption{Effects of Lafleur's convection model for two different azimuthal lengths on the azimuthal electric field. ({\bf a}) No convection, $L_x=0.5$~cm,  ({\bf b}) convection modeled, $L_x=0.5$~cm,  ({\bf c}) No convection, $L_x=1$~cm,  ({\bf d}) convection modeled, $L_x=1$~cm. The color of each plot is normalized to the maximum amplitude. Adapted from \citep{lafleur2016a}. }
      \label{fig-convection_numerical}
    \end{figure}
    \FloatBarrier
    \citet{croes2017} observed similar behavior with the bidimensional  simulation.
    The author investigated the values of the azimuthal length, which presented physical and unphysical results
    for different values of the axial length.
    \Cref{fig-couplesCroes} shows the results obtained (adapted from \citep{croes2017}).
    We can see that for a given value of the axial length, the azimuthal length must be less than a specific value to present physical results.
    However, the value of this upper limit depends on the axial length, such that if the axial length decreases, the upper limit of the azimuthal length decreases as well.
    The dotted gray line is a rough representation of the limit between the physical and unphysical results.

    \begin{figure}[hbt]
      \centering
      \includegraphics[width=\defaultwidth]{2D_couples.pdf}
      \caption{For 2D PIC simulations\string: values of the azimuthal length and the axial length for which the simulation result is physical (similar to \cref{fig-convection_numerical}.{\bf b}) or unphysical  (similar to \cref{fig-convection_numerical}.{\bf d}). The dotted gray line is an approximation of the limit between the domains.}
      \label{fig-couplesCroes}
    \end{figure}

    In the next section, we develop a theory that could explain the observation, and a new convection model for the simulation is proposed.

  \subsection{Numerical noise of Lafleur's convection model}

    Let us consider Lafleur's convection model in \ac{1D} on the charge density.
    When computing the charge density on the mesh vertices, the axial position is not taken into account.
    Consequently, the convection process illustrated in \cref{fig-Fake_1d_1} is similar to moving a particle arbitrarily (read randomly).
    Seen by the charge density, this is similar to Poisson noise, also named shot noise, on the charge density.\footnote{In fact, this noise is the combination of Poisson noise with a uniform noise as we use a cloud in cell method. In addition it is happening twice for every particle convection, once with a positive charge and once with a negative charge. But the result is not affected by this simplification due to the central limit theorem.}

    After a certain number of particles removed and created, the Poisson noise is similar to a Gaussian noise, also named thermal noise, following a normal distribution $\N$.
    \nomenclature[Q]{\ensuremath{ \N }}{ Normal distribution.}
    Hence, the charge density becomes \footnote{One can note that the mean noise is strictly zero (with probability 1), as the charge density is conserved.}
    \begin{equation} \label{eq-rhonoise}
      \rho = \rho_0 + \N(0, \stdconv),
    \end{equation}
    with $\rho$ the charge density, $\rho_0$ the charge density without the convection process, and $\stdconv$ the standard deviation of the distribution of the noise associated with the convection model.
    \nomenclature[Q]{\ensuremath{ \rho}}{ Charge density}
    \nomenclature[Q]{\ensuremath{ \stdconv}}{ Standard deviation of the distribution of the noise associated with the convection model}
    Surprisingly, the noise due to the convection model is similar to the numerical noise induced by the decomposition of the plasma into particles $\N(0, \sigma_{\rm stat})$.
    However, the amplitude of this statistical noise decreases with the number of particles per cell used
    \begin{equation*} \label{eq-statistical}
     \sigma_{\rm stat} \propto \frac{1}{\sqrt{N_{pc}}}.
    \end{equation*}

    On the other hand, the amplitude of the noise induced by the convection model depends on the plasma density $n$, the axis velocity of the particles $v_z$ and the axial length $L_z$
    \begin{equation} \label{eq-convstd}
     \stdconv \propto \frac{n}{L_z} v_z.
    \end{equation}

    We can see in \cref{eq-convstd} that the amplitude of the convection induced noise on the charge density is proportional to the inverse of the axial length $L_z$.
    This could explain the observation of \cref{fig-couplesCroes} when using a smaller $L_z$.
    However, it does not explain the effects of the azimuthal length observed in \cref{fig-couplesCroes,fig-convection_numerical}.

  \subsection{Effect of the noise on the electric field}
    \label{sec-mathnoise}
    In order to explain the impact of the azimuthal length on the instability, we can study the azimuthal electric field $\aziE$ resulting of the charge density $\rho$.
    As the Poisson equation is linear, we have
    \begin{align}
      \aziE(\theta) &= C + \frac{1}{\epsilon_0} \int_0^{\theta} \rho(s) ds\\
                    &= C + \frac{1}{\epsilon_0} \int_0^{\theta} (\rho_0(s) + \N(0, \stdconv) ) ds \\
                    &= C + \aziE_{, 0} + \aziE_{, 1}
    \end{align}
    with $C$ a constant that ensures that the periodical \ac{BC} are respected.
    The part of the electric field $\aziE_{, 0}$ corresponds to the unperturbed charge density $\rho_0$ and $\aziE_{, 1}$  corresponds to the noisy charge density $\N(0, \sigma_{\rm stat})$.
    Hence, let us focus now on $\aziE_{, 1}$.
    We can study $\aziE_{, 1}$ using two equivalent means\string: the \ac{FT} and the Brownian bridge.

    \paragraph{Fourier Transform \\}
      Applying the \ac{FT} on the equation
      \begin{equation} \label{eq-aziE1}
        \aziE_{, 1} = \frac{1}{\epsilon_0} \int_0^{\theta}  \N(0, \stdconv) ds
      \end{equation}
      gives
      \begin{align}
        \FFT \lp \aziE_{, 1} \rp (k) &= \frac{1}{\epsilon_0} \FFT \lp \int_0^{\theta}  \N(0, \stdconv) ds \rp \\
                                     &= \frac{1}{\epsilon_0} \frac{ \N(\mu_{\rm FT}, \sigma_{\rm FT})}{k} \label{eq-fft}
      \end{align}

      \Cref{eq-fft} shows that $\aziE_{, 1}$ also follows a Gaussian distribution, but with a non-zero mean value.
      It is also inversely proportional to the wave number $k$.
      Hence, when we increase the azimuthal length, which means that small wave numbers can exist in the simulation domain, the amplitude of $\aziE_{, 1}$ increases as well.

    \paragraph{Brownian Bridge\\}
      \Cref{eq-aziE1}, combined with the \ac{BC}, is the definition of the a Brownian bridge.

      A Brownian bridge is a particular Brownian motion that reaches at a given distance the same value as the initial value.
      Hence, we have \citep{ibe2013}
      \begin{align*}
        \mathbb{E}(\aziE_{, 1}) &= 0,  \\
        {\rm var}(\aziE_{, 1}) &= \stdconv^2 \frac{L_{\theta}^2}{4}
      \end{align*}

      Hence, the increase of the azimuthal length increases the amplitude of $\aziE_{, 1}$.

    We believe that when the amplitude of $\aziE_{, 1}$ is too large, it can trigger an unphysical oscillation.
    The next section uses this conclusion in order to adapt the convection model.

    \subsection{Noiseless convection model}
      \label{sec-noiselessresults}
      In the previous section, we have shown that the convection model induces a noise in the charge density, that produces an azimuthal electric field which amplitude depends on the azimuthal length.

      We propose here a modified version of Lafleur's convection model in order to remove the noise in the charge density.
      The noiseless convection model follows the same algorithm as before, but the azimuthal position of the particle created is not chosen uniformly as random, but instead the new particle has the same position as the removed particle.
      \Cref{fig-fakez3} shows a schematic illustration of the noiseless convection algorithm applied on a particle.

      \begin{figure}[hbt]
        \centering
        \includegraphics[width=\defaultwidth]{Fake_1d_3}
        \caption{Illustration of the noiseless convection model}
        \label{fig-fakez3}
      \end{figure}

      We have implemented this modified convection model in the \ac{2D} radial and azimuthal simulation.
      \Cref{fig-newconv_noconv} shows the time  evolution of the azimuthal electric field at the center of the radial dimension with and without the noiseless convection model.
      It presents the same conditions as in \cref{fig-convection_numerical}.{\bf a} and {\bf b}.
      As previously, the convection stabilizes the growth of the instability to a steady-state, but it does not affect the physics.

      \begin{figure}[hbt]
        \centering
        \includegraphics[width=0.95\textwidth]{Compare_no_new_Reinj_Oz}
        \caption{Time evolution of the azimuthal electric field at the center of the radial dimension with and without the noiseless convection model. }
        \label{fig-newconv_noconv}
      \end{figure}

      \Cref{fig-oldeconv_newconv} shows the time  evolution of the azimuthal electric field at the center of the radial dimension  with the convection modeled using Lafleur's model and the noiseless model with a small azimuthal length.
      We can see that the two models give almost exactly the same results.

      \begin{figure}[hbt]
        \centering
        \includegraphics[width=0.95\textwidth]{Compare_old_new_Reinj_Oz}
        \caption{Time evolution of the azimuthal electric field at the center of the radial dimension with the convection modeled using (left) Lafleur's model and (right) the noiseless model with a small azimuthal length (0.325cm).}
        \label{fig-oldeconv_newconv}
      \end{figure}

      \Cref{fig-oldeconv_newconv_longLZ} shows the  time  evolution of the azimuthal electric field at the center of the radial dimension  with the convection modeled using Lafleur's model and the noiseless model but using a longer azimuthal length than \cref{fig-oldeconv_newconv}.
      In this case, we can see that Lafleur's convection model induces oscillations that are not observed with the noiseless model.

      \begin{figure}[!hbt]
        \centering
        \includegraphics[width=0.95\textwidth]{Compare_old_new_Reinj_Oz_LongLx}
        \caption{Time evolution of the azimuthal electric field at the center of the radial dimension with the convection modeled using (left) Lafleur's model and (right) the noiseless model with a longer azimuthal length (0.65cm).}
        \label{fig-oldeconv_newconv_longLZ}
      \end{figure}

      These observations have shown that Lafleur's convection model induces a noise on the charge density, that does not affect the simulation when the domain size is small, but can rise numerical artifacts when the domain size is larger.
      We have seen that minor modifications on the model do not affect the simulation results on a small domain, and allows us to use a larger simulation domain without any numerical artifact.

    \subsection{Effects on a \acs{2D} simulation domain}

      The mathematical development of \cref{sec-mathnoise} has been done in \ac{1D}.
      We can legitimately wonder if the results  can be extended directly to a \ac{2D} domain.
      A mathematical definition of $\aziE_{, 1}$ in \ac{2D} is more difficult, as we have, neglecting the dielectric layers,
      \begin{equation} \label{eq-aziE}
        \aziE_{, 1} = -\partial_{\theta} \phi_1 \text{ such that } \grad \cdot \grad \phi_1 = - \frac { \N(0, \stdconv)}{\epsilon_0} \text{ following the \ac{BC}}.
      \end{equation}
      The \ac{BC}s are
      \begin{itemize}
        \item periodic \ac{BC} in the azimuthal direction,
        \item Dirichlet \ac{BC} in the radial direction, modeling grounded walls,
      \end{itemize}
      which translate as
      \begin{align}
        &\phi = 0 \text{ for } r=0 \text{ and } r=L_r, &\forall \theta \label{eq-BC1} \\
        &\phi(\theta = 0)= \phi(\theta = L_{\theta}) , &\forall r \label{eq-BC2}
      \end{align}

      Solving \cref{eq-aziE} with the conditions \cref{eq-BC1,eq-BC2} analytically is much more difficult that the \ac{1D} development, because of the Dirichlet \ac{BC}.
      \nomenclature[N]{Dirichlet boundary condition\string:}{ a type of boundary conditions for which the field is fixed. For instance for grounded electrodes on the plasma potential\string: $\phi = 0$}
      \nomenclature[N]{Neumann boundary condition\string:}{ a type of boundary conditions for which the first derivative of the field field is fixed. For instance for a surface with surface charges on the plasma potential\string: $\deriv{\phi}{x} = \sigma$}
      However, we can investigate it numerically, by solving \cref{eq-aziE} for a given random source term.
      Using a Monte Carlo approach, we average the results  200 times to better observe the mean behavior with respect to the noise (i.e. increasing signal to noise ratio).
      For each computation, a normalized source term $\rho_1 = \N(0, 1)$ is generated over a \ac{2D} domain, then the \ac{2D} Poisson equation is solved numerically\footnote{The SOR algorithm is used in this MC calculation. The iterations are stopped using a relative tolerance of $\sn{2}{-6}$ on the mean square error.} to obtain $\phi_1$, and the azimuthal electric field $\aziE_{, 1} =- \partial_{\theta} \phi_1 $ is computed.

      \begin{figure}[!hbt]
        \centering
        \includegraphics[width=\textwidth]{2D_MC_noise.png}
        \caption{Results for one case used in the Monte Carlo calculation with 100 cells in radial direction and 500 cells in the azimuthal direction, with (left) the normalized source term $\rho = \N(0, 1)$, (center) the azimuthal electric field, and (right) the plasma potential. }
        \label{fig-one}
      \end{figure}

      One typical result is shown in \cref{fig-one}.
      We can see the impact of the radial Dirichlet boundary conditions, \cref{eq-BC1}, on the potential $\phi_1$ induced by the noise.
      The potential mostly oscillates in the azimuthal direction, and its amplitude is larger on the centerline between the walls.
      A similar behavior is observed for the azimuthal electric field.

      \Cref{fig-dftLr} shows the \ac{DFT} of the source term $\rho_1$, the resulting azimuthal electric field $\aziE_{, 1}$ and plasma potential $\phi_1$ computed on the centerline of the simulation domain, for three different radial lengths expressed in number of cells in the radial direction $N_x$.
      Is also shown the "equivalent" source term $\rho_{\rm eq}$, which is the source term that would give the frequency spectra of $\aziE_{, 1}$ observed in a \ac{1D} domain

      \begin{equation} \label{eq-equirho}
        \rho_{\rm eq} = \epsilon_0 \partial_\theta \aziE_{, 1}.
      \end{equation}
      The results are given for different radial lengths $N_x=15,50 \text{ and } 200$, while the azimuthal length $N_y=200$ is kept constant.
      We can see that the plasma potential and the electric field show larger amplitudes for small wave numbers (large wavelength) compared to large wave numbers in the three cases.
      However, the amplitude of the smallest wave numbers is affected.
      In the cases of small radial length ($N_x=15 \text{ and } 50$), the spectra of the electric field is not monotonic.
      This can be explained by the Dirichlet \ac{BC}s that {\it pins down} the fluctuation of the plasma potential.

      To compare the results to the purely azimuthal \ac{1D} case, \cref{fig-dftLr} shows the frequency spectra of the equivalent source term $\rho_{\rm eq}$.
      We see that $\rho_{\rm eq}$ is always smaller than $\rho_1$, and is significantly reduced in the small and large wavenumber.
      However, even though the amplitude is reduced in \ac{2D} with small radial direction compared to a \ac{1D} model, we still observe large amplitude of small wave number oscillations in both the electric field and the plasma potential.
      It means that the \ac{2D} domain does not change significantly the effect of the numerical noise $\rho_1$.
      Hence, the conclusions of  \cref{sec-mathnoise} derived in \ac{1D} can be legitimately used for \ac{2D} domains.

      \begin{figure}[!hbt]
        \centering
        \includegraphics[width=\textwidth]{effect_Lr_noEq1D.pdf}
        \caption{ DFT of the source term $\rho_1 = \N(0, \stdconv)$, the resulting azimuthal electric field $\aziE_{, 1}$ and plasma potential $\phi$ computed on the centerline of a radial-azimuthal simulation, and the Equivalent \acs{1D} source term defined by \cref{eq-equirho}. The azimuthal length is $L_{\theta}=50$ cm. The \acs{DFT} are averaged 200 times  }
        \label{fig-dftLr}

      \end{figure}


\chapter{Simulation}
% put these two lines after every \chapter{} command
\vspace{-2em}
\minitoc
To implement and research various FDIR systems on satellites an simulation of satellite dynamics and kinematics is developed. The focus of this thesis is on small satellites and more specifically cubesats. For the simulation of the ADCS of the satellite \cite{auret2012design, JansevanVuuren2015, Jordaan2016} were referenced during the development of the satellite simulation. The simulation was developed in Python to simulate the dynamics and kinematics during a satellite orbit. The faults for the subsystems are also developed within the simulation and will be discussed within this chapter.

\section{Attitude Determination and Control System}

For the mission of the specific satellite in this document the main operational goal of the Attitude Determination and Control System (ADCS) on this specific satellite mission is to control the payload to point towards the centre of the earth.

\subsection{Coordinate Frames}
The coordinate frames in aerospace is a fundamental part of the ADCS. To determine the orientation and position of an object, it should be relative to a fixed frame. Consequently, the Earth inertial coordinate (EIC) frame is the fixed frame from which every other frame is relative to.

A coordinate frame consists of three orthogonal vectors which is commonly referred to as x, y, and z. The axis of the coordinate frame is appropriately named as X-axis, Y-axis and Z-axis as seen in Figure... A vector (r) within the current coordinate frame can thus be expressed as
\begin{equation}
\overrightarrow{r} = x\overrightarrow{i} + y\overrightarrow{j} + z\overrightarrow{k}
\end{equation}
where the magnitude of $\overrightarrow{r}$ is denoted as $|\overrightarrow{r}|$ and is equal to
\begin{equation}
|\overrightarrow{r}| = \sqrt{x^2 + y^2 + z^2}.
\end{equation}

The Earth-centered coordinate frames are dived into two, namely the EIC and earth fixed coordinate (EFC) frame. EFC is fixed to the earth and rotates with it. This frame is important with respect to where the satellite position is with regards to position's on earth, such as the ground station. It is also import for the modelling of the geomagnetic fields.

% Insert a figure of the earth coordinate frames here

The EIC is defined as the Z-axis pointing towards the north pole, the X-axis pointing towards the Vernal Equinox, $\Upsilon$, and the Y-axis completing the orthogonal set. The EFC is a copy of the EIC, with the Z-axis being identical, however the EFC rotates with the earth. The EFC in relation to the EIC can be expressed by a single angle of rotation, which is the Greenwich Hour Angle (GHA), $\alpha_G$. With the knowledge of $t$ --- the elapsed time since $t_0$, $w_E$ --- the angular rate of the earth, and $\alpha_{G,0}$ --- the GHA at $t = t_0$, $\alpha_G$ can be calculated as
\begin{equation}
\alpha_G = w_Et + \alpha_{G,0}
\end{equation}
To transform a vector from one coordinate frame to another, a transformation matrix, $\boldsymbol{A}$, is required. For example vector $\overrightarrow{r}_{EFC}$ can be transformed to $\overrightarrow{r}_{EIC}$ with
\begin{equation}
\overrightarrow{r}_{EIC} = \boldsymbol{A}^{EIC}_{EFC}\overrightarrow{r}_{EFC}
\end{equation}
with $\boldsymbol{A}^{EIC}_{EFC}$ being the EFC-to-EIC transformation matrix. Due to the definition of both coordinate frames, $\boldsymbol{A}^{EIC}_{EFC}$ can be defined .

\begin{equation}
\boldsymbol{A}^{EIC}_{EFC} =
\begin{bmatrix}
	cos(\alpha_G) & -sin(\alpha_G) & 0\\
	sin(\alpha_G) & cos(\alpha_G) & 0 \\
	0 & 0 & 1
\end{bmatrix}
\end{equation}

To determine the satellite position, satellite coordinate frames must be used. Three satellite-centred coordinate frames are used, namely the inertial-reference coordinate frame (the satellite does not rotate), the orbit-referenced coordinate (ORC) frame and the satellite body coordinate (SBC) frame. The IRC frame is only acknowledged, since it is the frame that is fixed (as it does not rotate around the centre of the satellite), however it changes position with the orbit of the satellite. This frame is not used to determine the position of the satellite and will not be referenced for the remainder of this document.

The ORC frame changes location as the satellite moves, however the Z-axis is always pointing towards the centre of the earth, with the Y-axis being the anti-normal and the X-axis completing the orthogonal set. To transform a vector from the EIC frame to the ORC frame the unit position vector, $\overrightarrow{r}_{sat}$ and the unit velocity vector, $\overrightarrow{v}_{sat}$ in EIC \cite{Chen_ground-target}.

\begin{equation}
	\boldsymbol{A}^{ORC}_{EIC} =
	\begin{bmatrix}
		\hat{u} & \hat{v} & \hat{w}\\
	\end{bmatrix}^T
\end{equation}
where
\begin{equation}
\hat{w} = -\frac{r_{sat}}{||r_{sat}||}
\end{equation}
\begin{equation}
\hat{v} = -\frac{r_{sat} \times v_{sat}}{||r_{sat} \times v_{sat}||}
\end{equation}
\begin{equation}
\hat{u} = \hat{v} \times \hat{w}
\end{equation}

The SBC frame is the frame fixed to the satellite and it is the relative rotation of the satellite in relation to the ORC. Thus for the mission of this satellite it is required that the SBC and ORC frames coincide. For the transformation of a vector from the ORC to SBC frame, the direct cosine matrix (DCM) also referred to as $\boldsymbol{A}$ or $\boldsymbol{A}^{SBC}_{ORC}$ is used. For the remainder of the document the DCM will be referred to as $\boldsymbol{A}^{SBC}_{ORC}$ to avoid any confusion. The calculation of this transformation matrix will be discussed in $\S$\ref{subsection_quaternions}.

% Insert a figure of the satellite coordinate frames here

\subsection{Attitude}
\label{subsection_quaternions}
To determine the attitude of an object, a model must be used to determine the rotation of an object in three dimensions. For this the visual and intuitive example of the Euler angles exist. Euler angles are the rotation of an object around three orthogonal axis, that change orientation with the rotation of the object. The three axes, denoted by X, Y and Z rotate with the object as depicted in Figure~\ref{Figure-Euler_angles}.

\begin{figure}[h!tb]
\label{Figure-Euler_angles}
\begin{tikzpicture}[scale=2.5,tdplot_main_coords]
	%\tdplotsetmaincoords{70}{110}
	% Set origin of main (body) coordinate system
	\coordinate (O) at (0,0,0);

	% Draw main coordinate system
	\draw[red, ,->] (0,0,0) -- (1,0,0) node[anchor=north east]{$x_{\mathcal{I}}$};
	\draw[red, ,->] (0,0,0) -- (0,1,0) node[anchor=north west]{$y_{\mathcal{I}}$};
	\draw[red, ,->] (0,0,0) -- (0,0,1) node[anchor=south]{$z_{\mathcal{I}}$};

	% Intermediate frame 1
	\tdplotsetrotatedcoords{-60}{0}{0}
	\draw[tdplot_rotated_coords,->, blue] (0,0,0) -- (1,0,0) node[anchor=north east]{$x'$};
	\draw[tdplot_rotated_coords,->, blue] (0,0,0) -- (0,1,0) node[anchor=west]{$y'$};
	\draw[tdplot_rotated_coords,->, blue] (0,0,0) -- (0,0,1) node[anchor=west]{$z'$};

	\tdplotsetrotatedthetaplanecoords{90}
	%draw theta arc and label
	%\tdplotdrawarc[tdplot_rotated_coords,->,color=blue]{(0,0,0)}{0.5}{0}{350}{anchor=south west,color=gray}{$\alpha$}
	\tdplotdrawarc[tdplot_rotated_coords,->,color=gray]{(0,0,0)}{0.5}{80}{90}{anchor=south west,color=gray}{$\alpha$}
	\tdplotdrawarc[tdplot_rotated_coords,->,color=gray]{(0,0,0)}{0.5}{170}{180}{anchor=south west,color=gray,  yshift = -15 pt}{$\alpha$}

	%% Intermediate frame 2
	\tdplotsetrotatedcoords{-60}{15}{0}
	\draw[,tdplot_rotated_coords,->, green] (0,0,0) -- (1,0,0) node[anchor=
	north]{};
	\draw[,tdplot_rotated_coords,->, green] (0,0,0) -- (0,1,0)
	node[anchor=west]{$y''$};
	\draw[,tdplot_rotated_coords,->, green] (0,0,0) -- (0,0,1)
	node[anchor=south]{$z''$};
	\tdplotsetrotatedthetaplanecoords{60}
	%draw theta arc and label
	%\tdplotdrawarc[tdplot_rotated_coords,->,color=green]{(0,0,0)}{0.5}{0}{350}{anchor=north,color=gray}{$\beta$}
	\tdplotdrawarc[tdplot_rotated_coords,->,color=gray]{(0,0,0)}{0.5}{80}{90}{anchor=north,color=gray}{$\beta$}
	\tdplotdrawarc[tdplot_rotated_coords,->,color=gray]{(0,0,0)}{0.5}{310}{320}{anchor=south west,color=gray}{$\beta$}
	%
	% Rotate to final frame
	\tdplotsetrotatedcoords{-60}{15}{45}
	\draw[thick,tdplot_rotated_coords,->, cyan] (0,0,0) -- (1,0,0)
	node[anchor=west]{$x_{\mathcal{B}}$, \textcolor{green}{$x''$}};
	\draw[thick,tdplot_rotated_coords,->, cyan] (0,0,0) -- (0,1,0) node[anchor=west]{$y_{\mathcal{B}}$};
	\draw[thick,tdplot_rotated_coords,->, cyan] (0,0,0) -- (0,0,1) node[anchor=south]{$z_{\mathcal{B}}$};

	\tdplotsetrotatedthetaplanecoords{30}
	%draw theta arc and label
	%\tdplotdrawarc[tdplot_rotated_coords,->,color=cyan]{(0,0,0)}{0.5}{0}{350}{anchor=north,color=gray}{$\gamma$}
	\tdplotdrawarc[tdplot_rotated_coords,->,color=gray]{(0,0,0)}{0.5}{215}{225}{anchor=north,color=gray, yshift = 15pt}{$\gamma$}
	\tdplotdrawarc[tdplot_rotated_coords,->,color=gray]{(0,0,0)}{0.5}{328}{338}{anchor=south west,color=gray}{$\gamma$}

\end{tikzpicture}
\end{figure}

Euler angles and DCM will be acknowledged and explained why they are not applicable.
In some literature the first and last quaternion are swapped.

\subsection{Satellite Kinematics and Dynamics}

\subsection{Rungka-kutta}

\section{Environment}
\subsection{Earth Orbit}
Earth orbit according to sgp4 and also the placement of the earth sensor.

Show plot of 3D earth orbit...

\subsection{Sun}
The calculations for the sun position and also the placement of the coarse and fine sun sensor.

Show graph of sun plot...

\subsection{Geomagnetic field}

\begin{equation}
\label{Eq-Geomagnetic_field}
V(r_s,\theta, \lambda) = R_E \sum_{n=1}^{k}\left(\frac{R_E}{r_s}^{n+1}\right)\sum_{m=0}^{n}\left(g_n^mcos(m\lambda) + h_n^msin(m\lambda)\right)P_n^m(\theta)
\end{equation}

Show graph of geomagnetic plot...

\section{Sensor models}
\subsection{Position of Sensors and Field of View}

\subsection{Noise}

\section{Disturbance models}
\subsection{Gravity Gradient}

\subsection{Aerodynamic Disturbance}
\cite{Steyn2014}

\subsection{Wheel Imbalance}

\section{Attitude Determination}
In this section discuss the Kalman filter.

\subsection{Kalman Filter}
\cite{Jones2017}

\section{Attitude Control}
Magnetic control during detumbling
Reaction wheel control during normal operation

\section{Constellations}
Explain the design of the satellite constellations and the algorithms to run communicate between satellites.

\begin{algorithm}

	\SetKwInOut{Input}{Input}
	\SetKwInOut{Output}{Output}

	\SetKwData{Left}{left}
	\SetKwData{This}{this}
	\SetKwData{Up}{up}
	\SetKwFunction{Union}{Union}
	\SetKwFunction{FindCompress}{FindCompress}

	\Indm
	\Input{Description of the input to the algorithm.}
	\Output{Description of the output from the algorithm.}
	\Indp

	\BlankLine

	\emph{Initialize hyperparameters}\;
	Get initial data from satellite\\
	Update positions of each satellite\\
	\For{$i\leftarrow 1$ \KwTo $N$}{
		Determine $k$-nearest satellites to $satellite_i$ from the positions\\
		Select data from nearest satellites\\
		Send nearest satellites predictions and data to $satellite_i$\\
		Retrieve data from $satellite_i$ and fault predictions of $k$-nearest satellites\\
	}
	Update position of $satellite_i$\\
	Update data of $satellite_i$

	\caption[Do not end short caption with full-stop]{Algorithm example}
	\label{alg}

\end{algorithm}

\section{Typical Faults}
For the simulation of the satellite and the induced faults to train and test various anomaly detection methodologies a database of typical faults is required. \textcite{tafazoli2009study} made a study of the percentage of failure per subsystem.

\subsection{Probability of Fault Occurence}
The occurrence of a fault depends on the reliability of that equipment. \textcite{Guo2014} studied the reliability of small satellites and calculated the parameters for the Weibull distribution based on real data. To model the probability of a fault to occur the probability density function is used \cite{Jones2017}.

This probability however is small and for the training of the system the data is too sparse for the computational abilities of any regular PC. Thus the probability of a failure during training is fixed to $1/1000000$ to produce the data required for the anomaly detection with a million test samples.

\subsection{Set of faults}
A set of typical faults for the ADCS is shown in Table~\ref{ADCS fault table}.

\newpage
\begin{sidewaystable}[]
	\label{ADCS fault table}
	\begin{tabular}{|l|c|l|l|l|l|}
		\hline
		\multicolumn{6}{|c|}{\textbf{Internal Faults}} \\ \hline
		\textbf{Fault classes} &
		\multicolumn{1}{l|}{\textbf{\begin{tabular}[c]{@{}l@{}}Failure rate \\ per hour\end{tabular}}} &
		\textbf{Fault causes} &
		\textbf{References} &
		\textbf{Possible effect} &
		\textbf{Possible permutations} \\ \hline
		\multirow{4}{*}{Reaction wheels} &
		\multicolumn{1}{l|}{\multirow{4}{*}{2.5E-7 \cite{Spilhaus1987}}} &
		\begin{tabular}[c]{@{}l@{}}Reaction wheel electronics \\ fail\end{tabular} &
		\cite{allen2012satellite} \cite{Jacklin2019} &
		\begin{tabular}[c]{@{}l@{}}Does not respond \\ to control inputs\end{tabular} &
		\begin{tabular}[c]{@{}l@{}}Momentum remains the same \\ or decreases slightly due to \\ friction\end{tabular} \\ \cline{3-6}
		&
		\multicolumn{1}{l|}{} &
		Overheated reaction wheel &
		\cite{Wintoft} &
		Decrease in speed &
		1\% of initial speed per second \\ \cline{3-6}
		&
		\multicolumn{1}{l|}{} &
		\begin{tabular}[c]{@{}l@{}}Catastrophic failure (cause \\ unknown)\end{tabular} &
		\cite{Choi2011} &
		Stops rotating &
		0 \\ \cline{3-6}
		&
		\multicolumn{1}{l|}{} &
		\begin{tabular}[c]{@{}l@{}}Increase in rotation speed \\ (Unknown cause)\end{tabular} &
		\begin{tabular}[c]{@{}l@{}}Gerhard Janse \\ van Vuuren\end{tabular} &
		\begin{tabular}[c]{@{}l@{}}Wheel speed \\ increases\end{tabular} &
		\begin{tabular}[c]{@{}l@{}}Between 90-100\% of maximum \\ wheel speed\end{tabular} \\ \hline
		Magnetorquers &
		\multicolumn{1}{l|}{ADCS fault table8.15E-9 \cite{Spilhaus1987}} &
		Polarities are inverted &
		\cite{Crowell2011} &
		Incorrect rotation &
		\\ \hline
		\multirow{2}{*}{Magnetometers} &
		\multicolumn{1}{l|}{\multirow{2}{*}{8.15E-9 \cite{Spilhaus1987}}} &
		Unknown &
		\begin{tabular}[c]{@{}l@{}}Gerhard Janse \\ van Vuuren\end{tabular} &
		Stops reacting &
		\begin{tabular}[c]{@{}l@{}}Provides no feedback or the \\ output remains constant\end{tabular} \\ \cline{3-6}
		&
		\multicolumn{1}{l|}{} &
		\begin{tabular}[c]{@{}l@{}}Magnetometers and magne-\\ torquers interfered with \\ each other\end{tabular} &
		\cite{Jacklin2019} &
		\begin{tabular}[c]{@{}l@{}}Noise on magneto-\\ meters and noise \\ on control of mag-\\ netorquers\end{tabular} &
		\begin{tabular}[c]{@{}l@{}}Between x3 and x5 times the \\ normal noise magnitude \\ Guassian distribution\end{tabular} \\ \hline
		Earth Sensor &
		- &
		Unknown &
		\cite{Robertson2019} &
		\begin{tabular}[c]{@{}l@{}}Noisy Earth Sensor \\ effected pointing \\ accuracy\end{tabular} &
		\begin{tabular}[c]{@{}l@{}}Between x5 and x10 times the \\ normal sensor noise based on \\ Guassian distribution\end{tabular} \\ \hline
		\multirow{2}{*}{Sun sensor} &
		\multirow{2}{*}{-} &
		\begin{tabular}[c]{@{}l@{}}Cross-wired during instal-\\ lation\end{tabular} &
		\cite{Crowell2011} &
		\begin{tabular}[c]{@{}l@{}}Erroneous \\ measurements\end{tabular} &
		Uniform random values \\ \cline{3-6}
		&
		&
		Unknown &
		\cite{Jacklin2019} &
		Sun sensor fails &
		output is 0 \\ \hline
		Star tracker &
		- &
		\begin{tabular}[c]{@{}l@{}}Shutter on star tracker is \\ closed\end{tabular} &
		\cite{Crowell2011} &
		Star tracker fails &
		output is 0 \\ \hline
		Overall control &
		- &
		\begin{tabular}[c]{@{}l@{}}Incorrect control law or \\ variation \\ thereof\end{tabular} &
		\begin{tabular}[c]{@{}l@{}}Gerhard Janse \\ van Vuuren\end{tabular} &
		\begin{tabular}[c]{@{}l@{}}Angular velocity \\ suddenly increases \\ or decreases or \\ oscillation results\end{tabular} &
		\begin{tabular}[c]{@{}l@{}}Increase to 75 - 100\% \\ Decrease to 0 - 25\%\\ Oscillates\end{tabular} \\ \hline
		\multirow{3}{*}{\begin{tabular}[c]{@{}l@{}}Common data \\ transmission errors\end{tabular}} &
		\multirow{3}{*}{-} &
		Sign flip &
		\cite{Crowell2011} &
		Processor-based &
		\begin{tabular}[c]{@{}l@{}}Processor outputs and/or \\ inputs experience a sign flip\end{tabular} \\ \cline{3-6}
		&
		&
		Bit flip &
		N/A &
		&
		\begin{tabular}[c]{@{}l@{}}Processor outputs and/or \\ inputs experience a bit flip flip\end{tabular} \\ \cline{3-6}
		&
		&
		Insertion of zeros &
		\cite{Jacklin2019} &
		&
		\begin{tabular}[c]{@{}l@{}}Processor outputs and/or inputs \\ experience an insertion of a zero\end{tabular} \\ \hline
		\begin{tabular}[c]{@{}l@{}}Possible sensors \\ errors\end{tabular} &
		- &
		Unknown &
		N/A &
		High sensor noise &
		\begin{tabular}[c]{@{}l@{}}Between x5 and x10 times the \\ normal sensor noise based on \\ Guassian distribution\end{tabular} \\ \hline
	\end{tabular}
\end{sidewaystable}

\newpage


\section{Discussion}
Whereas little other research has been devoted to applying genetic programming in the context of the post-operative patient data set, there have been other classifiers used to attempt to solve the classification problem.

Firstly, Owen \cite{owen1999tubular} applied multiple nearest-neighbor approaches to the problem, with the best performant approach achieving an accuracy of 75.8\% using 88 cases (2 cases were not used due to the presence of null values).

Secondly, Luukka \cite{luukka2009pca} explored the use of an expert system to determine - based on hypothermia condition - whether patients in a post-operative recovery area should be sent to Intensive Care
Unit, general hospital floor or go home. The reported results indicate that the system provides a mean classification accuracy of 62.7\%.

Finally, a comparative study of different classification techniques for the post operative patient data set \cite{dash2013comparative} explored various classification problems to the data set. The best of these approaches, referred to in the study as \emph{FuzzyRoughNN}, achieved a classification accuracy of 88.88\%.

When compared to the results discussed above, the classifiers produced by the genetic programming approach applied for this assignment perform relatively well. For instance, the fittest individual achieved a classification accuracy of 87.14\% on the training data and an accuracy of 82.22\% on the entire data set. Whilst results may seem less optimistic when considering that the best accuracy achieved on unseen data was 75.00\%, indicators are still positive that - with additional parameter tuning - better results can be achieved.

While this initial experimentation has proved promising, additional research is still necessary to determine whether a genetic programming approach can produce a classifier which achieves better accuracy than the \emph{FuzzyRoughNN} \cite{dash2013comparative} algorithm. Such research may explore the application of a GP approach using a larger data set which may lend itself better to the evolutionary approach.