\subsection{Instance models}
\label{subsec:formalisations:ecore_formalisation:instance_models}
An instance model represents an instance of a type model. In other words, the metamodel of an instance model is its type model. Because of our definitions of type models, this means that the metametamodel of an instance model is the Ecore metamodel.

An instance model consists of a set of objects, which have a corresponding class they instantiate and an optional identifier. All objects are an instance of a specific class and are therefore typed by that class and its superclasses. Furthermore, an instance model also specifies the values for each field of an object. Its type determines the fields present for each object. Finally, the instance model specifies a set of default values, which assigns a value to each of the named constants from the type model ($Constant_{Tm}$), allowing to assign default values to fields.

As with the type model and type definitions, there is a cyclic dependency between instance models and values. In the same manner, the solution is set to be the smallest solution to the set of equations for the instance model and values.

The suffix $Im$ is used when the definition of something depends on any instance model $Im$, which itself depends on the definition of any type model $Tm$.

\begin{defin}[Instance model]
\label{defin:formalisations:ecore_formalisation:instance_models:instance_model}
For a type model $Tm$,
\begin{equation*}
    Tm = \langle Class, Enum, UserDataType, Field, \mathrm{FieldSig}, EnumValue, Inh, Prop, Constant, \mathrm{ConstType} \rangle
\end{equation*}
a single instance model $Im$ is defined as
\begin{equation*}
    Im = \langle Object, \mathrm{ObjectClass}, \mathrm{ObjectId}, \mathrm{FieldValue}, \mathrm{DefaultValue} \rangle
\end{equation*}
with
\begin{itemize}
    \item $Object$ is the set of objects (class instances) in $Im$.
    \item $\mathrm{ObjectClass}: Object \Rightarrow Class_{Tm}$ is the function that maps each object in $Im$ to a class.
    \item $\mathrm{ObjectId}: Object \Rightarrow Name$ is the injective partial function that maps each object in $Im$ to an identifier.
    \item $\mathrm{FieldValue}: (Object \times Field_{Tm}) \Rightarrow Value_{Im}$ is the partial function between each $Field_{Tm}$ of an $Object_{Im}$ and a $Value_{Im}$ (see \cref{defin:formalisations:ecore_formalisation:instance_models:values}).
    \item $\mathrm{DefaultValue}: Constant_{Tm} \Rightarrow Value_{Im}$ is the function that assigns a value to each constant in the corresponding type model $Tm$.
\end{itemize}
where
\begin{itemize}
    \item $\forall ( o, n ), ( o', n' ) \in ObjectId: n = n' \Longrightarrow o = o'$.
    \item $\forall o \in Object, f \in Field_{Tm}: ( o, f ) \in \mathrm{dom}\ FieldValue \Longleftrightarrow ObjectClass(o) \sqsubseteq_{Tm} \mathrm{class}(f)$.
\end{itemize}

\isabellelref{instance_model}{Ecore.Instance_Model}
\end{defin}

Please note that $\mathrm{ObjectId}$ is injective because each object must have a unique identifier. It is partial because an object does not necessarily need an identifier: The internal object identifiers (the elements of the set $Object$) are already unique. The $\mathrm{ObjectId}$ function is for adding an explicit identifier that is not generated internally.

The $\mathrm{FieldValue}$ function maps a combination of an object and field to a value. Please note that the function is partial because not every combination of object and field is valid. The domain of this function is therefore made explicit by the constraints of the definition. Please note that this function is not injective: Values can be shared across objects and do not have to be unique.

An important function is the $\mathrm{DefaultValue}$ function, which is defined on an instance model rather than a type model. This definition has been chosen to accommodate for default values that reference another object. In order to reference another object, the possible object references need to be known. These object references are only known on the instance level, as the type level does not define any objects.

\begin{figure}[p]
    \centering
    \begin{subfigure}{\textwidth}
        \centering
        \includegraphics{images/03_formalisations/02_ecore_formalisation/instance_model_example.pdf}
        \caption{Instance model based on Ecore notation}
    \end{subfigure}

    \begin{subfigure}{\textwidth}
        \centering
        \begin{align*}
            Object_{Im} =\ & \{
                1, 2, 3, 4, 5, 6
            \}\\
            \mathrm{ObjectClass}_{Im} =\ & \{
                ( 1, .\type{House} ),
                ( 2, .\type{Room} ),
                ( 3, .\type{Room} ),
                ( 4, .\type{Room} ),
                ( 5, .\type{Renter} ),
                ( 6, .\type{Renter} ),
            \}\\
            \mathrm{ObjectId}_{Im} =\ & \{
                ( 1, .\type{SmallHouse} ),
                ( 2, .\type{1} ),
                ( 3, .\type{2} ),
                ( 4, .\type{3} ),
                ( 5, .\type{John} ),
                ( 6, .\type{Jane} )
            \}\\
            \mathrm{FieldValue}_{Im} =\ & \Big\{
                \Big( \big( 1, ( .\type{House}, \type{name} ) \big), \big[ \type{string}, \text{``Small House''} \big] \Big),\\&
                \Big( \big( 1, ( .\type{House}, \type{rooms} ) \big), \big[ \type{setof}, \big\langle [ \type{obj}, 2 ], [ \type{obj}, 3 ], [ \type{obj}, 4 ] \big\rangle \big] \Big),\\&
                \Big( \big( 2, ( .\type{Room}, \type{number} ) \big), \big[ \type{int}, 1 \big] \Big),\
                \Big( \big( 2, ( .\type{Room}, \type{renter} ) \big), \big[ \type{obj}, 5 \big] \Big),\\&
                \Big( \big( 3, ( .\type{Room}, \type{number} ) \big), \big[ \type{int}, 2 \big] \Big),
                \Big( \big( 3, ( .\type{Room}, \type{renter} ) \big), \big[ \type{obj}, 5 \big] \Big),\\&
                \Big( \big( 4, ( .\type{Room}, \type{number} ) \big), \big[ \type{int}, 3 \big] \Big),
                \Big( \big( 4, ( .\type{Room}, \type{renter} ) \big), \big[ \type{obj}, 6 \big] \Big),\\&
                \Big( \big( 5, ( .\type{Person}, \type{name} ) \big), \big[ \type{string}, \text{``John Doe''} \big] \Big),\\&
                \Big( \big( 5, ( .\type{Person}, \type{age} ) \big), \big[ \type{int}, 24 \big] \Big),\\&
                \Big( \big( 5, ( .\type{Renter}, \type{payment\_interval} ) \big), \big[ \type{enum}, ( .\type{PaymentInterval}, \type{MONTH} ) \big] \Big),\\&
                \Big( \big( 5, ( .\type{Renter}, \type{rents} ) \big), \big[ \type{setof}, \big\langle [ \type{obj}, 2 ], [ \type{obj}, 3 ] \big\rangle \big] \Big),\\&
                \Big( \big( 6, ( .\type{Person}, \type{name} ) \big), \big[ \type{string}, \text{``Jane Doe''} \big] \Big),\\&
                \Big( \big( 6, ( .\type{Person}, \type{age} ) \big), \big[ \type{int}, 23 \big] \Big),\\&
                \Big( \big( 6, ( .\type{Renter}, \type{payment\_interval} ) \big), \big[ \type{enum}, ( .\type{PaymentInterval}, \type{MONTH} ) \big] \Big),\\&
                \Big( \big( 6, ( .\type{Renter}, \type{rents} ) \big), \big[ \type{setof}, \big\langle [ \type{obj}, 4 ] \big\rangle \big] \Big)
            \Big\}\\
            \mathrm{DefaultValue}_{Im} =\ & \Big\{
                \Big( .\type{Constant}.\type{PaymentInterval}.\type{Month}, \big[ \type{enum}, ( .\type{PaymentInterval}, \type{MONTH} ) \big] \Big)
            \Big\}
        \end{align*}
        \caption{Formal definition of the instance model}
    \end{subfigure}
    \caption{Example of an instance model corresponding with \cref{defin:formalisations:ecore_formalisation:instance_models:instance_model}}
    \label{fig:formalisations:ecore_formalisation:instance_models:instance_model_example}
\end{figure}

An example model is represented by \cref{fig:formalisations:ecore_formalisation:instance_models:instance_model_example}. It is based on the type model from the example in \cref{fig:formalisations:ecore_formalisation:type_models:type_model_example}.
It shows 2 instantiations of the $\type{Renter}$ class: the $\type{John}$ and $\type{Jane}$ objects. Furthermore, there are three instantiations of the $\type{Room}$ class ($\type{1}$, $\type{2}$ and $\type{3}$) and one instantiation of the $\type{House}$ class ($\type{SmallHouse}$). The text after the colon in the header of each object represents the $ObjectClass_{Im}$ of each object. Additionally, the text preceding the colon represents the $ObjectId_{Im}$. The $\type{Renter}$ objects have values assigned for all fields, including the fields of their superclasses. This also holds for the $\type{Room}$ and $\type{House}$ objects. For attributes, the assignment to a field name represents the value of a field. For relations, a named arrow between two objects represents the value of the field. The name of the arrow represents the field name, and multiple arrows with the same name represent multiple values for the same field.

Note that the objects from the example are represented by elements from $\mathbb{N}^+$. The conceptual model does not give a concrete specification for elements in the $Object_{Im}$ set, but by convention objects (or in graph terms, nodes) are represented by numbers.

For each instance model, a set of possible values is defined by the values for all data types, the possible enumerations of the type model and the objects in the instance model. Each value has a symbol that defines its type, allowing the values in an instance model to be typed by the types in the type model. This symbol also allows values with identical content but a different type to be separated. For example, any value in $\mathbb{Z} \cap \mathbb{R}$ (which can be of type $\type{integer}$ or $\type{real}$). Container values aggregate multiple values, which are typed by container types.

\begin{defin}[Values]
\label{defin:formalisations:ecore_formalisation:instance_models:values}
Given any instance model $Im$, the set of values is $Value_{Im}$.

The set of values is then defined as
\begin{equation*}
    Value_{Im} = AtomValue_{Im} \cup ContainerValue_{Im}
\end{equation*}
with
\begin{itemize}
    \item $AtomValue_{Im} = ClassValue_{Im} \cup LiteralValue \cup (\{ \type{enum} \} \times EnumValue_{Tm}) \cup (\{ \type{data} \times \mathbb{S}\})$
    \item $LiteralValue = (\{ \type{bool} \} \times \mathbb{B}) \cup (\{ \type{int} \} \times \mathbb{Z}) \cup (\{ \type{real} \} \times \mathbb{R}) \cup (\{ \type{string} \} \times \mathbb{S})$
    \item $ClassValue_{Im} = \{ \type{obj} \} \times (Object_{Im} \cup { \type{nil} })$
    \item $ContainerValue_{Im} = \{ \type{setof}, \type{bagof}, \type{seqof}, \type{ordof} \} \times Value_{Im}^*$ (where $Value_{Im}^*$ allows containers to recursively contain other containers.)
\end{itemize}

The set of values is recursively defined as the smallest solution of the given set of equations for $Value_{Im}$ and $ContainerValue_{Im}$. Furthermore, elements of the set $Value_{Im}$ are written using square brackets, e.g. $[\type{string}, \text{``Example''}]$ or $[\type{setof}, \langle [\type{int}, 4], [\type{int}, 8] \rangle]$.

\isabellelref{Value}{Ecore.Instance_Model}
\end{defin}

For custom data types, the value is an element from the set $\mathbb{S}$. In Ecore, custom data types can be made serializable, which means a value from $\mathbb{S}$ can be stored for the custom data type. Thus, the value for a custom data type can be stored in the model, but it cannot be further interpreted.

Containers attributed as $\type{setof}$ or $\type{ordof}$ are considered to have unique values, whereas containers attributed as $\type{bagof}$ or $\type{seqof}$ are not. This means for example that a tuple with two or more identical values is not a valid value for a container attributed as $\type{setof}$ or $\type{ordof}$, see also \cref{defin:formalisations:ecore_formalisation:instance_models:valid_type_values}.

Additionally, the values of a container attributed as $\type{bagof}$ or $\type{setof}$ are considered unordered, and $\type{seqof}$ or $\type{ordof}$ ordered. This affects the equivalency of containers, as defined in \cref{defin:formalisations:ecore_formalisation:instance_models:value_equivalency}.

In the example, the set of atomic values that are assigned consists of
\begin{align*}
    \{&
        [ \type{string}, \text{``Small House''} ],
        [ \type{string}, \text{``John Doe''} ],
        [ \type{string}, \text{``Jane Doe''} ],\\&
        [ \type{int}, 1 ],
        [ \type{int}, 2 ],
        [ \type{int}, 3 ],
        [ \type{int}, 24 ],
        [ \type{int}, 23 ],\\&
        [ \type{enum}, ( .\type{PaymentInterval}, \type{MONTH} ) ]\\&
        [ \type{obj}, 5 ],
        [ \type{obj}, 6 ]
    \}
\end{align*}
Note that only the $\type{Renter}$ objects are in an atomic assigned value for the field $(.\type{Room}, \type{renter})$, as it is the only field that references a single object. All other relations in the type model are container types, and as such all the objects are contained in a container value as well. For example, the container value for the $\type{rooms}$ field of the $\type{House}$ object is $\big[ \type{setof}, \big\langle [ \type{obj}, 2 ], [ \type{obj}, 3 ], [ \type{obj}, 4 ] \big\rangle \big]$ (in no particular order, as the relation is of a set container type).

Each instance model also defines an equivalence relation for values. This relation allows the comparison of aggregate values and explicitly defines equivalency for unordered container values.

\begin{defin}[Value equivalency]
\label{defin:formalisations:ecore_formalisation:instance_models:value_equivalency}
Two values are equivalent $(\equiv_{Im}\: \subseteq Value_{Im} \times Value_{Im})$ if both the type is identical and the actual value content is equivalent. It is defined as the smallest reflexive relation between values and the relations defined by the rules given next.

For atomic values equivalence is defined as
\begin{mathpar}
    \inferrule{v_1 \in Value_{Im} \\ v_2 \in Value_{Im} \\ v_1 = v_2}{v_1 \equiv_{Im} v_2}
\end{mathpar}

Sequences and ordered sets are equivalent if the values in their tuples are pairwise equivalent.
\begin{mathpar}
    \inferrule[Sequence container equivalency]{c_1 = \big[ \type{seqof}, \langle v_1, \dotsc, v_n \rangle \big] \\ c_2 = \big[ \type{seqof}, \langle u_1, \dotsc, u_n \rangle \big] \\ v_1 \equiv_{Im} u_1, \dotsc, v_n \equiv_{Im} u_n}{c_1 \equiv_{Im} c_2}
\end{mathpar}
\begin{mathpar}
    \inferrule[Ordered set container equivalency]{c_1 = \big[ \type{ordof}, \langle v_1, \dotsc, v_n \rangle \big] \\ c_2 = \big[ \type{ordof}, \langle u_1, \dotsc, u_n \rangle \big] \\ v_1 \equiv_{Im} u_1, \dotsc, v_n \equiv_{Im} u_n}{c_1 \equiv_{Im} c_2}
\end{mathpar}

Sets and bags are equivalent if there exists a bijective function which maps elements from one set/bag
to the other, such that the mapped values are equivalent.
\begin{mathpar}
    \inferrule[Set container equivalency]{c_1 = \big[ \type{setof}, \langle v_1, \dotsc, v_n \rangle \big] \\ c_2 = \big[ \type{setof}, \langle u_1, \dotsc, u_n \rangle \big] \\ \exists f: \{1, \dotsc, n\} \bij \{1, \dotsc, n\}: v_i \equiv_{Im} u_{f(i)}}{c_1 \equiv_{Im} c_2}
\end{mathpar}
\begin{mathpar}
    \inferrule[Bag container equivalency]{c_1 = \big[ \type{bagof}, \langle v_1, \dotsc, v_n \rangle \big] \\ c_2 = \big[ \type{bagof}, \langle u_1, \dotsc, u_n \rangle \big] \\ \exists f: \{1, \dotsc, n\} \bij \{1, \dotsc, n\}: v_i \equiv_{Im} u_{f(i)}}{c_1 \equiv_{Im} c_2}
\end{mathpar}

\isabellelref{value_equiv}{Ecore.Instance_Model}
\end{defin}

In the example, the value $\big[ \type{setof}, \big\langle [ \type{obj}, 2 ], [ \type{obj}, 3 ] \big\rangle \big]$ would thus be equivalent to $\big[ \type{setof}, \big\langle [ \type{obj}, 3 ], [ \type{obj}, 2 ] \big\rangle \big]$, as the ordering does not matter for `$\type{setof}$' container types.

For each type in $Type_{Tm}$, there exists a set of values from $Value_{Im}$ which is considered \textit{valid}. This is
defined by a relation $Valid_{Im} \subseteq (Type_{Tm} \times Value_{Im})$ which defines a tuple for each valid value given a type.

\begin{defin}[Valid type values]
\label{defin:formalisations:ecore_formalisation:instance_models:valid_type_values}
The $Valid_{Im}$ set contains tuples which indicate what values are valid for a given type, which is defined by
\begin{equation*}
    Valid_{Im} \subseteq (Type_{Tm} \times Value_{Im})
\end{equation*}

An element $[ T, v ] \in Valid_{Im}$ may be written as
\begin{mathpar}
    \inferrule{\ }{v:_{Im} T}
\end{mathpar}

The contents of the $Valid_{Im}$ set is then defined as follows:

Data type values:
\begin{mathpar}
    \inferrule{v \in \mathbb{B}}{[ \type{bool}, v ]:_{Im} \type{boolean}}
    \and
    \inferrule{v \in \mathbb{Z}}{[ \type{int}, v ]:_{Im} \type{integer}}
    \and
    \inferrule{v \in \mathbb{R}}{[ \type{real}, v ]:_{Im} \type{real}}
    \and
    \inferrule{v \in \mathbb{S}}{[ \type{string}, v ]:_{Im} \type{string}}
\end{mathpar}

Class values:
\begin{mathpar}
    \inferrule{ObjectClass_{Im}(o) = c \\ !c \sqsubseteq_{Tm} t \\ t \in ClassType_{Tm}}{[ \type{obj}, o ]:_{Im} t}
    \and
    \inferrule{t \in \{ \type{nullable} \} \times Class_{Tm}}{[ \type{obj}, \type{nil} ]:_{Im} t}
\end{mathpar}

Enumeration values:
\begin{mathpar}
    \inferrule{( ename, eval ) \in EnumValue_{Tm} \\ ename \in Enum_{Tm}}{[ \type{enum}, ( ename, eval ) ]:_{Im} ename}
\end{mathpar}

User-defined data type values:
\begin{mathpar}
    \inferrule{v \in \mathbb{S} \\ t \in UserDataType_{Tm}}{[ \type{data}, v ]:_{Im} t}
\end{mathpar}

Container values:
\begin{mathpar}
    \inferrule{v_1:_{Im} T, \dotsc, v_n:_{Im} T \\ \langle v_1, \dotsc, v_n \rangle\ \mathrm{distinct} \\ [ \type{setof}, T ] \in Container_{Tm}}{[ \type{setof}, \langle v_1, \dotsc, v_n \rangle ]:_{Im} [ \type{setof}, T ]}
    \and
    \inferrule{v_1:_{Im} T, \dotsc, v_n:_{Im} T \\ [ \type{bagof}, T ] \in Container_{Tm}}{[ \type{bagof}, \langle v_1, \dotsc, v_n \rangle ]:_{Im} [ \type{bagof}, T ]}
    \and
    \inferrule{v_1:_{Im} T, \dotsc, v_n:_{Im} T \\ \langle v_1, \dotsc, v_n \rangle\ \mathrm{distinct} \\ [ \type{ordof}, T ] \in Container_{Tm}}{[ \type{ordof}, \langle v_1, \dotsc, v_n \rangle ]:_{Im} [ \type{ordof}, T ]}
    \and
    \inferrule{v_1:_{Im} T, \dotsc, v_n:_{Im} T \\ [ \type{seqof}, T ] \in Container_{Tm}}{[ \type{seqof}, \langle v_1, \dotsc, v_n \rangle ]:_{Im} [ \type{seqof}, T ]}
\end{mathpar}

\isabellelref{Valid}{Ecore.Instance_Model}
\end{defin}

The validity of an instance model depends on the multiplicity of field values. The valid multiplicities depend on the types and field signatures in the corresponding type model. As a consequence, a valid multiplicity also requires the type of the value to be valid. The multiplicity is of most influence for container values, as they can contain an arbitrary amount of values.

\begin{defin}[Multiplicity validity]
\label{defin:formalisations:ecore_formalisation:instance_models:multiplicity_validity}
A field value $( ( object, field ), value ) \in FieldValue_{Im}$ has a valid multiplicity if the following property holds:
\begin{multline*}
    value:_{Im} \mathrm{type}_{Tm}(field) \land value = [ t, \langle v_1, \dotsc, v_n \rangle ] \in ContainerValue_{Im} \Longrightarrow\\ \mathrm{lower}_{Im}(field) \leq n \leq \mathrm{upper}_{Im}(field)
\end{multline*}

This may be written as $\mathrm{validMul}_{Im}\big((( object, field ), value)\big)$.

\isabellelref{validMul}{Ecore.Instance_Model}
\end{defin}

\begin{figure}
    \centering
    \begin{subfigure}{\textwidth}
        \centering
        \includegraphics{images/03_formalisations/02_ecore_formalisation/multiplicities/type_model.pdf}
        \caption{Example type model}
        \label{fig:formalisations:ecore_formalisation:instance_models:multiplicity_example:type_model}
    \end{subfigure}

    \begin{subfigure}{0.3\textwidth}
        \centering
        \includegraphics{images/03_formalisations/02_ecore_formalisation/multiplicities/invalid_lower.pdf}
        \caption{Invalid instance model: cardinality of $\type{rel}$ too low}
        \label{fig:formalisations:ecore_formalisation:instance_models:multiplicity_example:invalid_lower}
    \end{subfigure}
    \begin{subfigure}{0.3\textwidth}
        \centering
        \includegraphics{images/03_formalisations/02_ecore_formalisation/multiplicities/valid.pdf}
        \caption{Valid instance model: cardinality of $\type{rel}$ within bounds}
        \label{fig:formalisations:ecore_formalisation:instance_models:multiplicity_example:valid}
    \end{subfigure}
    \begin{subfigure}{0.3\textwidth}
        \centering
        \includegraphics{images/03_formalisations/02_ecore_formalisation/multiplicities/invalid_upper.pdf}
        \caption{Invalid instance model: cardinality of $\type{rel}$ too high}
        \label{fig:formalisations:ecore_formalisation:instance_models:multiplicity_example:invalid_upper}
    \end{subfigure}
    \caption{Examples of valid and invalid multiplicities}
    \label{fig:formalisations:ecore_formalisation:instance_models:multiplicity_example}
\end{figure}

The examples shown in \cref{fig:formalisations:ecore_formalisation:instance_models:multiplicity_example} show different multiplicities in instance models. More specifically, \cref{fig:formalisations:ecore_formalisation:instance_models:multiplicity_example:type_model} shows a type model that specifies a multiplicity of $1..2$ for the $\type{rel}$ relation. \cref{fig:formalisations:ecore_formalisation:instance_models:multiplicity_example:invalid_lower} and \cref{fig:formalisations:ecore_formalisation:instance_models:multiplicity_example:invalid_upper} show two instance models that have an invalid multiplicity (too low and too high respectively), whereas \cref{fig:formalisations:ecore_formalisation:instance_models:multiplicity_example:valid} shows an instance model with correct multiplicity (an alternative correct instance model could have only a single instance of class $\type{B}$).

In order to simplify reasoning over assignments of values, the $\mathrm{edgeCount}$ and $\mathrm{edge}$ operators are defined. These operators specify the number of relations (and the existence thereof) between any two objects.

\begin{defin}[Value edges]
\label{defin:formalisations:ecore_formalisation:instance_models:value_edges}
Let $a, b \in Object_{Im}$ and $r \in Field_{Tm}$ where $r \in fields_{Tm}(\mathrm{ObjectClass}_{Im}(a))$. Furthermore, we define $\mathrm{containerCount}_{Im}(a, r, b)$ as
\begin{equation*}
    \mathrm{containerCount}_{Im}(a, r, b) = \big|\big\{ i \in \mathbb{N} \mid \big( (a, r), \big[ t, \langle v_1, \dotsc, v_n \rangle \big] \big) \in \mathrm{FieldValue}_{Im} \land v_i = [ \type{obj}, b ] \big\}\big|
\end{equation*}

Then $\mathrm{edgeCount}_{Im}(a, r, b)$ is defined as
\begin{equation*}
    \mathrm{edgeCount}_{Im}(a, r, b) =
    \begin{cases}
        0, & \begin{aligned}
            \text{if } &\mathrm{type}_{Tm}(r) \not\in Container_{Tm} \\&\land \big( (a, r), [ \type{obj}, b ] \big) \not\in \mathrm{FieldValue}_{Im}
        \end{aligned}\\
        1, & \begin{aligned}
            \text{if } &\mathrm{type}_{Tm}(r) \not\in Container_{Tm} \\&\land \big( (a, r), [ \type{obj}, b ] \big) \in \mathrm{FieldValue}_{Im}
        \end{aligned}\\
        \mathrm{containerCount}_{Im}(a, r, b), & \text{otherwise}
    \end{cases}
\end{equation*}
\isabellelref{edgeCount}{Ecore.Instance_Model}

The $\mathrm{edge}_{Im}(a, r, b)$ predicate is defined as
\begin{equation*}
    \mathrm{edge}_{Im}(a, r, b) = \mathrm{edgeCount}_{Im}(a, r, b) \geq 1
\end{equation*}
\isabellelref{edge}{Ecore.Instance_Model}
\end{defin}

As previously mentioned, the properties specified in a type model must be satisfied by the instance model in order for it to be valid. For each property, there is a satisfaction formula defined, which must hold for a given instance model for that instance model to be valid. The following definition specifies such a formula for each possible property in a type model.

\begin{defin}[Property satisfaction]
\label{defin:formalisations:ecore_formalisation:instance_models:property_satisfaction}
Given an instance model $Im$ and a type model $Tm$, a property $p \in Prop_{Tm}$ can be satisfied, written
as $Im \models p$, if the satisfaction formula holds for $p$.

\begin{itemize}
    \item The abstract property $[ \type{abstract}, c ]$ is satisfied by some instance model $Im$ if none of the objects in $Im$ is typed by class $c$.

    Formally, the satisfaction formula for $Im \models [ \type{abstract}, c ]$ is defined as:
    \begin{equation*}
        \nexists o \in Object_{Im}: \mathrm{ObjectClass}_{Im}(o) = c
    \end{equation*}

    \item The containment property $[ \type{containment}, r ]$ is satisfied for an instance model $Im$ when any object in $Im$ that is the target for a containment relation is contained by no more than one object, and there are no cycles in the instance model given the containment values.

    Let $CR_{Tm} = \{r \mid r \in Rel_{Tm} \land [ \type{containment}, r ] \in Prop_{Tm} \}$ be the set of all containment relations in a type model $Tm$. The satisfaction formula for $Im \models [ \type{containment}, r ]$ is then defined as:
    \begin{align*}
        \forall o \in\ &Object_{Im}\!: \big|\big\{ \big( ( f\!o, f\!\!f ), f\!v \big) \mid \big( ( f\!o, f\!\!f ), f\!v \big) \in \mathrm{FieldValue}_{Im} \land [ \type{obj}, o ] = f\!v \land f\!\!f \in CR_{Tm} \big\}\big| \leq 1 \\&
        \land \big\{ (f\!o, f\!v) \mid \big( ( f\!o, f\!\!f ), f\!v \big) \in \mathrm{FieldValue}_{Im} \land f\!\!f \in CR_{Tm} \big\} \text{ is acyclic}
    \end{align*}

    \item The identity property $[ \type{identity}, c, A ]$. is satisfied for an instance model $Im$, when for each pair of objects of class $c$, the values for at least one of the attributes in $A$ is different.

    Formally, the satisfaction formula for $Im \models [ \type{identity}, c, A ]$ is defined as:
    \begin{align*}
        \forall o, o' \in\ &Object_{Im}\!: \mathrm{ObjectClass}_{Im}(o) = c \land \mathrm{ObjectClass}_{Im}(o') = c \\&\land \forall a \in A\!: \mathrm{FieldValue}_{Im}(( o, a )) \equiv_{Im} \mathrm{FieldValue}_{Im}(( o', a )) \\&\Longrightarrow o = o'
    \end{align*}

    \item The keyset property $[ \type{keyset}, r, A ]$ is satisfied for an instance model $Im$ when for each object containing relation $r$, each pair of objects referenced by $r$ has a different set of values for the attributes in $A$. In other words, for each such pair, there is at least one value for the attributes in $A$ that is different for both objects.

    The satisfaction formula for $Im \models [ \type{keyset}, r, A ]$ is defined as:
    \begin{align*}
        \forall o, o', p \in\ &Object_{Im}\!: r \in \mathrm{fields}_{Tm}(\mathrm{ObjectClass}_{Im}(p))\\&
        \land \mathrm{edge}_{Im}(p, r, o) \land \mathrm{edge}_{Im}(p, r, o')\\&
        \land \forall a \in A\!: \mathrm{FieldValue}_{Im}(( o, a )) \equiv_{Im} \mathrm{FieldValue}_{Im}(( o', a )) \\& \Longrightarrow o = o'
    \end{align*}

    \item The opposite property $[ \type{opposite}, r, r' ]$ is satisfied for an instance model $Im$ when for each object $o$ with a value for $r$, the referenced objects by $r$ have a value for $r'$, which references object $o$. In other words: each object referenced by $r$ must also have a reference $r'$ that references the source object that defined $r$.

    Formally, the satisfaction formula for $Im \models [ \type{opposite}, r, r' ]$ given an instance is defined as:
    \begin{align*}
        \forall o, o' \in Object_{Im}\!: \mathrm{edgeCount}_{Im}(o, r, o') = \mathrm{edgeCount}_{Im}(o', r', o)
    \end{align*}
\end{itemize}

\isabellelref{property_satisfaction}{Ecore.Instance_Model}
\end{defin}

\begin{figure}
    \centering
    \includegraphics{images/03_formalisations/02_ecore_formalisation/properties/invalid_abstract.pdf}
    \caption{Model not satisfying the $\type{abstract}$ property.}
    \label{fig:formalisations:ecore_formalisation:instance_models:properties:abstract}
\end{figure}

\cref{fig:formalisations:ecore_formalisation:instance_models:instance_model_example} shows an example of an instance model that satisfies the $[ \type{abstract}, \type{Person} ]$ property, as no direct instantiations of the $\type{Person}$ class exist. On the other hand, \cref{fig:formalisations:ecore_formalisation:instance_models:properties:abstract} shows an instance model that does not satisfy the property, as the $\type{Person}$ class has been instantiated (by the object $\type{Jane}$).

\begin{figure}[p]
    \centering
    \begin{subfigure}{0.35\textwidth}
        \centering
        \includegraphics{images/03_formalisations/02_ecore_formalisation/properties/containment/type_model.pdf}
        \caption{Example type model with two containment relations}
        \label{fig:formalisations:ecore_formalisation:instance_models:properties:containment:type_model}
    \end{subfigure}
    \begin{subfigure}{0.3\textwidth}
        \centering
        \includegraphics{images/03_formalisations/02_ecore_formalisation/properties/containment/invalid.pdf}
        \caption{Model not satisfying the containment property}
        \label{fig:formalisations:ecore_formalisation:instance_models:properties:containment:invalid}
    \end{subfigure}
    \begin{subfigure}{0.3\textwidth}
        \centering
        \includegraphics{images/03_formalisations/02_ecore_formalisation/properties/containment/valid.pdf}
        \caption{Model satisfying the containment property}
        \label{fig:formalisations:ecore_formalisation:instance_models:properties:containment:valid}
    \end{subfigure}
    \caption{Examples of the $\type{containment}$ property.}
    \label{fig:formalisations:ecore_formalisation:instance_models:properties:containment}
\end{figure}

\cref{fig:formalisations:ecore_formalisation:instance_models:properties:containment:type_model} shows a type model that defines two containment relations, in opposite direction. The instance model given in \cref{fig:formalisations:ecore_formalisation:instance_models:properties:containment:invalid} does not satisfy the satisfaction formula for the containment property, as there exists a cycle of containment relations. This is corrected in the instance model in \cref{fig:formalisations:ecore_formalisation:instance_models:properties:containment:valid}, where such a cycle does not exist (and each object is containment by at most one other object).

\begin{figure}[p]
    \centering
    \includegraphics{images/03_formalisations/02_ecore_formalisation/properties/invalid_identity.pdf}
    \caption{Model not satisfying the $\type{identity}$ property.}
    \label{fig:formalisations:ecore_formalisation:instance_models:properties:identity}
\end{figure}

To illustrate the satisfaction of a $\textsf{identity}$ property, assume the type model in \cref{fig:formalisations:ecore_formalisation:type_models:type_model_example} specifies an identity property for the $\type{name}$ and $\type{age}$ attributes of the $\type{Renter}$ object. Formally, we define the following property:
\begin{equation*}
  \big[ \textsf{identity}, .\type{Renter}, \big\{ ( .\type{Person}, \type{name} ), ( .\type{Person}, \type{age} ) \big\} \big]
\end{equation*}

The example in \cref{fig:formalisations:ecore_formalisation:instance_models:properties:identity} shows an instance model that does not satisfy the property, as the $\type{Renter}$ objects share the same values for the $\type{name}$ and $\type{age}$ attributes, but are still identified as different objects. In \cref{fig:formalisations:ecore_formalisation:instance_models:instance_model_example} the values of the $\type{name}$ and $\type{age}$ attributes are not the same, and thus the property would be satisfied.

\begin{figure}[p]
    \centering
    \begin{subfigure}{0.45\textwidth}
        \centering
        \includegraphics{images/03_formalisations/02_ecore_formalisation/properties/keyset/type_model.pdf}
        \caption{Example type model with relation $\type{rel}$ that has the keyset property defined on field $\type{key}$}
        \label{fig:formalisations:ecore_formalisation:instance_models:properties:keyset:type_model}
    \end{subfigure}
    \begin{subfigure}{0.25\textwidth}
        \centering
        \includegraphics{images/03_formalisations/02_ecore_formalisation/properties/keyset/invalid.pdf}
        \caption{Model not satisfying the keyset property}
        \label{fig:formalisations:ecore_formalisation:instance_models:properties:keyset:invalid}
    \end{subfigure}
    \begin{subfigure}{0.25\textwidth}
        \centering
        \includegraphics{images/03_formalisations/02_ecore_formalisation/properties/keyset/valid.pdf}
        \caption{Model satisfying the keyset property}
        \label{fig:formalisations:ecore_formalisation:instance_models:properties:keyset:valid}
    \end{subfigure}
    \caption{Examples of the $\type{keyset}$ property.}
    \label{fig:formalisations:ecore_formalisation:instance_models:properties:keyset}
\end{figure}

An example of the keyset property is shown in \cref{fig:formalisations:ecore_formalisation:instance_models:properties:keyset}. In \cref{fig:formalisations:ecore_formalisation:instance_models:properties:keyset:type_model}, we see the type model of this example. We assume there exists a class $\type{A}$ which can reference objects of class $\type{B}$ through relation $\type{rel}$. Furthermore, we assume that the $\type{key}$ field on class $\type{B}$ is used as key for the relation $\type{rel}$. In that case, \cref{fig:formalisations:ecore_formalisation:instance_models:properties:keyset:invalid} shows a violation of the $\type{keyset}$ property, because the 2 objects of type $\type{B}$ have the same value for $\type{key}$. In \cref{fig:formalisations:ecore_formalisation:instance_models:properties:keyset:valid}, the property is satisfied as both objects of type $\type{B}$ have a different value for $\type{key}$.

\begin{figure}[p]
    \centering
    \includegraphics{images/03_formalisations/02_ecore_formalisation/properties/invalid_opposite.pdf}
    \caption{Model not satisfying the $\type{opposite}$ property.}
    \label{fig:formalisations:ecore_formalisation:instance_models:properties:opposite}
\end{figure}

In \cref{fig:formalisations:ecore_formalisation:instance_models:properties:opposite}, an example model is shown which does not satisfy the opposite property for the $\type{rents}$ and $\type{renter}$ relations. Although the number of relations is equal, they do not have the same source and target objects (in opposite direction). The example model in \cref{fig:formalisations:ecore_formalisation:instance_models:instance_model_example} does in fact satisfy the property.

With the previous definitions, it is now possible to define when an instance model itself is valid, given its type model.

\begin{defin}[Model validity]
\label{defin:formalisations:ecore_formalisation:instance_models:model_validity}
An instance model $Im$ is said to be valid with respect to type model $Tm$ if and only if
\begin{itemize}
    \item All values are correctly typed: $\forall ( ( obj, f\!ield ), val ) \in \mathrm{FieldValue}_{Im}\!: val:_{Im} \mathrm{type}_{Tm}(f\!ield)$.
    \item All container multiplicities are valid: $\forall fv \in \mathrm{FieldValue}_{Im}\!: \mathrm{validMul}_{Im}(f\!v)$.
    \item All properties are satisfied: $\forall p \in Prop_{Tm}\!: Im \models p$
    \item All default values have the correct type: $\forall c \in Constant_{Tm}\!: \mathrm{DefaultValue}_{Im}(c):_{Im} \mathrm{ConstType}_{Tm}(c)$.
    \item $Tm$ is consistent, as defined in \cref{defin:formalisations:ecore_formalisation:type_models:type_model_consistency}.
\end{itemize}

The validity of $Im$ with respect to $Tm$ is written as $Tm \vdash Im$.
\isabellelref{instance_model}{Ecore.Instance_Model}
\end{defin}


\section{Compact and Locally Compact Spaces}
\subsection{Compact Spaces}

\paragraph{2.}
  I further assume that $X$ is Hausdorff.
\begin{proof}
  Assume, to obtain a contradiction, that $F_n = K_n\setminus O \ne\varnothing$
  for every $n$. Since $F_n \supset F_{n+1}$, $\{F_n\}$ is collection of closed
  subsets of compact set $K_1$ with finite intersection property. Hence,
  $\bigcap F_n$ is nonempty, contradicting with $\bigcap K_n \subset O$.
\end{proof}

\paragraph{3.}
\begin{proof}
  Let $F$ be a closed set and $x \notin F$. Since $X$ is Hausdorff, for every
  $y \in F$, there are two disjoint open sets $U_y$ and $O_y$ s.t. $y \in U_y$
  and $x \in O_y$. Since $X$ is compact, so is $F$. Note that $\{U_y\}$ is an
  open cover for $F$. Hence, it has a finite subcover $\{U_{y_i}\}_{i=1}^n$.
  Let $U = \bigcup U_{y_i}$ and $O = \bigcap O_{y_i}$. Clear that they are
  disjoint open sets s.t. $F \subset U$ and $x \in O$.
\end{proof}

\paragraph{6.}
\begin{proof}
  Let $\vep > 0$ be fixed. Since $\mcal{F}$ is equicontinuous, for every
  $x \in X$, there is a neighborhood $O_x$ s.t. for every $x\hp \in X$,
  $\sigma(f(x), f(x\hp)) < \vep$. Clear that $\{O_x\}$ is an open cover and
  since $X$ is compact, it has a finite subcover $\{O_{x_i}\}_{i=1}^m$.

  For $x_i$, since $f_n(x_i) \to f(x_i)$, there is an integer $N_i$ s.t. for
  every $n > N$, $\sigma(f_n(x_i), f(x_i)) < \vep$. Since $\sigma(f_n(x_i),
  f_n(x)) < \vep$ holds for all $n$, $\sigma(f(x_i), f(x)) \le \vep$.
  Hence, for every $x \in O_{x_i}$ and $n > N$,
  \[
    \sigma(f_n(x), f(x))
    \le \sigma(f_n(x), f_n(x_i)) + \sigma(f_n(x_i), f(x_i))
      + \sigma(f(x_i), f(x))
    < 3\vep.
  \]
  Let $N = \max N_{x_i}$ and we get the desired result.
\end{proof}

\subsection{Countable Compactness and the Bolzano-Weierstrass Property}
\paragraph{9.}
\begin{proof}
  $\,$\par
  (a) It follows immediately from the definition and Problem 8.20.

  (b) For every $\alpha \in \mathbb{R}$,
  \[
    f + g < \alpha
    \quad\text{iff}\quad
    f < \alpha - g
    \quad\text{iff}\quad
    \exists q\in \mathbb{Q} \text{ s.t. } f < q,\, q < \alpha - g.
  \]
  Hence,
  \[
    \{f + g < \alpha\}
    = \bigcup_{q \in \mathbb{Q}} \{f < q\} \cap \{g < \alpha - q\},
  \]
  which is open. Thus, $f + g$ is also upper semicontinuous.

  (c) Since $(f_n)$ is a decreasing sequence, we can write $f(x) = \inf_n
  f_n(x)$. Hence, for every $\alpha \in \mathbb{R}$, $f < \alpha$ iff there
  exists some $n$ s.t. $f_n(x) < \alpha$. Hence,
  \[
    \{f < \alpha\} = \bigcup_n \{f_n < \alpha\},
  \]
  which is open. Thus, $f$ is also upper semicontinuous.

  (d) Note that $(f_n - f)$ is a decreasing sequence of upper semicontinuous
  functions that converges to $0$. Hence, by Dini's theorem, the convergence is
  uniform.

  (e) Suppose that $x \in \{f < \alpha\}$. Let $\vep$ be a positive real
  number. Since $f_n \to f$ uniformly, there is an integer $n$ s.t.
  $|f(y) - f_n(y)| < \vep$ for all $y \in X$. Meanwhile, since $f_n$ is upper
  semicontinuous, there is a $\delta > 0$ s.t. for every $y$ in the
  $\delta$-ball $B$ centered at $x$, $f_n(y) < f_n(x) + \vep$. Hence, for every
  $y \in B$,
  \begin{align*}
    f(y) = f(y) - f_n(y) + f_n(y) - f_n(x) + f_n(x) - f(x) + f(x)
    \le 3\vep + f(x).
  \end{align*}
  Thus, for sufficiently small $\vep > 0$, we have $B \subset \{f < \alpha\}$.
  Namely, $\{f < \alpha\}$ is open whence $f$ is upper semicontinuous.
\end{proof}

\paragraph{10.}
\begin{proof}
  $\,$\par
  (i. $\Rightarrow$ iii.) Let $f$ be a bounded continuous real-valued function
  and $M := \sup f < \infty$. Let $F_n = \{f \ge M - 1/n\}$. Since $f$ is
  continuous, $F_n$ is closed. Note that $(F_n)$ is a countable family of
  closed sets with finite intersection property. Hence, $\bigcap F_n =
  \{f \ge M\}$ is nonempty as $X$ is countably compact. Namely, the maximum
  can be attained.

  (iii. $\Rightarrow$ ii.) Let $f$ be a continuous function and assume, to
  obtain a contradiction, that $f$ is unbounded. Then the function
  $-1/(|f| + 1)$ is a continuous bounded function whose maximum can not be
  attained. Contradiction.

  (ii. $\Rightarrow$ i.) Assume, to obtain a contradiction, that $X$ does not
  have the Bolzano-Weierstrass property, that is, there is a sequence $(x_n)$
  in $X$ that has no cluster point. Then $F := \{x_n\}_{n=1}^\infty$ is closed.
  Define $f: F \to \mathbb{R}$ by $f(x_n) = n$. Note that $f$ is continuous on
  $F$ and by Tietze's extension theorem, it can be continuously extended to
  $X$. However, $f$ is unbounded, contradicting (ii.). Thus $X$ has the
  Bolzano-Weierstrass and, therefore, is countably compact.
\end{proof}

\subsection{Products of Compact Spaces}
\paragraph{13.}
\begin{proof}
  Let $E$ be a closed and bounded set in $\mathbb{R}^n$. Then it is contained
  in some closed cube $K = \prod_{i=1}^n[a_i, b_i]$. By Tychonoff's theorem,
  $K$ is compact. Thus, $K$, a closed subset of a compact set, is also compact.
\end{proof}

\paragraph{15.}
\begin{proof}
  Let $X = \prod_{n=1}^\infty$ be the product of sequentially compact spaces
  $(X_n)$. Let $(x_n)$ be a sequence in $X$. Since $X_1$ is sequentially
  compact, we may choose a subsequence $x_n^1$ of $x_n$ s.t. the first
  coordinate of $(x_n^1)$ converges to some $x^1$. Similarly, from $(x_n^1)$ we
  may choose a subsequence $x_n^2$ whose second coordinate converges to some
  $x^2$. Proceed inductively and we get a sequence of sequence. Finally,
  consider the sequence $(x_n^n)$. Since each coordinate converges and we are
  dealing with the product topology, $x_n^n$ converges to $(x_1, x_2, \dots)$.
\end{proof}

\subsection{Locally Compact Spaces}
\paragraph{18.}
\begin{proof}
  For every $x \in K$, since $X$ is locally compact, there is an open set
  $O_x$ with $\cl O_x$ compact. Note that $\{O_x\}_{x\in K}$ is an open cover
  for the compact set $K$. Hence, it has a finite subcover
  $\{O_{x_i}\}_{i=1}^n$. Then, $O = \bigcup_{i=1}^n O_{x_i}$ is an open set
  containing $K$ whose closure is compact.
\end{proof}

\paragraph{19.}
\begin{proof}
  $\,$\par
  (a) Since $X$ is a locally compact Hausdorff space and $K$ is compact, there
  exists an open set $V$ with compact closure s.t. $V\supset K$. Since
  $\cl V$ is compact, it is normal. Therefore, by Urysohn's lemma, there is
  a continuous function $f: \cl V \to [0, 1]$ s.t. $f\equiv 1$ on $K$ and
  $f\equiv 0$ on $\partial V$. Extend $f$ to $X$ by setting $f \equiv 0$
  outsides $\cl V$. Then $f$ is continuous and $f \equiv 1$ on $K$. Meanwhile,
  since $\supp f\subset \cl V$, it is also compact.
\end{proof}

\paragraph{24.}
  Assume that $X$ is also Hausdorff.
\begin{proof}
  $\,$\par
  (a) Clear that if $F$ is closed, so is $F\cap K$ for each closed compact
  $K$. For the reverse, we show that $F^c$ is open.
  Let $x \notin F$. Since $X$ is locally compact, there is a neighborhood $U$
  of $x$ whose closure is compact. If $F\cap\cl U = \varnothing$, then we are
  done. If $F\cap \cl U \ne \varnothing$, then by the hypothesis, it is closed.
  Therefore, $U\setminus(F\cap\cl U)$ is again an open neighborhood of $x$.
  Since $X$ is a locally compact Hausdorff space, we can find an open
  neighborhood $V$ with $\cl V \subset U\setminus(F\cap\cl U)$. In both cases,
  $F^c$ is open.

  (b) Suppose that for each closed compact $K$, $F\cap K$ is closed. For every
  $x \in \cl F$, since $X$ is first-countable, there exists a sequence $(x_n)
  \subset F$ which converges to $x$. Then $E := \{x\}\cup\{x_n\}_{n=1}^\infty$
  is closed and compact. Thus, by the hypothesis, $F\cap E$ is also closed,
  which implies that $x \in F$. Hence, $F$ is closed.
\end{proof}

\paragraph{26.}
  Assume that $X$ is Hausdorff.
\begin{proof}
  Let $x$ be an arbitrary point in $X$ and $V$ any neighborhood of $x$. Since
  $X$ is a locally compact Hausdorff space, we may choose a open neighborhood
  $U_1$ of $x$ whose closure is compact and contained by $V$. Since $O_1$ is
  dense, $U_1\cap O_1$ is a nonempty neighborhood of $x$. Then, choose a
  neighborhood $U_2$ of $x$ s.t. $\cl U$ is compact and $\cl U \subset
  U_1\cap O_1$. Proceed inductively and we get a sequence $(U_n)$ s.t.
  $\cl U_n$ is compact and $\cl U_{n+1} \subset O_n\cap U_n$.

  Since $(\cl U_n)$ is a nested sequence of compact sets, $\bigcap \cl U_n$
  is nonempty. Choose $x_* \in \bigcap\cl U_n$. For every $O_n$, $x_*
  \in \cl U_{n+1} \subset O_n$. Thus, $x_* \in V\cap\bigcap_{n=1}^\infty O_n$.
  Namely, $\bigcap_{n=1}^\infty O_n$ is dense.
\end{proof}

\paragraph{29.}
\begin{proof}
  $\,$\par
  (a) Let $F$ be a closed subset of a locally compact space $X$. For every
  $x\in F\subset X$, there is a neighborhood $U$ of $x$ whose closure is
  compact in $X$. Then, $U\cap F$ is also compact. Thus, $F$ is locally
  compact.

  (b) Let $O$ be an open subset of a locally compact Hausdorff space $X$. For
  every $x\in O \subset X$, there is a neighborhood $U$ of $x$ whose closure is
  compact in $X$ and contained by $O$. Note that $\cl U$ is also compact in
  $O$. Thus, $O$ is locally compact.
\end{proof}


\documentclass[a4paper,titlepage]{article}
\usepackage[utf8]{inputenc}
\usepackage{fullpage}
\usepackage{indentfirst}
\usepackage[per-mode=symbol]{siunitx}
\usepackage{listings}
\usepackage{graphicx}
\usepackage{color}
\usepackage{amsmath}
\usepackage{array}
\usepackage[hidelinks]{hyperref}
\usepackage[format=plain,font=it]{caption}
\usepackage{subcaption}
\usepackage{standalone}
\usepackage[nottoc]{tocbibind}
\usepackage[noabbrev,capitalize,nameinlink]{cleveref}
\usepackage{listings}
\usepackage{titlesec}
\usepackage{minted}
\usepackage{booktabs}
\usepackage{csvsimple}
\usepackage{siunitx}
\usepackage[super]{nth}
\usepackage[titletoc]{appendix}

% Custom commands
\newcommand\numberthis{\addtocounter{equation}{1}\tag{\theequation}}
\newcommand{\code}[1]{\texttt{#1}}
\newcolumntype{P}[1]{>{\centering\arraybackslash}p{#1}}

\setminted{linenos,breaklines,fontsize=auto}

%\titleformat*{\section}{\normalsize\bfseries}
%\titleformat*{\subsection}{\small\bfseries}
\renewcommand{\thesubsection}{\thesection.\alph{subsection}}
\providecommand*{\listingautorefname}{Listing}
\newcommand*{\Appendixautorefname}{Appendix}

%opening
\title{\textbf{ECSE 543 \\ Assignment 1}}
\author{Sean Stappas \\ 260639512}
\date{October \nth{21}, 2017}

\begin{document}
	\sloppy
	\maketitle

	\tableofcontents

	\twocolumn

	\section*{Introduction}

	The code for this assignment was created in Python 2.7 and can be seen in \autoref{appendix:code}. To perform the required tasks in this assignment, a custom \mintinline{python}{Matrix} class was created, with useful methods such as add, multiply, transpose, etc. This package can be seen in the \mintinline{python}{matrices.py} file shown in \autoref{lst:matrices}. The structure of the rest of the code will be discussed as appropriate for each question. Output logs of the program are provided in \autoref{appendix:logs}.

	The only packages used that are not built-in are those for fitting curves and creating the plots for this report. These include \mintinline{python}{matplotlib} for plotting, \mintinline{python}{numpy} for curve fitting and \mintinline{python}{sympy} for printing mathematical symbols on the plots. Curve fitting was used to fit the $R(N)$ function in Question 2 and to fit polynomial complexity functions to the number of iterations or runtime of various parts of the program. For any curve fit, the fitting function is given in the legend of the associated plot.

	\section{Choleski Decomposition}

	The source code for the Question 1 program can be seen in the \mintinline{python}{q1.py} file, shown in \autoref{lst:q1}.

	\subsection{Choleski Program}
	% Write a program to solve the matrix equation Ax=b by Choleski decomposition. A is a real, symmetric, positive-definite matrix of order n.

	The code relating specifically to Choleski decomposition can be seen in the \mintinline{python}{choleski.py} file shown in \autoref{lst:choleski}. It is separated into \mintinline{python}{elimination} and \mintinline{python}{back_substitution} methods.

	\subsection{Constructing Test Matrices}
	% Construct some small matrices (n = 2, 3, 4, or 5) to test the program. Remember that the matrices must be real, symmetric and positive-definite. Explain how you chose the matrices.

	The matrices were constructed with the knowledge that, if $A$ is positive-definite, then $A = LL^T$ where L is a lower triangular non-singular matrix. The task of choosing valid $A$ matrices then boils down to finding non-singular lower triangular $L$ matrices. To ensure that $L$ is non-singular, one must simply choose nonzero values for the main diagonal. The Choleski decomposition algorithm then validates that the matrix is positive definite during the elimination phase, throwing an error if it is not. The positive definite validation of these test matrices can be seen in \autoref{lst:q1_log}.

	\subsection{Test Runs}
	% Test the program you wrote in (a) with each small matrix you built in (b) in the following way: invent an x, multiply it by A to get b, then give A and b to your program and check that it returns x correctly.

	The matrices were tested by inventing $x$ matrices, and checking that the program solves for that $x$ correctly. The output of the program, comparing expected and obtained values of $x$, can be seen in \autoref{lst:q1_log}.

	\subsection{Linear Networks}
	% Write a program that reads from a file a list of network branches (Jk, Rk, Ek) and a reduced incidence matrix, and finds the voltages at the nodes of the network. Use the code from part (a) to solve the matrix problem. Explain how the data is organized and read from the file. Test the program with a few small networks that you can check by hand. Compare the results for your test circuits with the analytical results you obtained by hand. Cleary specify each of the test circuits used with a labeled schematic diagram.

	The code relating to solving linear networks can be found in the \mintinline{python}{linear_networks.py} file and is shown in \autoref{lst:linear_networks}. Here, the \mintinline{python}{csv_to_network_branch_matrices} method reads from a CSV file where row $k$ contains the $J_k$, $R_k$ and $E_k$ values. It then converts the resistances to a diagonal admittance matrix $Y$ and produces the $J$ and $E$ column vectors. The incidence matrix $A$ is also read directly from file, as seen in \autoref{lst:q1}.

	First, the program was tested with various circuits. These circuits are labeled 1 to 6 and can be seen in \cref{fig:q1_circuit_1,fig:q1_circuit_2,fig:q1_circuit_3,fig:q1_circuit_4,fig:q1_circuit_5,fig:q1_circuit_6}. The corresponding voltages solved by SPICE at each node can be seen in \cref{table:q1_circuit_1,table:q1_circuit_2,table:q1_circuit_3,table:q1_circuit_4,table:q1_circuit_5,table:q1_circuit_6}. Each circuit has corresponding incidence matrix and network branch CSV files, located in the \mintinline{python}{network_data} directory. For each circuit, the program obtains the expected voltages, as seen in the output in \autoref{lst:q1_log}.

	% TODO: Add listings of program output here?

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=0.5\columnwidth]{plots/q1_circuit_1.pdf}
		\caption
		{Test circuit 1 with labeled nodes.}
		\label{fig:q1_circuit_1}
	\end{figure}

	\begin{table}[!htb]
		\centering
		\caption{Voltage at labeled nodes of circuit 1.}
		\csvautobooktabular{csv/q1_circuit_1.csv}
		\label{table:q1_circuit_1}
	\end{table}

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=0.5\columnwidth]{plots/q1_circuit_2.pdf}
		\caption
		{Test circuit 2 with labeled nodes.}
		\label{fig:q1_circuit_2}
	\end{figure}

	\begin{table}[!htb]
		\centering
		\caption{Voltage at labeled nodes of circuit 2.}
		\csvautobooktabular{csv/q1_circuit_2.csv}
		\label{table:q1_circuit_2}
	\end{table}

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=0.5\columnwidth]{plots/q1_circuit_3.pdf}
		\caption
		{Test circuit 3 with labeled nodes.}
		\label{fig:q1_circuit_3}
	\end{figure}

	\begin{table}[!htb]
		\centering
		\caption{Voltage at labeled nodes of circuit 3.}
		\csvautobooktabular{csv/q1_circuit_3.csv}
		\label{table:q1_circuit_3}
	\end{table}

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=0.75\columnwidth]{plots/q1_circuit_4.pdf}
		\caption
		{Test circuit 4 with labeled nodes.}
		\label{fig:q1_circuit_4}
	\end{figure}

	\begin{table}[!htb]
		\centering
		\caption{Voltage at labeled nodes of circuit 4.}
		\csvautobooktabular{csv/q1_circuit_4.csv}
		\label{table:q1_circuit_4}
	\end{table}

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=0.75\columnwidth]{plots/q1_circuit_5.pdf}
		\caption
		{Test circuit 5 with labeled nodes.}
		\label{fig:q1_circuit_5}
	\end{figure}

	\begin{table}[!htb]
		\centering
		\caption{Voltage at labeled nodes of circuit 5.}
		\csvautobooktabular{csv/q1_circuit_5.csv}
		\label{table:q1_circuit_5}
	\end{table}

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=0.75\columnwidth]{plots/q1_circuit_6.pdf}
		\caption
		{Test circuit 6 with labeled nodes.}
		\label{fig:q1_circuit_6}
	\end{figure}

	\begin{table}[!htb]
		\centering
		\caption{Voltage at labeled nodes of circuit 6.}
		\csvautobooktabular{csv/q1_circuit_6.csv}
		\label{table:q1_circuit_6}
	\end{table}

	\section{Finite Difference Resistive Mesh}

	The source code for the Question 2 program can be seen in the \mintinline{python}{q2.py} file shown in \autoref{lst:q2}.

	\subsection{Equivalent Resistance}
	% Using the program you developed in question 1, find the resistance, R, between the node at the bottom left corner of the mesh and the node at the top right corner of the mesh, for N = 2, 3, …, 10. (You will probably want to write a small program that generates the input file needed by the network analysis program. Constructing by hand the incidence matrix for a 200-node network is rather tedious).

	The code for creating all the network matrices and for finding the equivalent resistance of an $N$ by $2N$ mesh can be seen in the \mintinline{python}{linear_networks.py} file shown in \autoref{lst:linear_networks}. To find the equivalent resistance of the mesh, a current source between the top right node and ground was added. Finding the resistance is then simply measuring the voltage at that node and dividing by the test current, which is \SI{10}{\milli\ampere}. The \mintinline{python}{create_network_matrices_mesh} method creates the incidence matrix $A$, the admittance matrix $Y$, the current source matrix $J$ and the voltage source matrix $E$. The matrix $A$ is created by reading the associated numbered \mintinline{python}{incidence_matrix} CSV files inside the \mintinline{python}{network_data} directory. Similarly, the $Y$, $J$ and $E$ matrices are created by reading the \mintinline{python}{network_branches} CSV files in the same directory. Each of these files contains a list of network branches $(J_k, R_k, E_k)$. The resistances found by the program for values of $N$ from 2 to 10 can be seen in \autoref{table:q2a}.

	\begin{table}[!htb]
		\centering
		\caption{Mesh equivalent resistance R versus mesh size N.}
		\csvautobooktabular{csv/q2a.csv}
		\label{table:q2a}
	\end{table}

	The resistance values returned by the program for small meshes were validated using simple SPICE circuits. The voltage found at the $V_{test}$ node for the 2x4 mesh shown in \autoref{fig:q2a_mesh_2} is \SI{1.875}{\volt} and the equivalent resistance is therefore \SI{1875}{\ohm}. Similarly, for the 3x6 mesh (\autoref{fig:q2a_mesh_3}), $V_{test} = \SI{2.37955}{\volt}$ and the equivalent resistance is \SI{2379.55}{\ohm}. These match the results found by the program, as seen in \autoref{table:q2a}. Bigger mesh circuits were not tested, but these results give at least some confidence that the program is working correctly.

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=\columnwidth]{plots/q2a_mesh_2.pdf}
		\caption
		{SPICE circuit used to test the 2x4 mesh.}
		\label{fig:q2a_mesh_2}
	\end{figure}

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=\columnwidth]{plots/q2a_mesh_3.pdf}
		\caption
		{SPICE circuit used to test the 3x6 mesh.}
		\label{fig:q2a_mesh_3}
	\end{figure}

	\subsection{Time Complexity}
	% In theory, how does the computer time taken to solve this problem increase with N, for large N? Are the timings you observe for your practical implementation consistent with this? Explain your observations.

	The runtime data for the mesh resistance solver is plotted in \autoref{fig:q2b}. The overall runtime of the program is dominated by the initial matrix multiplication to form $AYA^T$, which is $O(N^6)$, and this will be true for the banded and non-banded versions of the Choleski program. This matches the results seen in \autoref{fig:q2b}.

%	\begin{table}[!htb]
%		\centering
%		\caption{Runtime of non-banded mesh resistance solver program versus mesh size $N$.}
%		\csvautobooktabular{csv/q2b.csv}
%		\label{table:q2b}
%	\end{table}

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=\columnwidth]{plots/q2b.pdf}
		\caption
		{Runtime of non-banded mesh resistance solver program versus mesh size $N$.}
		\label{fig:q2b}
	\end{figure}

	To better display the benefits of banded Choleski elimination, we will look specifically at the runtime of the Choleski elimination and back-substitution, which is plotted in \autoref{fig:q2b_choleski}. Theoretically, the time complexity of the non-banded Choleski program should be $O(N^6)$. However, as can be seen in \autoref{fig:q2b_choleski}, $O(N^5)$ more closely matches the obtained data. The simple Choleski program is therefore more efficient than expected. This may be because of successful branch prediction on the repeated zeros of the matrix when performing elimination, or because of the relatively small amount of data points.

%	\begin{table}[!htb]
%		\centering
%		\caption{Runtime of non-banded Choleski program versus mesh size $N$.}
%		\csvautobooktabular{csv/q2b_choleski.csv}
%		\label{table:q2b_choleski}
%	\end{table}

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=\columnwidth]{plots/q2b_choleski.pdf}
		\caption
		{Runtime of non-banded Choleski program versus mesh size $N$.}
		\label{fig:q2b_choleski}
	\end{figure}

	\subsection{Sparsity Modification}
	% Modify your program to exploit the sparse nature of the matrices to save computation time. What is the half-bandwidth b of your matrices? In theory, how does the computer time taken to solve this problem increase now with N, for large N? Are the timings you for your practical sparse implementation consistent with this? Explain your observations.

	 By inspection of the constructed network matrices, a half-bandwidth of $b = 2N + 1$ was chosen for the banded version of the program. The runtime data for the banded mesh resistance solver is plotted in \autoref{fig:q2c}. Once again, the program is dominated by the $O(N^6)$ initial matrix multiplication, which matches the obtained results. The runtime of the banded Choleski program is plotted in \autoref{fig:q2c_choleski}. Theoretically, the banded version of the Choleski program should have a time complexity of $O(N^4)$, which also matches the experimental results.

%	\begin{table}[!htb]
%		\centering
%		\caption{Runtime of banded mesh resistance solver program versus mesh size $N$.}
%		\csvautobooktabular{csv/q2c.csv}
%		\label{table:q2c}
%	\end{table}

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=\columnwidth]{plots/q2c.pdf}
		\caption
		{Runtime of banded mesh resistance solver program versus mesh size $N$.}
		\label{fig:q2c}
	\end{figure}

%	\begin{table}[!htb]
%		\centering
%		\caption{Runtime of banded Choleski program versus mesh size $N$.}
%		\csvautobooktabular{csv/q2c_choleski.csv}
%		\label{table:q2c_choleski}
%	\end{table}

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=\columnwidth]{plots/q2c_choleski.pdf}
		\caption
		{Runtime of banded Choleski program versus mesh size $N$.}
		\label{fig:q2c_choleski}
	\end{figure}

	The runtime of the banded and non-banded versions of the Choleski program are plotted together in \autoref{fig:q2bc_choleski}, showing the clear benefits of banded elimination.

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=\columnwidth]{plots/q2bc_choleski.pdf}
		\caption
		{Comparison of runtime of banded and non-banded Choleski programs versus mesh size $N$.}
		\label{fig:q2bc_choleski}
	\end{figure}

	\subsection{Resistance vs. Mesh Size}
	% Plot a graph of R versus N. Find a function R(N) that fits the curve reasonably well and is asymptotically correct as N tends to infinity, as far as you can tell.

	The equivalent mesh resistance $R$ is plotted versus the mesh size $N$ in \autoref{fig:q2d}. The function $R(N)$ appears logarithmic, and a log function does indeed fit the data well. As shown in \autoref{fig:q2d}, $R(N) = 1260.81\log{N} + 996.28$ is a good fit, where $R$ is in $\Omega$.

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=\columnwidth]{plots/q2d.pdf}
		\caption
		{Resistance of mesh versus mesh size $N$.}
		\label{fig:q2d}
	\end{figure}

	\section{Coaxial Cable}

	The source code for the Question 3 program can be seen in the \mintinline{python}{q3.py} file shown in \autoref{lst:q3}.

	\subsection{SOR Program}
	% Write a computer program to find the potential at the nodes of a regular mesh in the air between the conductors by the method of finite differences. Use a five-point difference formula. Exploit at least one of the planes of mirror symmetry that this problem has. Use an	equal node-spacing, h, in the x and y directions. Solve the matrix equation by successive	over-relaxation (SOR), with SOR parameter w. Terminate the iteration when the magnitude	of the residual at each free node is less than 10^-5.

	The source code for the finite difference methods can be seen in the \mintinline{python}{finite_diff.py} file shown in \autoref{lst:finite_diff}. Horizontal and vertical symmetries were exploited by only solving for a quarter of the coaxial cable, and reproducing the results where necessary. The initial potential values are guessed based on a simple function which decreases radially from the center conductor.

	\subsection{Varying $\omega$}
	% With h = 0.02, explore the effect of varying w. For 10 values of w between 1.0 and 2.0,	tabulate the number of iterations taken to achieve convergence, and the corresponding value	of potential at the point (x ,y) = (0.06, 0.04). Plot a graph of number of iterations versus w.

	The number of iterations to achieve convergence for 10 values of $\omega$ between 1 and 2 are tabulated in \autoref{table:q3b_iterations} and plotted in \autoref{fig:q3b}. Based on these results, the value of $\omega$ yielding the minimum number of iterations is 1.3.

	\begin{table}[!htb]
		\centering
		\caption{Number of iterations of SOR versus $\omega$.}
		\csvautobooktabular{csv/q3b_iterations.csv}
		\label{table:q3b_iterations}
	\end{table}

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=\columnwidth]{plots/q3b.pdf}
		\caption
		{Number of iterations of SOR versus $\omega$.}
		\label{fig:q3b}
	\end{figure}

	The potential values found at (0.06, 0.04) versus $\omega$ are tabulated in \autoref{table:q3b_potential}. It can be seen that all the potential values are identical to 3 decimal places, which shows that the program is converging correctly.

	\begin{table}[!htb]
		\centering
		\caption{Potential at (0.06, 0.04) versus $\omega$ when using SOR.}
		\csvautobooktabular{csv/q3b_potential.csv}
		\label{table:q3b_potential}
	\end{table}

	\subsection{Varying $h$}
	% With an appropriate value of w, chosen from the above experiment, explore the effect of	decreasing h on the potential. Use values of h = 0.02, 0.01, 0.005, etc, and both tabulate and	plot the corresponding values of potential at (x, y) = (0.06, 0.04) versus 1/h. What do you think is the potential at (0.06, 0.04), to three significant figures? Also, tabulate and plot the number of iterations versus 1/h. Comment on the properties of both plots.

	With $\omega = 1.3$, the number of iterations of SOR versus $1/h$ is tabulated in \autoref{table:q3c_iterations} and plotted in \autoref{fig:q3c_iterations}. Note that $h$ is in meters in all shown plots and tables. It can be seen that the smaller the node spacing is, the more iterations the program will take to run. Theoretically, the time complexity of the program should be $O(N^3)$, where the finite difference mesh is NxN. However, the experimental data shows a complexity closer to $O(1/h^2) = O(N^2)$. The discrepancy can perhaps be because of the relatively small amount of data points.

	\begin{table}[!htb]
		\centering
		\caption{Number of iterations of SOR versus $1/h$. Note that $\omega=1.3$.}
		\csvautobooktabular{csv/q3c_iterations.csv}
		\label{table:q3c_iterations}
	\end{table}

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=\columnwidth]{plots/q3c_iterations.pdf}
		\caption
		{Number of iterations of SOR versus $1/h$. Note that $\omega=1.3$.}
		\label{fig:q3c_iterations}
	\end{figure}

	The potential values found at (0.06, 0.04) versus $1/h$ are tabulated in \autoref{table:q3c_potential} and plotted in \autoref{fig:q3c_potential}. By examining these values, the potential at (0.06, 0.04) to three significant figures is converging to approximately \SI{5.24}{\volt}. It can be seen that the smaller the node spacing is, the more accurate the calculated potential is. However, by inspecting \autoref{fig:q3c_potential} it is apparent that the potential converges relatively quickly to around \SI{5.24}{\volt}. There are therefore diminishing returns to decreasing the node spacing too much, since this will also greatly increase the runtime of the program. This of course depends on the level of precision needed in the program.

	\begin{table}[!htb]
		\centering
		\caption{Potential at (0.06, 0.04) versus $1/h$ when using SOR.}
		\csvautobooktabular{csv/q3c_potential.csv}
		\label{table:q3c_potential}
	\end{table}

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=\columnwidth]{plots/q3c_potential.pdf}
		\caption
		{Potential at (0.06, 0.04) found by SOR versus $1/h$. Note that $\omega=1.3$.}
		\label{fig:q3c_potential}
	\end{figure}

	\subsection{Jacobi Method}
	% Use the Jacobi method to solve this problem for the same values of h used in part (c). Tabulate and plot the values of the potential at (x, y) = (0.06, 0.04) versus 1/h and the number of iterations versus 1/h. Comment on the properties of both plots and compare to those of SOR.

	The number of iterations of the Jacobi method versus $1/h$ is tabulated in \autoref{table:q3d_iterations} and plotted in \autoref{fig:q3d_iterations}. Similarly to SOR, the smaller the node spacing is, the more iterations the program will take to run. We can see however that the Jacobi method takes a much larger number of iterations to converge. Theoretically, the Jacobi method should have a time complexity of $O(N^4)$. However, the experimental data shows a complexity closer to $O(1/h^3) = O(N^3)$. The discrepancy can perhaps be because of the relatively small amount of data points.

	\begin{table}[!htb]
		\centering
		\caption{Number of iterations versus $\omega$ when using the Jacobi method.}
		\csvautobooktabular{csv/q3d_iterations.csv}
		\label{table:q3d_iterations}
	\end{table}

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=\columnwidth]{plots/q3d_iterations.pdf}
		\caption
		{Number of iterations of the Jacobi method versus $1/h$.}
		\label{fig:q3d_iterations}
	\end{figure}

	The potential values found at (0.06, 0.04) versus $1/h$ with the Jacobi method are tabulated in \autoref{table:q3d_potential} and plotted in \autoref{fig:q3d_potential}. These potential values are almost identical to the SOR ones, which suggests that it is converging correctly. Similarly to SOR, the smaller the node spacing is, the more accurate the calculated potential is.

	\begin{table}[!htb]
		\centering
		\caption{Potential at (0.06, 0.04) versus $1/h$ when using the Jacobi method.}
		\csvautobooktabular{csv/q3d_potential.csv}
		\label{table:q3d_potential}
	\end{table}

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=\columnwidth]{plots/q3d_potential.pdf}
		\caption
		{Potential at (0.06, 0.04) versus $1/h$ when using the Jacobi method.}
		\label{fig:q3d_potential}
	\end{figure}

	A comparison of the number of iterations of SOR and Jacobi can be seen in \autoref{fig:q3d_iterations_comparison}, which shows the clear benefits of SOR.

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=\columnwidth]{plots/q3d_iterations_comparison.pdf}
		\caption
		{Comparison of number of iterations when using SOR and Jacobi methods versus $1/h$. Note that $\omega=1.3$ for the SOR program.}
		\label{fig:q3d_iterations_comparison}
	\end{figure}

	\subsection{Non-uniform Node Spacing}
	% Modify the program you wrote in part (a) to use the five-point difference formula derived in	class for non-uniform node spacing. An alternative to using equal node spacing, h, is to use	smaller node spacing in more “difficult” parts of the problem domain. Experiment with a	scheme of this kind and see how accurately you can compute the value of the potential at (x, y)	= (0.06, 0.04) using only as many nodes as for the uniform case h = 0.01 in part (c).

	First, we adjust the equation derived in class to set $a_1 = \Delta_x\alpha_1$, $a_2 = \Delta_x\alpha_2$, $b_1 = \Delta_y\beta_1$ and $b_2 = \Delta_y\beta_2$. These values \footnote{Note that, in the program, index $i$ is associated to position $y$ and index $j$ is associated to position $x$. This is purely for easier handling of the matrices.} correspond to the distances between adjacent nodes, and can be easily calculated by the program. Then, the five-point difference formula for non-uniform spacing can be seen in \autoref{eq:non_uniform}.

	\begin{align} \label{eq:non_uniform}
		\begin{split}
			\phi^{k + 1}_{i,j} =
			&\frac{1}{a_1 + a_2}\left(\frac{\phi^k_{i - 1,j}}{a_1} + \frac{\phi^k_{i + 1,j}}{a_2}\right) + \\
			&\frac{1}{b_1 + b_2}\left(\frac{\phi^k_{i, j - 1}}{b_1} + \frac{\phi^k_{i, j + 1}}{b_2}\right)
		\end{split}
	\end{align}

	This was implemented in the finite difference program, as seen in \mintinline{python}{NonUniformRelaxer} class in the \mintinline{python}{finite_diff.py} file shown in \autoref{lst:finite_diff}. As can be seen in this code, many different mesh arrangements were tested. It was also tested that, if the non-uniform program is given a uniformly spaced grid, it finds the same potential as Jacobi. The chosen grid arrangement can be seen in \autoref{fig:q3e}. This grid was selected because the ``difficult'' regions are close to the inner conductor, where there is a higher concentration of nodes. The potential at (0.06, 0.04) obtained from this arrangement is \SI{5.243}{\volt}, which seems like an accurate potential value. Indeed, as can be seen in \Cref{fig:q3c_potential,fig:q3d_potential}, the potential value for small node spacings tends towards \SI{5.24}{\volt} for both the Jacobi and SOR methods.

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=\columnwidth]{plots/q3e.pdf}
		\caption
		{Final mesh arrangement used for non-uniform node spacing. Each point corresponds to a mesh point. The $x$ and $y$ coordinate are in meters. Points are positioned closer to the inner conductor, since this is a more difficult area. Note that this arrangement only represents one fourth of the entire grid, which is symmetric in $x$ and $y$.}
		\label{fig:q3e}
	\end{figure}

	\onecolumn

%	\appendix

	\begin{appendices}

		\section{Code Listings} \label{appendix:code}

		\setminted{linenos,breaklines,fontsize=\footnotesize}

		\begin{center}
			\captionof{listing}{Custom matrix package (\texttt{matrices.py}).}
			\inputminted{python}{../matrices.py}
			\label{lst:matrices}
		\end{center}

		\begin{center}
			\captionof{listing}{CSV manipulation utilities (\texttt{csv\_saver.py}).}
			\inputminted{python}{../csv_saver.py}
			\label{lst:csv_saver}
		\end{center}

		\begin{center}
			\captionof{listing}{Choleski decomposition (\texttt{choleski.py}).}
			\inputminted{python}{../choleski.py}
			\label{lst:choleski}
		\end{center}

		\begin{center}
			\captionof{listing}{Linear resistive networks (\texttt{linear\_networks.py}).}
			\inputminted{python}{../linear_networks.py}
			\label{lst:linear_networks}
		\end{center}

		\begin{center}
			\captionof{listing}{Question 1 (\texttt{q1.py}).}
			\inputminted{python}{../q1.py}
			\label{lst:q1}
		\end{center}

		\begin{center}
			\captionof{listing}{Question 2 (\texttt{q2.py}).}
			\inputminted{python}{../q2.py}
			\label{lst:q2}
		\end{center}

		\begin{center}
			\captionof{listing}{Finite difference method (\texttt{finite\_diff.py}).}
			\inputminted{python}{../finite_diff.py}
			\label{lst:finite_diff}
		\end{center}

		\begin{center}
			\captionof{listing}{Question 3 (\texttt{q3.py}).}
			\inputminted{python}{../q3.py}
			\label{lst:q3}
		\end{center}

		\section{Output Logs} \label{appendix:logs}

		\begin{center}
			\captionof{listing}{Output of Question 1 program (\texttt{q1.txt}).}
			\inputminted{pycon}{logs/q1.txt}
			\label{lst:q1_log}
		\end{center}

		\begin{center}
			\captionof{listing}{Output of Question 2 program (\texttt{q2.txt}).}
			\inputminted{pycon}{logs/q2.txt}
			\label{lst:q2_log}
		\end{center}

		\begin{center}
			\captionof{listing}{Output of Question 3 program (\texttt{q3.txt}).}
			\inputminted{pycon}{logs/q3.txt}
			\label{lst:q3_log}
		\end{center}
	\end{appendices}

\end{document}


\documentclass[12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{float}
\usepackage{amsmath}
\usepackage{tikz} % for Hasse diagram
\usepackage[hmargin=3cm,vmargin=6.0cm]{geometry}
%\topmargin=0cm
\topmargin=-2cm
\addtolength{\textheight}{6.5cm}
\addtolength{\textwidth}{2.0cm}
%\setlength{\leftmargin}{-5cm}
\setlength{\oddsidemargin}{0.0cm}
\setlength{\evensidemargin}{0.0cm}

\begin{document}

\section*{Student Information }
%Write your full name and id number between the colon and newline
%Put one empty space character after colon and before newline
Full Name : Yavuz Selim YEŞİLYURT \\
Id Number : 2259166 \\

% Write your answers below the section tags
\section*{Answer 1}
\qquad Let $f_n$ be the number of ternary strings that contain 3 consecutive 0s, 1s or 2s. $f_1=0$ and $f_2 =0$ because they do not have 3 digits. Let $g_n$ stand for the number of ternary strings that doesn't contain 3 consecutive 0s, 1s or 2s.\\

So for finding $f_n$, we should find $g_n$ and then subtract it from the total number of ternary strings with length n (i.e. $3^n$).\\

Find $g_n$ by constructing a ternary string of length n.\\

First choose first digit. Any of 0,1,2 can be chosen as first digit of the string. Let's choose 0 as first digit, however other digits can be chosen, too. The probability of the string to start with 0 is $1/3$. Since we have 3 of these beginning digits we should multiply our probability by $(1/3) * 3 = 1$. Possibilities for second digit are 0,1,2 too. But we have to analyze 2 cases in this case. We should check for "1" and "2" as second digit of the string(say case 1) and chech for "0" as second digit of the string (say case 2). \\

In case 1, string starts with 01.. or 02.. which are not consecutive numbers (not 00). We can reset the count of first digit in this case (first digit is 0 in this case) at the beginning and go on with any string that does not contain 3 consecutive symbols and starts with 1 or 2. That is $2g_{n-1}$.\\

In case 2, string starts with 00.. which means the first two digits are consecutive. Since we started with 00 our next digit can not be 0 because then our string will contain three consecutive zeros (000). Therefore the rest of the string must start with 1 or 2 and does not contain 3 consecutive digits, which is $2g_{n-2}$.\\

Add this to the other case, multiply by our possibility to choose first digit (which we found at the first part of answer and which is 1) and get $g_n$:\\
$g_n = 1*(2g_{n-1} + 2g_{n-2})$ for $n \geq 3$\\
where $g(1) = 3,\ g(2) = 9$.\\

Turn back to $f_n$ and subtract $g_n$ from $3^n$ to find $f_n$.\\
$f_n = 3^n - g_n$ where $g_n = 2(g_{n-1} + g_{n-2})$ for $n\geq 3$ \\
And initial conditions are:\\
$f(1) = 0 , f(2) = 0$ and $g(1) = 3,g(2) = 9$

\section*{Answer 2}
\textbf{a)}A tile can be placed horizontally, i.e. as a $1 \times 2$ tile or vertically, i.e. as a $2 \times 1$ tile. We need 3 small tiles to tile the board of size $3 \times 2$. There are three ways to tile:\\
\begin{tabular}{|cccc|}
\hline
 &  &  & \tabularnewline
 &  &  & \tabularnewline
\hline
\hline
 &  &  & \tabularnewline
 &  &  & \tabularnewline
\hline
\hline
 &  &  & \tabularnewline
 &  &  & \tabularnewline
\hline
\end{tabular}
\begin{tabular}{|cc|cc|}
  \hline
  & & & \tabularnewline
  & & & \tabularnewline
  & & & \tabularnewline
  & & & \tabularnewline
  \hline \hline
  & \multicolumn{1}{c}{} &  & \tabularnewline
  & \multicolumn{1}{c}{} &  & \tabularnewline
  \hline
\end{tabular}
\begin{tabular}{|cc|cc|}
\hline
 & \multicolumn{1}{c}{} &  & \tabularnewline
 & \multicolumn{1}{c}{} &  & \tabularnewline
\hline
\hline
 &  &  & \tabularnewline
 &  &  & \tabularnewline
 &  &  & \tabularnewline
 &  &  & \tabularnewline
\hline
\end{tabular}\\\\\\
\textbf{b)}
We have three $3\times 2$ boards to cover $3\times n$ board, namely (from part a);\\
- $3\times 2$ board tiled with 3 horizontal $2\times 1$ tiles (say type 1 tiling)\\
- $3\times 2$ board tiled with 1 horizontal tile at the upside of the board and 2 vertical tile at the downside of the board $2\times 1$ tiles (say type 2 tiling)\\
- $3\times 2$ board tiled with 2 vertical tile at the upside of the board and 1 horizontal tile at the downside of the board $2\times 1$ tiles (say type 3 tiling)\\

Let $f_n$ be the count of ways to place tiles on a $3\times n$ board. Since we cover 2 columns in one tiling operation, for odd numbers of $n$, since we can not tile these boards with odd number of columns problem gives $0$ and for even numbers of $n$ problem reduces to $f_{n-2}$.\\

For the even numbers of $n$ now consider placing the first $3\times 2$ tile to $3\times n$ board.If the first tiling is of type 1,then we can tile the following part with all types, no restrictions, so problem reduces to $f_{n-2}$, say this is case 1.\\

But, since we have the condition of dropping the same 2 tilings (tilings which can be obtained from one another when mirrored along the side of length-$n$), we should check for the cases when any of the two tilings are the same;\\

Let's say we place a tile of type 2 for the first tiling and then we tile the remaining part of $3\times n$ board with some tilings of any type (i.e. the remaining tiling problem reduces to $f_{n-2}$ and say this is case 2). If we were to place a tile of type 3 for the first and then we continue to tile the remaining part same as in the first case (i.e. the remaining tiling problem reduces to $f_{n-2}$ and say this is case 3) these two tilings (case 2 and case 3) would be same since each tiling can be obtained from one another when mirrored along the side of length-$n$ (figure 1), so we have to delete one of these occurences, therefore, in case-3 problem actually reduces to $f_{n-2}-1$\\

So we have (for even numbers of $n$) $f_n = f_{n-2} + f_{n-2} + f_{n-2}-1$,\\
Therefore we get for $n\geq 3$, $f_n = 3f_{n-2}-1$ for even numbers of $n$ and $0$ for odd numbers of $n$ . As initial conditions we have $f(0)=0$, $f(1)=0$, $f(2)=2$ .

\newpage

\textbf{c)}	We have $f_{n}=3f_{n-2}-1$ for even numbers of $n$ and for $n\geq 3$. Initial conditions were $f(0)=0$, $f(1)=0$, $f(2)=2$ and let's say$<f_{0},f_{1},f_{2}...,f_{n},....><->F(x)$\\

$F(x)=\sum_{n=3}^{\infty}f_{n}x^{n} + 2x^{2}=2x^{2}+\sum_{n=3}^{\infty}(3f_{n-2}-1)x^{n}$\\

$F(x)=2x^{2}+\sum_{n=3}^{\infty}3f_{n-2}x^{n}-\sum_{n=3}^{\infty}1x^{n}$\\

$F(x)=2x^{2}+3x^{2}F(x)-x^{3}(1+x^{2}+x^{4}...)$\\

$F(x)=2x^{2}+3x^{2}F(x)-x^{3}(\frac{1}{1-x})$\\

$F(x)=\frac{2x^{2}-3x^{3}}{3x^3-3x^2-x+1}$ Do partial fractions:\\

$F(x)=\frac{1}{2(1-x)}+\frac{x-1}{2(3x^2-1)}-1$ \\

where; $\frac{1}{2}\frac{1}{1-x}=\frac{1}{2}(1+x+x^{2}+...)<-><\frac{1}{2},\frac{1}{2},\frac{1}{2},\frac{1}{2},\frac{1}{2}...,\frac{1}{2},...>$ and\\

$\frac{1}{2}\frac{1}{1-3x^{2}}=\frac{1}{2}(1+3x^{2}+3^{2}x^{4}+...)<-><\frac{1}{2},0,\frac{1}{2}3,0,\frac{1}{2}3^{2},0...,\frac{(-1)^{n}+1}{2}\frac{3^{\frac{n}{2}}}{2},...>$
and\\

$\frac{1}{2}\frac{x}{1-3x^{2}}=\frac{1}{2}(1+3x^{3}+3^{2}x^{5}+...)<-><0,\frac{1}{2},0,\frac{1}{2}3,0,\frac{1}{2}3^{2},0...,\frac{(-1)^{n-1}+1}{2}\frac{3^{\frac{n-1}{2}}}{2},...>$
and\\

$1=<1,0,0,0,0,0....>$\\

Therefore (odd coefficients are zero, so they are denoted with $f's$).\\  $F(x)<-><0,0,2,f_3,5,f_5,......,\frac{1}{2}+ \frac{(-1)^{n}+1}{2}\frac{3^{\frac{n}{2}}}{2}-\frac{(-1)^{n-1}+1}{2}\frac{3^{\frac{n-1}{2}}}{2},....>$,
which implies;\\

$f_{n}=\frac{1}{2}+\frac{(-1)^{n}+1}{2}\frac{3^{\frac{n}{2}}}{2}-\frac{(-1)^{n-1}+1}{2}\frac{3^{\frac{n-1}{2}}}{2}$ for even numbers of n with $n \geq 3$. With initial conditions $f(0)=0$, $f(1)=0$, $f(2)=2$.
\newpage
\section*{Answer 3}
Since a binary relation R on a set S is a partial order iff it is reflexive, antisymmetric and transitive, we should check if the binary relation is reflexive, antisymmetric and transitive on each part seperately. Keep the relations' features in mind;
\\
- A relation is reflexive if $\forall a \in S \ \ aRa$\\
- A relation is antisymmetric if $\forall{a,b} \in S ((aRb \land bRa) \implies a=b)$\\
- A relation is transitive if $\forall{a,b,c} \in S ((aRb \land bRc) \implies aRc)$
\\\\
Using these information;
\\
\textbf{a)}
\\\\
Set inclusion ($ \subseteq $) on any set of sets is;\\
-Reflexive, because every set is a subset of itself on any set of sets,\\
-Antisymmetric, since if a subset of the set is the set's superset; the set's subset(also the superset) is the same set as the set on any set of sets,\\
-Transitive, since if any subset of the set's subset is also that set's subset on any set of sets.
\\\\
So set inclusion ($\subseteq$) on any set of sets is partial order.
\\\\
\textbf{b)}
\\\\
Even relation $"|"$ of divisibility on integers $Z$ is both reflexive and transitive it is not partial order because;\\
It is not antisymetric, since $-2|2$ is true and $2|-2$ is true but $2 \neq -2$. So relation $"|"$ of divisbility on integers $Z$ is not a partial order.
\\\\
\textbf{c)}
\\\\
Relation R is defined as "$aRb$ if there is a positive integer $r$ such that $b=a^r$" on $Z$. It is;\\
-Reflexive since for $r=1$, $a=a^1$,\\
-This relation is antisymmetric. Assume that $a$ and $b$ are arbitrarily chosen, such that $aRb$ and $bRa$. Hence $a=b^r$ and $b=a^{r_2}$.\\
$a=a^{r*r_2} \implies r*r_2 =1$. Since $r \ \ and \ \ r_2$ are positive integers $r=1$ and $r_2 = 1$ so $a=b^1$ and $a^1=b$ so this relation is antisymmetric.\\
-Transitive since if $b=a^r$ and $c=b^{\bar{r}}$, $c=a^{r^{'}}$ is true for every $r^{'}=r*\bar{r}$.\\
\\
So this relation on $Z$ is partial ordered.

\newpage

\section*{Answer 4}

\textbf{a)}\\\\

1-) $1+1+1+1+1$\\

2-) $2+1+1+1$\\

3-) $2+2+1 $\\

4-) $3+1+1$\\

5-) $3+2$\\

6-) $4+1$\\

7-) $5$\\

As can be seen there are 7 partitions of 5.\\\\

\textbf{b)}

%Hasse diagram example
\begin{figure}[H]
\centering
\begin{tikzpicture}
%%   kw   (name)   (x, y)   {text}
    \node (md1) at (2, 4)     {5};
    \node (md2) at (0, 2)     {3+2};
    \node (rt2) at (4, 2)     {4+1};
    \node (lt3) at (0, 0)     {3+1+1};
    \node (rt3) at (4, 0)     {2+2+1};
	\node (md4) at (2, -2)     {2+1+1+1};
	\node (md5) at (2,-4)     {1+1+1+1+1};

    \draw (md1) -- (md2);
    \draw (md2) -- (lt3);
    \draw (md2) -- (rt3);
    \draw (rt2) -- (rt3);
    \draw (lt3) -- (md4);
    \draw (rt3) -- (md4);
    \draw (md5) -- (md4);
    \draw (lt3) -- (rt2);
    \draw (rt2) -- (md1);
\end{tikzpicture}
\end{figure}

\end{document}