\chapter{Adventuring}\label{ch:Adventuring}
\section{Time, Speed and Travel}\label{sec:timeSpeedTravel}
\subsection{Time Units}\label{subsec:timeUnits}
The relations between seconds, minutes, hours and days are equivalent to earth units, even though they are somewhat longer units overall, since Kusa, the planet of the Ragged lands, is larger than earth.\\

A week on Kusa has 10 days, which are usually numbered (first weekday, second weekday, etc.), and the last 3 days are considered to be weekend days - even though that doesn't have much effect on common folk, who have to work in the fields and care for their animals anyway.\\

Each Kusaen Month consists of three weeks, i.e.\ 30 days.\\

A year begins mid-winter and consists of 13 months and one additional week.

During this week, also called "black week" or "dark week", the unique constellation of the planet's two moons cause a week-long eclipse, which shrouds the planet in complete darkness.
In this time, areas outside of towns are filled with monsters that disappear once the sun rises again.
This is also the point at which the new year starts.\\

\subsection{Short-Distance Travel}\label{subsec:shortDistanceTravel}
During Combat or in situations where split-second decisions are important, a character is assumed to be able to tactically move \passus{2} per AP, or run \passus{4} per AP and Stamina spent.
If a character is trying to move stealthy, they are considered to be half as fast during combat or during a time-based encounter.\\

\subsection{Mid-Distance Travel}\label{subsec:midDistanceTravel}
While travelling in areas with a dense layout, like a town, city or a cavern, a character is considered to be able to move \passus{50} per minute.

\subsection{Long-Distance Travel}\label{subsec:longDistanceTravel}
While travelling overland, a character is considered to be able to move \leg{4} per hour, which means that a well-travelled character should be able to move \leg{16} per 4-hour interval;
Adventurers are usually considered to be well-travelled.\\

One travelling day is sectioned into six separate 4-hour intervals, three of which are usually spent travelling.

Travelling more than 16 hours reduces a character's maximum Stamina by 1 for each additional hour they spend travelling until they take a rest, at which point one maximum Stamina is restored for each hour rested.\\

For each 4-hour interval, each character in the group can choose a side activity.

These consist of:

\begin{itemize}
	\item Follow Tracks

	\item Ensuring that the group moves stealthy (reduces the group's speed by half)

	\item Lookout for ambushes

	\item Scavenge the area for items

\end{itemize}
This list is not exhaustive.\\

Depending on the area of travel and the group's makeup, there could be more options.
For example, if the group is moving by horse-drawn wagon, one member of the group has to lead the wagon, while others could use the wagon to rest, learn a perk or even craft items.

\subsection{Stealth}\label{subsec:stealth}
If a creature tries to move stealthy in a dungeon, they are considered to be able to move at one-fourth speed, meaning they spend 4 times as many AP for movement, and can only move up to one-fourth their agility in addition to a static action in combat.
If they try not to be noticed while moving through a city, their speed should be treated as half their normal speed.\\
When moving stealthily, a creature makes a stealth check.
If that stealth check is below someone's~\nameref{stat:notice}, they realize something is off - they see moving shadows, hear footsteps, the hiding creature knocks something over etc.
The hiding creature might react to someone becoming aware of them, and the now aware creature might start looking around by making perception checks.

\subsection{Swimming}\label{subsec:swimming}
In still waters, a creature that can swim is usually considered to be able to swim normally.
Swimming for more than 1 hour without break will star to drain a creature's stamina at a rate of 1 per hour.\\
In rougher waters, a creature swimming has to make Agility checks to make sure they can overcome the currents.\\

\subsubsection{Suffocation}\label{subsubsec:suffocation}
A creature starts suffocating the moment they lose their ability to breathe.
A suffocating creature is effectively mute, and loses 1 Stamina per AP of suffocation.
After a suffocating creature has reached 0 Stamina, they start to take 1d6 damage every 5 AP.

\section{Carrying Capacity}\label{sec:carryingCapacity}
Items in the RLP are measured relative in the sizes "coin sized" (CS), "tiny" (T), "small" (S), medium (M), large(L), extra large (XL) or extra extra large (XXL).\\
One tiny object is equal to 10 coin sized items.
One small item is equal to 10 tiny items, and so forth.\\
These units are a combination of weight and volume, and containers usually can hold a certain amount of objects.
However, some objects are more or less dense.
For example, while a Backpack might be able to carry the equivalent of one large item in both weight and volume, it might not be able to hold 10 gold bars -- the straps of the backpack would possibly break.\\
Therefore, GMs and Players should treat these units as larger or smaller depending on the situation if they're dealing with denser or lighter materials.\\
A creature can usually carry one large item per point of ST, but might need a fitting container, like a backpack, to do so.\\

A person is usually able to carry their ST stat in large items.\\

\section{Hazards}\label{sec:hazards}
\subsection{Temperature}\label{subsec:temperature}
In regular environment, characters don't have to fear issues from temperature.
However, very high and very low temperatures can affect a character's health, stamina and can even damage them.\\

In warm and chilly environments, a character's stamina recovery is slowed down to 1 point every 2 AP of resting.
This can be countered by wearing armor with the warming or cooling abilities, respectively.\\

In hot and cold environments, a character takes 1 hot or cold damage per minute.
This damage is applied every 2 minutes, and requires a minimum damage reduction of 2 to be countered.\\

In extremely hot or extremely cold environments, a character takes 1 hot or cold damage per AP.
This damage is applied every 5 AP, and requires a minimum damage reduction of 2 to be countered.\\

\subsection{Falling}\label{subsec:falling}
Falling for \passus{2} deals 1d8 blunt damage on impact.
This damage increases by 1d8 for every additional \passus{2} travelled, to a maximum of \passus{50}, at which terminal speed is reached.
A character who can react and move can reduce this falling damage by making an Agility check.
The original DV for this check is 20, and it reduces the falling damage by 1d8.
For every 5 points above 20 that the Agility check reaches, it reduces the falling damage by an additional 1d8.
For example, a character falling \passus{16} would take 8d8 blunt damage on impact.
If said character makes an Agility check with a result of 27, they would only take 6d8 blunt damage instead.

\subsection{Traps}\label{subsec:traps}
Traps are - usually deliberately placed - hazards that consist of a trigger and a -- usually harmful -- effect.\\
When setting a trap, the creator usually rolls a~\nameref{sec:trapHandling} check to set the trap, and a~\nameref{sec:stealth} Check to hide it.\\
When a Character is in the area of a trap, compare the Trap's Finding DV to their Notice.

If the character is actively searching for traps, they gain +5 on their Notice for this comparison.

If the Notice is higher than the DV, the character notices that something is off.

They usually see some sign of the trigger.\\
If the character then decides to actively search for this specific trap, they roll a~\ref{sec:examination} check contested by the Trap's Find DV.
If they find the trap, they can then attempt to disable it by making a~\nameref{sec:trapHandling} check contested by the Trap's Trap Handling DV.\\
If the disarm attempt succeeds, the trap is disarmed.

If it fails, the character currently misses the knowledge or expertise to disarm this trap.\\
If the disarm attempt fails by 5 or more, the trap is sprung, and the effect is triggered immediately, regardless of if any characters are in the effect's area.\\
Additionally, if a character skilled in Trap Handling beats the DV of a Trap by 5 or more, they might be able to gather some or even all the materials used in the creation of the trap.\\
If a character triggers a trap, they usually realize that they have triggered something - they feel a tripwire that is being taught and a click coming from the wall, or they realize that the tile they stepped on is giving away, or something similar.

They then have the chance to react, gaining an appropriate check against the traps' effect if they react correctly.\\

\section{Units}\label{sec:units}
These units are Laetharnian standard Imperial units and are known around the world, thanks to the aggressive expansion tactics that the Empire employs.\\
These units are used throughout the document with their conversions provided.\\

\textbf{Fin} - Unit of length, about 0.6 inches or 1.5 centimeters\\
Usually used to measure things below 2 passus, like human size or the length of a weapon.\\

\textbf{Passus} - Unit of length, about 5 feet or 1.5 meters long\\
Used to measure short walking distances, measuring the distances in combat as an example.\\

\textbf{Leg} - Unit of length, about 800 passus, 1200 meters, 3940 feet\\
Used to measure great distances, like between cities.
Four Leg can usually be walked in an hour.\\

\textbf{Legal} - Unit of area, one Leg * one Leg\\
Used to measure property.
Half or quart a Legal are typical units for owned land.\\

\textbf{Stone} - Unit of mass, about 6 kg, 6 litres of water, or 13 pounds, 200 liquid ounces\\
Used for weighing of cattle or people.\\

\textbf{Pugnus} - Unit of mass, 20 Pugnus make a Stone, 10 Pugnus a Half Stone, so about 300 g, 300 ml or 0.66 pounds, 10 liquid ounces\\
Used for smaller measurements, like drinks or food.

A person usually needs 5 Pugnus of water per day.

"A Beer" from a tavern is usually a Pugnus, sometimes a double-Pugnus is referred to as a  "Large One", with an "Extra" being 4 Pugnus.\\


\section{Publication}
\label{variantcalling-sec:publication}

The full publication about joint somatic variant calling can be found at \href{https://doi.org/10.1093/bioinformatics/btab606}{\nolinkurl{https://doi.org/10.1093/bioinformatics/btab606}} and non-journal formatted version is also attached as \autoref{ch:appendixManuscript} with all supplementary methods.

References to supplementary data will be prefixed with the letter \ref{ch:appendixManuscript} in the text.

\subsection{Summary}
To enable highly sensitive, fast and accurate variant detection from multiple related tumour samples, we have developed joint variant calling extensions to two widely used single-sample algorithms, FreeBayes \parencite{Garrison2012} and Strelka2 \parencite{Kim2018}. Using both simulated and clinical sequencing data, we show that these workflows are highly accurate and can detect variants at much lower variant allele frequencies than other commonly used methods.

\subsection{FreeBayesSomatic workflow}
The original FreeBayes algorithm can jointly evaluate multiple samples, but routinely it does not perform somatic variant calling on tumour-normal pairs. We introduce FreeBayesSomatic which allows concurrent analysis of multiple tumour samples by adapting concepts from SpeedSeq \parencite{Chiang2015} which differentiates the likelihood of a variant between tumour and normal samples instead of imposing an absolute filter for all variants called in the normal. Hence, for each genotype (GT) at SNV sites, FreeBayesSomatic first calculates the difference in likelihoods (LOD) between the normal (\autoref{eq:01}) and the tumour (\autoref{eq:02}) samples genotype likelihoods (GL) with g$_{0}$ describing the reference genotype.

\begin{align}
\text{LOD}_{\text{normal}} &= \max_{g_i \in \text{GT}} \left( \text{GL}(g_0) - \text{GL}(g_i) \right) \label{eq:01}\\
\text{LOD}_{\text{tumour}} &= \min_{s \in \text{Samples}} \left( \min_{g_i \in \text{GT}} \left( \text{GL}_s(g_i) - \text{GL}_s(g_0) \right) \right) \label{eq:02}\\
\text{somaticLOD} & := \left( \text{LOD}_{\text{normal}} \geq 3.5 \land \text{LOD}_{\text{tumour}} \geq 3.5 \right) \label{eq:03}
\end{align}
%we have to specify them individualluy here, because align doesnt really allow it
\myequation[\ref{eq:01}]{FreeBayesSomatic: LOD$_{normal}$}
\myequation[\ref{eq:02}]{FreeBayesSomatic: LOD$_{tumour}$}
\myequation[\ref{eq:03}]{FreeBayesSomatic: somaticLOD definition}

Next, the variant allele frequencies (VAF) in both the tumour and the normal samples are compared at each site.

\begin{align}
\text{VAF}_{\text{tumour}} &= \max_{s \in \text{Samples}} ( \text{VAF}_s) \label{eq:04}\\
\text{somaticVAF} & := \left( \text{VAF}_{\text{normal}} \leq 0.001 ~\lor \right. \nonumber \\
 & \left. ( \text{VAF}_{\text{tumour}} \geq 2.7 \cdot \text{VAF}_{\text{normal}}) \right) \label{eq:05}
\end{align}
\myequation[\ref{eq:04}]{FreeBayesSomatic: VAF$_{tumour}$}
\myequation[\ref{eq:05}]{FreeBayesSomatic: somaticVAF definition}

A variant is classified as somatic when both somaticLOD as well as somatic VAF pass the criteria somaticLOD (\autoref{eq:03}) and somaticVAF (\autoref{eq:05}).

The thresholds chosen for both LOD and VAF calculations were previously fitted by the blue-collar bioinformatics workflow for the ``DREAM synthetic 3`` dataset using the SpeedSeq likelihood difference approach \parencite{Chapman2020} and were selected to identify high confidence variants.

\subsection{Strelka2Pass workflow}
In contrast to FreeBayes, whilst Strelka2 has a multiple-sample mode for germline analysis and tumour-normal pair somatic variant calling capabilities, it cannot jointly analyse multiple related tumour samples. We enable this feature by adapting a two-pass strategy previously used for RNA-seq data \parencite{Veeneman2015}. First, somatic variants are called from each tumour-normal pair. All detected variants across the cohort are then used as input for the second pass of the analysis, where we re-iterate through each tumour-normal pair but assess allelic information for all input genomic sites.

The method re-evaluates the likelihood of each variant, by integrating every genotype from each tumour-normal pair. This step can "call" a variant ($v$) in a sample that initially did not present enough evidence to pass the Strelka2 internal filtering using two conditions: 1) if this variant was called as a proper "PASS" by Strelka2 in any other tumour sample, or 2) if the integrated evidence for this variant across all tumour-normal pairs reached a sufficiently high level. The second condition was based on the somatic evidence score (SomEVS) reported by Strelka2, which is the logarithm of the probability of the variant $v$ being an artefact.

\begin{equation}
p_{error}(v) = 10^{\left( \frac{-\text{SomEVS}(v)}{10} \right)} \label{eq:06}
\end{equation}
\myequation[\ref{eq:06}]{Strelka2Pass: pairwise error probability}

While the germline sample is shared between all processes, we can approximate these individual probabilities as being independent, since one variant calling process is agnostic of the other. Hence, we derive the following:

\begin{equation}
p_{error}(v_{s_1},v_{s_2},\ldots,v_{s_n}) = \prod_{s \in \text{Samples}} p_{error}(v_{s}) \label{eq:07}
\end{equation}
\myequation[\ref{eq:07}]{Strelka2Pass: joint error probability}

And therefore:

\begin{equation}
\text{SomEVS}(v_{s_1},v_{s_2},\ldots,v_{s_n}) = \sum_{s \in \text{Samples}} \text{SomEVS}(v_{s}) \label{eq:08}
\end{equation}
\myequation[\ref{eq:08}]{Strelka2Pass: joint SomEVS}

This allows the summation (\autoref{eq:08}) of the SomEVS score across all supporting variants to assign a "PASS" filter, if it reached a joint SomEVS score threshold. This threshold can be set by the user and is 20 by default, which corresponds to an estimated error rate of 1\%. These "recovered" variants need to pass a set of additional quality metrics related to depth of coverage, mapping quality and read position rank sum score.

As an additional improvement, we also built multiallelic support into Strelka2 which originally only reports the most prevalent variant at a specific site. Within the two-pass analysis, we reconstruct the available evidence for a multiallelic variant at a called site from the allele-specific read counts and report the minor allele at this site, if there is sufficient support from other samples. This method allows recovery of minor alleles only if another sample has this variant called by Strelka2, as SomEVS scores are not available for minor alleles.

\subsection{Validation}

As new methods are always a good idea, because they challenge previous assumptions and can be a step forward for the field by just showing that simpler models can have the same performance, all methods should be validated against the gold standard methods in the field with data which allows objective measures to be used. For germline variant calling, there have been multiple challenges and specifically designed test datasets, but these predefined datasets do not exist for the somatic equivalent. This issue is even more pronounced, as we do not only need a tumour-normal pair, but we need the multiple tumour samples in the dataset to be related. To allow a fair comparison, I first generated a fully synthetic dataset, where every variant is known and fully defined (\autoref{variantcalling-sec:simdata}) to allow a general performance assessment of the methods. Then to ensure that these metrics also hold true in real world data, we then re-analysed previously published datasets which have orthogonal validation in the form of targeted amplicon sequencing (TAS) (\autoref{variantcalling-sec:realdata}).

\begin{figure*}[!tpb]
\centering
  \includegraphics[width=\textwidth]{Appendices/Variantcalling/Figure_1}\vspace*{-12pt}
  \caption[Comparison of joint multi-sample and single tumour-normal paired variant calling methods]{Comparison of joint multi-sample variant calling and single tumour-normal paired calling methods; A) Simulated phylogeny highlighting two samples with high evolutionary distance (sim-a and sim-j) where MRCA denotes the most recent common ancestor. B) Recall estimates of FreeBayes and Strelka2, run in individual tumour-normal paired and joint calling configurations using two (sim-a and sim-j), three (sim-a, sim-g and sim-j), five (sim-a, sim-c, sim-f, sim-h and sim-j) and all ten tumour samples. C) Precision of Strelka2 and D) Number of variants called by Strelka2 run in both tumour-normal paired (grey) and added with joint calling configurations (blue), which have been validated by targeted amplicon sequencing (TAS). E) Correlation between cellularity and proportion of variants found only with joint calling using Strelka2Pass for clinical samples; grey area shows the "$95\%$" confidence interval for the linear model fit (dotted line).}\label{fig:varcalling:fig1}
\end{figure*}

\subsubsection{Simulated data}
\label{variantcalling-sec:simdata}
We first simulated a phylogeny with somatic and germline variants from ten tumour samples and one normal (\autoref{fig:varcalling:fig1}A and \autoref{A:fig:S01}A, B). Germline variants were simulated at a uniform allele frequency of $0.5$. Somatic VAFs were sampled from a custom distribution, modelled to favour low allele frequency variants to closely represent real world data (min VAF: $0.001$; max VAF: $1$; Fig.~S1C, D). Paired-end sequencing reads with realistic error profiles were simulated for WGS data at 160X average coverage using the ART-MountRainier software \parencite{Huang2011}. The simulated reads were aligned to GRCh38 and both germline and somatic variants from the phylogeny were spiked into the aligned reads using Bamsurgeon \parencite{Ewing2015}. We compared the workflows for FreeBayes and Strelka2 with and without our extensions for joint variant calling on the simulated datasets. The performance of Mutect2 joint variant calling was also assessed using its proposed best practice workflow. As both Mutect2 and FreeBayes do not return a verdict for each individual sample, we needed to assign each sample in the multi-sample VCF its own FILTER value. We called a somatic variant as present in a sample, if there were at least two reads supporting it for this sample and the overall FILTER showed a ``PASS``, which was the same cut-off used in the refiltering step in the Strelka2-pass workflow.

While the precision of each method without our extensions was greater than $99.8\%$, they all missed at least 25\% of all variants in the samples (i.e. recall $\leq 75\%$). In contrast, the recall of the modified workflows increased to $\approx 95\%$ with only a minute decrease in the precision for both FreeBayes and Strelka2 (\autoref{A:fig:S02}). Mutect2 had virtually no change in precision, but the recall actually decreased from $\approx 75\%$ to $\approx 41\%$ when analysing the samples jointly (\autoref{A:fig:S02}B). Additionally, with our modified workflows, true positive variants were called with VAFs as low as 0.008 (median detected VAF $\geq 0.14$ for joint sample analysis and $\geq 0.21$ for single tumour-normal pair analysis), enabling improved distinction between true variants and technical errors (\autoref{A:fig:S03}). This improvement in performance for Strelka2 is only achieved after the refiltering step and not just a result of the second pass (\autoref{A:fig:S04}, \autoref{A:varcalling:steps}).

The performance of joint variant calling in Mutect2 was inferior compared to all other methods (\autoref{A:fig:S02}A, B). This was primarily due to the "clustered\_events" filter in Mutect2, which excluded the majority of false negative variants, with negligible contribution to the exclusion of true negative variants (\autoref{A:fig:S05}A, B). This result was unexpected as the simulated variants were evenly distributed along the genome and the corresponding allele frequencies were sampled randomly (\autoref{A:fig:S01}D).

Since the extent of the improvement in our joint calling workflows is bound by the number of shared variants between samples, we sub-sampled the simulated dataset, to show the effect of incomplete sampling on our methods, which is more likely in clinical settings. Furthermore, the evolutionary distance between the related samples in addition to the number of samples, has a major impact on the number of shared variants, as only variants acquired between the germline and the most recent common ancestor (MRCA), will benefit from the joint analysis. Therefore, we selected three sample subsets which included two, three and five samples with high evolutionary distance to show the minimum expected improvement (\autoref{fig:varcalling:fig1}A, B). There was a clear linear improvement for both FreeBayesSomatic and Strelka2Pass when increasing the number of samples, even if they had a distant evolutionary relationship. In contrast, when using only two samples with a small evolutionary distance, the increase in performance was almost as large as when jointly analysing all 10 available samples. This shows that samples with a high number of shared variants will perform better in joint calling workflows (\autoref{A:fig:S06}).

\subsubsection{Clinical data}
\label{variantcalling-sec:realdata}
To validate the performance of our new workflows, we then analysed WGS and whole-exome sequencing (WES) data of multi-region tumour samples from eight patients, with multiple tumour sites (average 7 samples per patient; total number of samples 55), enrolled in a rapid autopsy program conducted at the Peter MacCallum Cancer Centre (\autoref{A:tab:S1} and \autoref{A:varcalling:clinical}) \parencite{Solomon2020, Vergara2021}. The published studies had multiple somatic variants from the clinical samples orthogonally validated through targeted amplicon sequencing (TAS). We used these TAS-validated variants as the gold standard to evaluate the performance of different workflows, acknowledging that the technical biases inherent to TAS data are different to those present in WGS and WES (\autoref{A:fig:S07}) and that there would be sampling biases depending on different tumour cells analysed in each data type.

In concordance with the results of the simulated data, our improved workflows found additional variants in all but one patient (\autoref{fig:varcalling:fig1}D, \autoref{A:fig:S08}) (total additional variants Strelka2Pass: $64$; FreeBayesSomatic: $85$) with only a slight drop in precision for FreeBayesSomatic (mean: $0.94$ vs. $0.88$) and Strelka2Pass (mean: $0.97$ vs. $0.92$). Since the panel of variants validated by TAS was limited ($7108$ bp for patients CA-B through -H), this increase in detected variants suggests that a high number of shared variants in samples are missed with current approaches, which in turn leads to an overestimation of tumour heterogeneity between samples, as these variants are thought to not be present rather than undetected.

Even though the number of shared variants is a major influencing factor when jointly calling variants, low cellularity samples benefit more from the joint calling, as conventional methods cannot reliably distinguish low allele frequency variants from noise. Through a joint analysis approach, the number of recovered variants is higher in low cellularity samples, which indicates, that especially for clinical samples with variable tumour purity, joint analysis can have a major impact on improving performance (\autoref{fig:varcalling:fig1}E, \autoref{A:fig:S09}).

Mutect2 in contrast, did not show significant improvement in any sample in its joint calling configuration, but showed inferior performance compared to the tumour-normal pairwise approach in two samples (\autoref{A:fig:S08}E), similar to its decreased performance in the simulated data (\autoref{A:fig:S02}). This was due to true variants being removed by the internal filters of the tool (\autoref{A:fig:S05}C, D). This is in stark contrast to our novel workflows, where the joint analysis preserves all called sites from the pairwise method and finds additional variants. Overall, Mutect2 found less validated variants in all patients than both Strelka2Pass (mean: $2.2$) and FreeBayesSomatic (mean: $2.5$) with comparable levels of precision (\autoref{A:fig:S08}, \autoref{A:fig:S10}) but longer run times (\autoref{A:tab:S2}).

Our improved workflow also enabled the discovery of multiallelic variants with Strelka2, which led to the discovery of on average $42$ additional variants (min: $1$; max: $535$) in the analysed WES and $987$ additional variants in the WGS (min: $81$; max $2329$). These variants are strong indicators of sub clonal structure and are invaluable for the study of evolutionary trajectories in cancer, as shown in the following sections.


\documentclass[12pt]{article}
%\sloppy
\textheight24.7cm
\textwidth18.0cm
\topmargin-1.5cm
\oddsidemargin-1.0cm
\evensidemargin0.0cm
\usepackage{times}
\usepackage{amsmath}
%\renewcommand{\baselinestretch}{2}
\newcommand{\be}[1]{\begin{equation} \label{#1}}
\newcommand{\ee}{\end{equation}}
\newcommand{\bea}[1]{\begin{eqnarray} \label{#1}}
\newcommand{\eea}{\end{eqnarray}}
\newcommand{\bean}{\begin{eqnarray*}}
\newcommand{\eean}{\end{eqnarray*}}

\newcommand{\non}{\nonumber\\}
\newcommand{\eq}[1]{(\ref{#1})}
\newcommand{\difp}[2]{\frac{\partial #1}{\partial #2}}
\newcommand{\br}{{\bf r}}
\newcommand{\bR}{{\bf R}}
\newcommand{\bA}{{\bf A}}
\newcommand{\bB}{{\bf B}}
\newcommand{\bE}{{\bf E}}
\newcommand{\bm}{{\bf m}}
\newcommand{\bn}{{\bf n}}
\newcommand{\bN}{{\bf N}}
\newcommand{\bp}{{\bf p}}
\newcommand{\bF}{{\bf F}}
\newcommand{\bz}{{\bf z}}
\newcommand{\bZ}{{\bf Z}}
\newcommand{\bV}{{\bf V}}
\newcommand{\bv}{{\bf v}}
\newcommand{\bu}{{\bf u}}
\newcommand{\bx}{{\bf x}}
\newcommand{\bX}{{\bf X}}
\newcommand{\bJ}{{\bf J}}
\newcommand{\bj}{{\bf j}}
\newcommand{\bk}{{\bf k}}
\newcommand{\bTheta}{{\bf \Theta}}
\newcommand{\btheta}{{\boldsymbol\theta}}
\newcommand{\bOmega}{{\bf \Omega}}
\newcommand{\bomega}{{\boldsymbol\omega}}
\newcommand{\brho}{{\boldsymbol\rho}}
\newcommand{\rd}{{\rm d}}
\newcommand{\rJ}{{\rm J}}
\newcommand{\ph}{{\varphi}}
\newcommand{\te}{\theta}
\newcommand{\tht}{\vartheta}
\newcommand{\vpar}{v_\parallel}
\newcommand{\vparkb}{v_{\parallel k b}}
\newcommand{\vparkm}{v_{\parallel k m}}
\newcommand{\Jpar}{J_\parallel}
\newcommand{\ppar}{p_\parallel}
\newcommand{\Bpstar}{B_\parallel^*}
\newcommand{\intpi}{\int\limits_{0}^{2\pi}}
\newcommand{\summ}{\sum \limits_{m=-\infty}^\infty}
\newcommand{\tb}{\tau_b(\uv)}
\newcommand{\bh}{{\bf h}}
\newcommand{\cE}{{\cal E}}
\newcommand{\cB}{{\cal B}}
\newcommand{\cg}{{\cal G}}
\newcommand{\odtwo}[2]{\frac{\rd #1}{\rd #2}}
\newcommand{\pdone}[1]{\frac{\partial}{\partial #1}}
\newcommand{\pdtwo}[2]{\frac{\partial #1}{\partial #2}}
\newcommand{\ds}{\displaystyle}
%\newcommand{\bc}{\begin{center}
%\newcommand{\ec}{\end{center}}
%\input{prespan}

\begin{document}

\section{Canonical flux coordinates obtained from VMEC data}

\subsection{VMEC data}
\label{ssec:vmecdata}

VMEC code provides the data in his own flux coordinates $(s,\theta,\varphi)$ where
$s=\psi_{\rm tor}/\psi_{\rm tor}^{(a)}$ is the toroidal flux $\psi_{\rm tor}$ normalized
by its value $\psi_{\rm tor}^{(a)}$ at the last closed magnetic surface,
$\theta$ - poloidal angle of VMEC and $\varphi$ - usual azimuth of cylindrical coordinates.
Angles here do not make a straight field line coordinate system.
Output of the code consists of three 3D function which are poloidal coordinates $R(s,\theta,\varphi)$
and $Z(s,\theta,\varphi)$, and the stream function $\lambda(s,\theta,\varphi)$, and of three 1D functions
which are the rotational transform angle $\iota(s)$, normalized poloidal flux $\psi_{\rm pol}(s)$ and
toroidal magnetic field flux $\psi_{\rm tor}(s)$ (linear function). Normalized magnetic field fluxes
differ from full fluxes $\Psi_{\rm pol}$ and $\Psi_{\rm tor}$ by a factor of $2\pi$,
$\Psi_{\rm pol}=2\pi\psi_{\rm pol}$, $\Psi_{\rm tor}=2\pi\psi_{\rm tor}$.

\noindent
Stream function $\lambda$ determines the conversion to straight field line coordinates $(s,\vartheta,\varphi)$
which are so-called symmetry flux coordinates with poloidal angle
\be{defpolangle}
\vartheta = \theta + \lambda(s,\theta,\varphi).
\ee
There-dimensional functions are represented in the form of stellarator-symmetric Fourier series,
\bea{stelsymseries}
R(s,\theta,\varphi) &=& \sum_{k=1}^{N_F} R_{m_k n_k}(s)\cos(m_k\theta-n_k\varphi),
\nonumber \\
Z(s,\theta,\varphi) &=& \sum_{k=1}^{N_F} Z_{m_k n_k}(s)\sin(m_k\theta-n_k\varphi),
\\
\lambda(s,\theta,\varphi) &=& \sum_{k=1}^{N_F} \lambda_{m_k n_k}(s)\sin(m_k\theta-n_k\varphi),
\nonumber
\eea
where poloidal, $m_k$, and toroidal, $n_k$, Fourier harmonic indices are numbered in the single list by list index $k$
with total number of harmonics $N_F$. Fourier amplitudes $R_{m_k n_k}$, $Z_{m_k n_k}$ and $\lambda_{m_k n_k}$ as well
as 1D quantities $\iota$, $\psi_{\rm pol}$ and $\psi_{\rm tor}$ are given at knots $s=s_j$ of an equidistant grid
in $s$ with $1\le j \le N_s$ such that $s_{j_{N_s}}=1$.

\noindent
With this, magnetic field is presented in the form
\be{magfieldform}
\bB=\nabla\varphi\times\nabla\psi_{\rm pol}+\nabla\psi_{\rm tor}\times\nabla\left(\theta+\lambda\right)
=\nabla\times\left(\psi_{\rm tor}\nabla\vartheta-\psi_{\rm pol}\nabla\varphi\right)
=\nabla\times\left(A_\vartheta\nabla\vartheta+A_\varphi\nabla\varphi\right),
\ee
where $A_\vartheta=\psi_{\rm tor}$ and $A_\varphi=-\psi_{\rm pol}$ are covariant components of vector-potential.
Since $\iota$, poloidal and toroidal fluxes are linked together by the relation~\eq{iotadef} below,
information about these
1D quantities is redundant. Therefore, one should use only $\iota(s)$ or $\psi_{\rm pol}(s)$ for data consistency,
and reconstruct the other one from~\eq{iotadef}.

\subsection{Flux coordinates with $B_r=0$}

\noindent
From now on we would formally introduce more general notation for the flux surfaces label $r$, which would
play a role of radial coordinate, although all results will be obtained later setting $r=s$.
In order to find suitable, ``canonical'' coordinates with zero radial covariant magnetic field component,
$B_r=0$, we start from some straight field line flux coordinates $\bx=(r,\vartheta,\varphi)$ which in our case
are symmetry flux coordinates.
General properties of straight field line flux coordinates are the following.
\begin{itemize}
\item
Vector potential is already of the desired form,
\be{Aflux}
\bA = A_\vartheta\nabla\vartheta+A_\varphi\nabla\varphi,
\ee
where covariant components $A_\vartheta=\psi_{\rm tor}(r)$ and
$A_\varphi=-\psi_{\rm pol}(r)$ are expressed through the
poloidal and toroidal fluxes divided by $2\pi$, respectively.
\item
Magnetic field, consequently, is expressed through the contra-variant components
as
\be{Bflux}
\bB =
\nabla A_\vartheta\times\nabla\vartheta
+\nabla A_\varphi\times\nabla\varphi
=
 A_\vartheta^\prime \nabla r\times\nabla\vartheta
+A_\varphi^\prime \nabla r\times\nabla\varphi
=
\frac{A_\vartheta^\prime}{\sqrt{g}}\difp{\br}{\varphi}
-\frac{A_\varphi^\prime}{\sqrt{g}}\difp{\br}{\vartheta}
=
B^k \difp{\br}{x^k},
\ee
where metric determinant $g$ is given by
\be{sqrtg}
\sqrt{g}=\difp{\br}{r}\cdot\difp{\br}{\varphi}\times\difp{\br}{\vartheta}
=\frac{1}{\nabla r \cdot \nabla\vartheta\times\nabla\varphi}
\ee
Namely, Eq.~\eq{Bflux} gives for the contra-variant components
\be{conraBcomp}
B^r=0,
\qquad B^\vartheta
= -\frac{A_\varphi^\prime}{\sqrt{g}}
=\frac{\psi_{\rm pol}^\prime}{\sqrt{g}},
\qquad B^\varphi
= \frac{A_\vartheta^\prime}{\sqrt{g}}
= \frac{\psi_{\rm tor}^\prime}{\sqrt{g}},
\ee
and, as a consequence,
the property of straight field lines $B^\vartheta=\iota(r) B^\varphi$
where
\be{iotadef}
\iota(r)=\frac{1}{q(r)}=-\frac{A_\vartheta^\prime}{A_\varphi^\prime}
=\frac{\psi_{\rm pol}^\prime(r)}
{\psi_{\rm tor}^\prime(r)}=
\frac{\rd \psi_{\rm pol}}{\rd \psi_{\rm tor}}
\ee
is the rotational transform ($q$ is a safety factor).
\item
Covariant field components follow from the usual tensor transformation
\be{bcovar}
B_i = g_{ij}B^j=g_{i\vartheta}B^\vartheta+g_{i\varphi}B^\varphi
=\difp{\br}{x^i}\cdot\difp{\br}{\vartheta}B^\vartheta+\difp{\br}{x^i}\cdot\difp{\br}{\varphi}B^\varphi.
\ee
\item
Different straight field line flux coordinate systems $\bx=(r,\vartheta,\varphi)$ and
$\bx_c=(r_c,\vartheta_c,\varphi_c)$ (which always assume
that $r_c=f(r)$ where $f(r)$ is a monotonous function)
are linked with each other by the transform of angles
\be{transangles}
\vartheta_c = \vartheta+\iota(r)G(\bx),
\qquad
\varphi_c = \varphi+G(\bx),
\ee
where $G(\bx)$ is a single valued function
(periodic function of angles $\vartheta$ and $\varphi$).
Since all properties~\eq{Bflux}-\eq{conraBcomp} follow from~\eq{Aflux}
let us check its invariance
\be{Acheck}
\bA=
A_\vartheta\nabla\left(\vartheta+\iota G\right)
+
A_\varphi\nabla\left(\varphi+ G\right)
=
A_\vartheta\nabla\vartheta+A_\varphi\nabla\varphi
+\nabla\left(\iota A_\vartheta G+A_\varphi G\right),
\ee
where we used~\eq{iotadef}. Last term is a gradient and can be removed from
the vector potential (what means a gauge transformation) which leaves then co-variant components unchanged.
\end{itemize}
In the following we will not modify the flux surface label such that $r_c=r$.
When looking for the coordinate system $\bx_c$ with zero co-variant radial magnetic
field component it is more convenient to look for the inverse
transform
\be{invtrans}
\vartheta = \vartheta_c+\iota(r)G_c(\bx_c),
\qquad
\varphi = \varphi_c+G_c(\bx_c).
\ee
From the transformation of co-variant components of the magnetic field,
\bea{Bcovar}
B_k^c=B_j\difp{x^j}{x_c^k},
\eea
and the condition $B^c_r=0$ we obtain the nonlinear ODE for $G_c$,
\be{eqforG}
\difp{}{r}G_c(r,\vartheta_c,\varphi_c)=
-\frac{B_r(r,\vartheta,\varphi)
+\iota^\prime(r) B_\vartheta(r,\vartheta,\varphi) G_c(r,\vartheta_c,\varphi_c)}
{\iota(r)B_\vartheta(r,\vartheta,\varphi)
+B_\varphi(r,\vartheta,\varphi)},
\ee
where $\vartheta=\vartheta(\bx_c)$ and $\varphi=\varphi(\bx_c)$ must be substituted from Eq.~\eq{invtrans}.
In the tokamak case, magnetic field components are independent of the
toroidal angle and, therefore, $G_c=G_c(r,\vartheta_c)$. As a result, components
of the magnetic field are independent of $\varphi_c$ in the new coordinates
too.

\noindent
Set of quantities required for the formulation of guiding center equations in the canonical form
is covariant components of vector potential, $A_\vartheta^c=A_\vartheta$ and $A_\varphi^c=A_\varphi$,
magnetic field strength $B$ and covariant components of the magnetic field $B_\vartheta^c$ and $B_\varphi^c$.
Using the relations~\eq{Bcovar} and~\eq{invtrans},
the latter two are expressed with help of function $G_c$ via corresponding components
$B_\vartheta$ and $B_\varphi$ in symmetry flux coordinates as follows,
\bea{covarBcan}
B_\vartheta^c
&=&
B_\vartheta + \left(\iota B_\vartheta+B_\varphi\right)\difp{}{\vartheta_c}G_c(\bx_c),
\nonumber \\
B_\varphi^c
&=&
B_\varphi + \left(\iota B_\vartheta+B_\varphi\right)\difp{}{\varphi_c}G_c(\bx_c).
\eea

\subsection{Direct transformation from VMEC coordinates to canonical coordinates}

\noindent
As one can see from the structure of VMEC data in section~\ref{ssec:vmecdata}
3D functions are explicitly given as functions of intrinsic VMEC coordinates $\bx_V=(s,\theta,\varphi)$
but of symmetry flux coordinates $\bx=(s,\vartheta,\varphi)$. It is convenient to avoid transformation
of 3D functions to functions of $\bx$ and obtain final results in canonical coordinates $\bx_c$
directly from VMEC coordinates $\bx_V$. For this purpose we denote covariant magnetic filed
components in symmetry flux coordinates $B_k$ expressed as functions of VMEC coordinates $\bx_V$ as
follows
\be{dentcov}
B_k\left(r,\vartheta(r,\theta,\varphi),\varphi\right)=\cB_k(r,\theta,\varphi).
\ee
Then, equation~\eq{eqforG} for transformation function $G_c$ becomes
\be{eqforG_VMEC}
\difp{}{r}G_c(\bx_c)\equiv
\difp{}{r}G_c(r,\vartheta_c,\varphi_c)=
-\frac{\cB_r\left(r,\theta(\bx_c),\varphi(\bx_c)\right)
+\iota^\prime(r) \cB_\vartheta\left(r,\theta(\bx_c),\varphi\right) G_c(r,\vartheta_c,\varphi_c)}
{\iota(r)\cB_\vartheta\left(r,\theta(\bx_c),\varphi(\bx_c)\right)
+\cB_\varphi\left(r,\theta(\bx_c),\varphi(\bx_c)\right)},
\ee
where functions $\theta(\bx_c)$ and $\varphi(\bx_c)$ are implicitly defined by
\be{vmec_via_can}
\theta(\bx_c) + \lambda\left(r,\theta(\bx_c),\varphi(\bx_c)\right) = \vartheta_c+\iota(r)G_c(\bx_c),
\qquad
\varphi(\bx_c) = \varphi_c+G_c(\bx_c).
\ee
which follows from~\eq{invtrans} and~\eq{defpolangle}. First of these functions, $\theta(\bx_c)$, can be
computed by Newton method. The covariant canonical components of the magnetic field~\eq{covarBcan} then are
\bea{covarBcan_VMEC}
B_\vartheta^c(\bx_c)
&=&
\cB_\vartheta\left(r,\theta(\bx_c),\varphi(\bx_c)\right) +
\left(\iota(r) \cB_\vartheta\left(r,\theta(\bx_c),\varphi(\bx_c)\right)
+\cB_\varphi\left(r,\theta(\bx_c),\varphi(\bx_c)\right)\right)\difp{}{\vartheta_c}G_c(\bx_c),
\nonumber \\
B_\varphi^c(\bx_c)
&=&
\cB_\varphi\left(r,\theta(\bx_c),\varphi(\bx_c)\right)
+ \left(\iota(r) \cB_\vartheta\left(r,\theta(\bx_c),\varphi(\bx_c)\right)
+\cB_\varphi\left(r,\theta(\bx_c),\varphi(\bx_c)\right)\right)\difp{}{\varphi_c}G_c(\bx_c).
\eea
Since expression~\eq{conraBcomp} for contra-variant components of are the same in all straight field line
flux coordinates and covariant components of vector potential are the same too,
what remains is to obtain metric determinant of canonical coordinates $g_c$ in order to define those components as
\be{conraBcomp_can}
B^r_c(\bx_c)=0,
\qquad B^\vartheta_c(\bx_c)
= -\frac{A_\varphi^\prime(r)}{\sqrt{g_c(\bx_c)}},
\qquad B^\varphi_c(\bx_c)
= \frac{A_\vartheta^\prime(r)}{\sqrt{g_c(\bx_c)}}.
\ee
First, let us compute using Jacobians metric determinant of VMEC coordinates, $g_V$,
via metric determinant of cylindrical coordinates $(R,\varphi,Z)$ which are known functions of VMEC coordinates
$\bx_V=(s,\theta,\varphi)=(r,\theta,\varphi)$,
\be{g_VMEC}
\sqrt{g_V(\bx_V)}=\difp{(\br)}{(\bx_V)}=R\difp{(R,\varphi,Z)}{(r,\theta,\varphi)}=R\difp{(R,Z)}{(\theta,r)}
=R\left(\difp{R}{\theta}\difp{Z}{r}-\difp{Z}{\theta}\difp{R}{r}\right).
\ee
Metric determinant of canonical coordinates, $g_c$, follows then as
\bea{g_can}
\sqrt{g_c(\bx_c)}
&=&
\difp{(\br)}{(\bx_c)}=\difp{(\br)}{(\bx_V)}\difp{(\bx_V)}{(\bx_c)}
=\sqrt{g_V(\bx_V)}\difp{(r,\theta,\varphi)}{(r,\theta_c,\varphi_c)}
\nonumber \\
&=&
\sqrt{g_V(\bx_V(\bx_c))}\left(\difp{\theta(\bx_c)}{\vartheta_c}\difp{\varphi(\bx_c)}{\varphi_c}
-\difp{\varphi(\bx_c)}{\vartheta_c}\difp{\theta(\bx_c)}{\varphi_c}\right)
\nonumber \\
&=&
\sqrt{\cg\left(\bx_V(\bx_c)\right)}\left(1+\iota(r) \difp{G_c(\bx_c)}{\vartheta_c}+\difp{G_c(\bx_c)}{\varphi_c}\right),
\eea
where dependencies $\bx_V(\bx_c)$ of VMEC coordinates on canonical coordinates are known via~\eq{vmec_via_can},
and with $\sqrt{\cg(\bx_V)}$ we denote the Jacobian of symmetry flux coordinates $\sqrt{g}$ as function of VMEC coordinates,
$\sqrt{\cg(\bx_V)}=\sqrt{g\left(\bx(\bx_V)\right)}$.

\noindent
What is still missing here, it is functions $\cB_k$ used in Eq.~\eq{eqforG_VMEC} and in~\eq{covarBcan_VMEC}.
We obtain these functions from contra-variant components in symmetry flux coordinates, $B^k$
\be{covar_symm}
B_k = g_{k\vartheta} B^\vartheta+g_{k\varphi} B^\varphi
=\frac{A^\prime_\vartheta}{\sqrt{g}}\left(g_{k\varphi}+\iota g_{k\vartheta}\right),
\ee
where we used~\eq{conraBcomp} and~\eq{iotadef}. To make~\eq{covar_symm} a definition of functions $\cB_k$
we need to obtain $\sqrt{g}$ and $g_{ik}$ of symmetry flux coordinates as functions of VMEC coordinates.
First of these follows as
\be{sqg_sym}
\sqrt{g}=\sqrt{g_V}\difp{(r,\theta,\varphi)}{(r,\vartheta,\varphi)}
= \sqrt{g_V}\left(\difp{\vartheta}{\theta}\right)^{-1}
= \sqrt{g_V(\bx_V)}\left(1+\difp{}{\theta}\lambda(\bx_V)\right)^{-1}.
\ee
Metric tensor of symmetry flux coordinates $g_{ik}$ is obtained from metric tensor of VMEC coordinates $g_{ik}^V$
which has the following components
\bea{gik_VMEC}
g^V_{rr} &=& \left(\difp{R}{r}\right)^2+\left(\difp{Z}{r}\right)^2,
\nonumber \\
g^V_{r\theta} &=& g^V_{\theta r} = \difp{R}{r}\difp{R}{\theta}+\difp{Z}{r}\difp{Z}{\theta},
\nonumber \\
g^V_{r\varphi} &=& g^V_{\varphi r} = \difp{R}{r}\difp{R}{\varphi}+\difp{Z}{r}\difp{Z}{\varphi},
\nonumber \\
g^V_{\theta\theta} &=& \left(\difp{R}{\theta}\right)^2+\left(\difp{Z}{\theta}\right)^2,
\nonumber \\
g^V_{\theta\varphi} &=& g^V_{\varphi \theta} = \difp{R}{\theta}\difp{R}{\varphi}+\difp{Z}{\theta}\difp{Z}{\varphi},
\nonumber \\
g^V_{\varphi\varphi} &=& R^2+\left(\difp{R}{\varphi}\right)^2+\left(\difp{Z}{\varphi}\right)^2.
\eea
In order to use
\be{transV-c}
g_{ik}=g_{mn}^V c^m_i c^n_k, \qquad c^m_i \equiv \difp{x_V^m}{x^i}
\ee
we calculate the inverse matrix $\bar c^i_k$ such that
\be{invmatc}
\bar c^i_k c^k_j = \delta^i_j, \qquad \bar c^i_j = \difp{x^i}{x_V^j}.
\ee
Explicitly, components of this matrix are
\bea{cbar_elements}
& & \bar c^r_r=1, \qquad \bar c^r_\theta=0, \qquad \bar c^r_\varphi=0,
\nonumber \\
& & \bar c^\vartheta_r=\difp{\lambda}{r},
\qquad \bar c^\vartheta_\theta=1+\difp{\lambda}{\theta}, \qquad \bar c^\vartheta_\varphi=\difp{\lambda}{\varphi},
\nonumber \\
& & \bar c^\varphi_r=0, \qquad \bar c^\varphi_\theta=0, \qquad \bar c^\varphi_\varphi=1.
\eea
Respectively, components of matrix $c^i_j$ are
\bea{c_elements}
& & c^r_r=1, \qquad c^r_\vartheta=0, \qquad c^r_\varphi=0,
\nonumber \\
& & c^\theta_r=-\difp{\lambda}{r}\left(1+\difp{\lambda}{\theta}\right)^{-1},
\qquad c^\theta_\vartheta=\left(1+\difp{\lambda}{\theta}\right)^{-1},
\qquad c^\theta_\varphi=-\difp{\lambda}{\varphi}\left(1+\difp{\lambda}{\theta}\right)^{-1},
\nonumber \\
& & c^\varphi_r=0, \qquad c^\varphi_\vartheta=0, \qquad c^\varphi_\varphi=1.
\eea

\subsection{Numerical realization}

\noindent
Equation~\eq{eqforG_VMEC} is a nonlinear ODE with respect to variable $r$ where variables $\vartheta_c$
and $\varphi_c$ play a role of parameters. Therefore, family of solutions to this equation non-trivially
depends on initial radial integration point and a starting value of $G_c$ which can be an arbitrary function
of parameters $\vartheta_c$ and $\varphi_c$. Our choice of initial integration point is half radius because
near the last closed magnetic surface and near the magnetic axis VMEC data suffers from numerical pollution.
Integration constant will be fixed to zero.

For numerics, we spline $R(\bx_V)$, $Z(\bx_V)$ and $\lambda(\bx_V)$ in 3D using 5-th order splines (periodic
in $\theta$ and $\varphi$) and spline $A_\varphi$ and $A_\vartheta$ in 1D. Then all necessary derivatives of
these functions are available. Equation~\eq{eqforG_VMEC} is solved then by RK4/5 for each node of the
equidistant grid in $\vartheta_c$ and $\varphi_c$, and the transformation function $G_c$ is again splined
in 3D on $\bx_c$ grid. Using these two kinds of 3D splines (on $\bx_V$ grid and on $\bx_c$ grid) the covariant
components $B^c_\vartheta$ and $B^c_\varphi$ and metric determinant $\sqrt{g_c}$ can be computed on $\bx_c$
grid. The rest quantities (contra-variant components $B_c^\vartheta$ and $B_c^\varphi$, module of magnetic field
$B$) can be computed using 3D spline interpolation of those 3 quantities and 1D spline interpolation for
covariant components of vector potentials $A_\vartheta$ and $A_\varphi$.

\subsection{Canonical form of guiding center equations}

Guiding center Lagrangian, which has in general curvilinear coordinates $\bx$ the following form,
\be{lagrgencoord}
L_{gc} = \left(mv_\parallel h_k+\frac{e}{c}A_k\right)\dot x^k-J_\perp\dot\phi-H,
\ee
where $h_k = B_k /B$, and the Hamiltonian is
\be{gcham}
H=J_\perp\omega_c+\frac{mv_\parallel^2}{2}+e\Phi,
\ee
in canonical straight field line coordinates $\bx_c$ where covariant radial components of both, vector potential
and magnetic field are zeros, $A_r^c=B_r^c=0$, takes a short form
\be{lagrcancoord}
L_{gc} =
\left(mv_\parallel h_\vartheta^c+\frac{e}{c}A_\vartheta^c\right)\dot \vartheta_c
+
\left(mv_\parallel h_\varphi^c+\frac{e}{c}A_\varphi^c\right)\dot \varphi_c
-
J_\perp\dot\phi-H.
\ee
\noindent
Introducing in~\eq{lagrcancoord} the notation
\be{canmomenta}
p_\vartheta=mv_\parallel h_\vartheta^c+\frac{e}{c}A_\vartheta^c,
\qquad
p_\varphi=mv_\parallel h_\varphi^c+\frac{e}{c}A_\varphi^c,
\ee
we obtain the canonical form of the Lagrangian,
\be{Lagr_can}
L_{gc}=p_\vartheta\dot\vartheta_c+p_\varphi\dot\varphi_c- J_\perp\dot\phi-H.
\ee
Note that we did not specify here the independent variables. Lagrangian does
not depend on this choice. If we choose $p_\vartheta$ and $p_\varphi$ instead
of $r$ and $H$, we obtain Hamiltonian equations of motion,
\be{hameqs}
\dot J_\perp = 0, \quad \dot\phi=-\difp{H}{J_\perp},
\qquad
\dot p_\vartheta = - \difp{H}{\vartheta_c}, \quad
\dot \vartheta_c = \difp{H}{p_\vartheta},
\qquad
\dot p_\varphi = - \difp{H}{\varphi_c}, \quad
\dot \varphi_c = \difp{H}{p_\varphi},
\ee
where $H=H(\vartheta_c,\varphi_c,J_\perp,p_\vartheta,p_\varphi)$. These equations
are still different from the usual form because of the sign of the Hamiltonian
in the first pair (sign in the equation for $\dot\phi$). Standard form can be
obtained by either changing the sign of $J_\perp\rightarrow -J_\perp$
(usual way in the literature) or by changing the sign of the gyrophase,
$\phi\rightarrow-\phi$, as in our cylindrical model where the gyrophase is
counted clockwise (in mathematically negative direction).

\section{Boozer flux coordinates obtained from VMEC data}

\subsection{Generating function from transformation of covariant field components}
\label{ssec:covartrans}

We denote here a set of Boozer flux coordinates as $\bx_B=(r,\vartheta_B,\varphi_B)$.
In these coordinates, field is fully described by two 3D functions, namely, module
of $B=B(r,\vartheta_B,\varphi_B)$ and covariant radial field components
$B_r^B=B_r^B(r,\vartheta_B,\varphi_B)$ while the other two covariant components
are 1D, $B_\vartheta^B=B_\vartheta^B(r)$ and $B_\varphi^B=B_\varphi^B(r)$.
Our task is to obtain generating function $G_B(\bx_b)$ in the inverse transform
similar to~\eq{invtrans}. Given are field components $B_k$ in symmetry flux coordinates
$\bx=(r,\vartheta,\varphi)$ as functions of VMEC coordinates $\bx_V=(r,\theta,\varphi)$ and
stream function $\lambda(\bx_V)$ linking $\theta$ and $\vartheta$ via~\eq{defpolangle}.
With this, we have covariant field components in VMEC coordinates given as
\be{covvmec}
B_\theta^V=\left(1+\difp{\lambda}{\theta}\right)B_\vartheta,
\qquad
B_\varphi^V=B_\varphi+\difp{\lambda}{\varphi}B_\vartheta.
\ee
Using Stoke's theorem,
\be{stokes}
\frac{4\pi}{c}\int\limits_S \rd{\bf S}\cdot\bj=\oint\limits_{\partial S}\rd {\bf l}\cdot\bB,
\ee
where $\rd{\bf S}$ is the element of area $S$ bounded by the line $\partial S$, and $\rd {\bf l}$
is the element of this bounding line. Choosing for the bounding line a poloidal or toroidal contour
whose elements can be described in any flux coordinate system, including VMEC coordinates system $\bx_V$,
as
\be{lineels}
\rd {\bf l}_{\rm pol}=\difp{\br(\bx_V)}{\theta}\rd\theta,
\qquad
\rd {\bf l}_{\rm tor}=\difp{\br(\bx_V)}{\varphi}\rd\varphi,
\ee
so that both line elements are tangential to the magnetic flux surface $r=const$ we obtain in the
l.h.s of~\eq{stokes} toroidal and poloidal currents through the areas $S_{\rm pol}$ and $S_{\rm tor}$
limited by poloidal and toroidal contours $\partial S_{\rm pol}$ and $\partial S_{\rm tor}$,
respectively,
\be{currents}
\int\limits_{S_{\rm pol}} \rd{\bf S}\cdot\bj=I_{\rm tor}(r),
\qquad
\int\limits_{S_{\rm tor}} \rd{\bf S}\cdot\bj=I_{\rm pol}(r).
\ee
Thus
\bea{stokespolotor}
\frac{4\pi}{c}I_{\rm tor}(r)
&=&
\oint\limits_{\partial S_{\rm pol}}\rd {\bf l}_{\rm pol}\cdot\bB
=\int\limits_0^{2\pi}\rd\theta \difp{\br(\bx_V)}{\theta}\cdot \bB
=\int\limits_0^{2\pi}\rd\theta B_\theta^V(\bx_V),
\nonumber \\
\frac{4\pi}{c}I_{\rm pol}(r)
&=&
\oint\limits_{\partial S_{\rm tor}}\rd {\bf l}_{\rm tor}\cdot\bB
=\int\limits_0^{2\pi}\rd\varphi \difp{\br(\bx_V)}{\varphi}\cdot \bB
=\int\limits_0^{2\pi}\rd\varphi B_\varphi^V(\bx_V).
\eea
Since Boozer components are constant on flux surface, we obtain
\be{boozcur}
\frac{2}{c}I_{\rm tor}(r)=B_\vartheta^B(r),
\qquad
\frac{2}{c}I_{\rm pol}(r)=B_\varphi^B(r),
\ee
and, respectively,
\be{boozcovar}
B_\vartheta^B(r)=\frac{1}{2\pi}\int\limits_0^{2\pi}\rd\theta B_\theta^V(\bx_V),
\qquad
B_\varphi^B(r)=\frac{1}{2\pi}\int\limits_0^{2\pi}\rd\varphi B_\varphi^V(\bx_V).
\ee
For a perfect equilibrium, integrals~\eq{boozcovar} are independent of $\varphi$
and $\theta$, respectively, however some weak dependence may appear due to numerical
imperfections. Therefore, we compute Boozer components as double integrals
\be{boozcovar_double}
B_{\vartheta,\varphi}^B(r)=\frac{1}{4\pi^2}
\int\limits_0^{2\pi}\rd\theta
\int\limits_0^{2\pi}\rd\varphi
B_{\theta,\varphi}^V(\bx_V),
\ee
well approximated by the sums over equidistant grid
\be{boozcovar_sum}
B_{\vartheta,\varphi}^B(r)\approx\frac{1}{N_\theta N_\varphi}
\sum\limits_{i_\theta=1}^{N_\theta} \sum\limits_{i_\varphi=1}^{N_\varphi}
B_{\theta,\varphi}^V\left(r,\frac{2 \pi i_\theta}{N_\theta},\frac{2\pi i_\varphi}{N_\varphi}\right).
\ee
Since we get Boozer's covariant angular components in this easy way, we can find an equation for the
forward transformation function $G_F(\bx_V)=G_B(\bx_B(\bx_V))$ from the transform of covariant components
to symmetry flux variables where
\be{symmtobooz}
\vartheta_B=\vartheta+\iota G_F, \qquad \varphi_B=\varphi+G_F.
\ee
Namely, we get
\be{covtrans}
B_\vartheta=B_\vartheta^B+
\left(\iota B_\vartheta^B+B_\varphi^B\right)\difp{(G_F,\varphi)}{(\vartheta,\varphi)},
\qquad
B_\varphi=B_\varphi^B+\left(\iota B_\vartheta^B+B_\varphi^B\right)\difp{(\vartheta,G_F)}{(\vartheta,\varphi)},
\ee
where we used Jacobians to indicate fixed variable during differentiation.
Using~\eq{defpolangle} and properties of the Jacobians for transformation to derivatives over VMEC variables
we finally obtain
\bea{dGdphi}
\difp{G_F}{\varphi}\equiv \difp{(\theta,G_F)}{(\theta,\varphi)}
&=&
\frac{1}{\iota B_\vartheta^B+B_\varphi^B}\left(B_\varphi-B_\varphi^B
+\difp{\lambda}{\varphi}\left(B_\vartheta-B_\vartheta^B\right)
\right)
\nonumber \\
&=&
\frac{1}{\iota B_\vartheta^B+B_\varphi^B}\left(B_\varphi^V-B_\varphi^B
-\difp{\lambda}{\varphi}B_\vartheta^B\right)
\eea
with~\eq{covvmec} used in the last expression. Similarly we obtain another partial derivative,
\be{dGdtheta}
\difp{G_F}{\theta}\equiv \difp{(G_F,\varphi)}{(\theta,\varphi)}
=
\frac{1}{\iota B_\vartheta^B+B_\varphi^B}\left(B_\theta^V
-B_\vartheta^B\left(1+\difp{\lambda}{\theta}\right)\right).
\ee
Integrating~\eq{dGdtheta} for $\varphi=0$ we obtain $G_F(r,\theta,0)$ which is a starting value
for integration of~\eq{dGdphi} giving $G_F(\bx_V)$ up to a flux surface constant $G_F(r,0,0)$,
\bea{G_F}
G_F(r,\theta,\varphi)
&=&
G_F(r,0,0)+
\frac{1}{\iota B_\vartheta^B(r)+B_\varphi^B(r)}
\left(
\int\limits_0^\varphi\rd\varphi^\prime B_\varphi^V(r,\theta,\varphi^\prime)
-\frac{\varphi}{2\pi}\int\limits_0^{2\pi}\rd\varphi^\prime B_\varphi^V(r,\theta,\varphi^\prime)
\right.
\nonumber \\
&+&
\left.
\int\limits_0^\theta\rd\theta^\prime B_\theta^V(r,\theta^\prime,0)
-\frac{\theta}{2\pi}\int\limits_0^{2\pi}\rd\theta^\prime B_\theta^V(r,\theta^\prime,0)
-B_\vartheta^B(r)\left(\lambda(r,\theta,\varphi)-\lambda(r,0,0)\right)
\right).
\eea
In this form where we used Eqs.~\eq{boozcovar} for some occurrences of covariant Boozer components,
generating function is perfectly periodic even in presence of numerical imperfections of the equilibrium.
Integrals in~\eq{G_F} are computed uploading field components to the equidistant grid in $(\theta,\varphi)$
and using periodic spline approximation.

With this, we obtain two transformation functions specified on the equidistant $(\theta,\varphi)$ grid,
\be{deltp_BV}
\Delta\vartheta_{BV}(r,\theta,\varphi)\equiv\vartheta_B-\theta
=\iota(r) G_F(r,\theta,\varphi)+\lambda(r,\theta,\varphi),
\qquad
\Delta\varphi_{BV}(r,\theta,\varphi)\equiv \varphi_B-\varphi
=G_F(r,\theta,\varphi).
\ee
These function map the equidistant grid in $(\theta,\varphi)$ into non-equidistant grid in
$(\vartheta_B,\varphi_B)$. In order to find the inverse transform $\theta=\theta(r,\vartheta_B,\varphi_B)$
and $\varphi=\varphi(r,\vartheta_B,\varphi_B)$ we simply re-interpolate functions $\Delta\vartheta_{BV}$
and $\Delta\varphi_{BV}$ to the new, equidistant grid in $(\vartheta_B,\varphi_B)$ using Lagrange polynomial
interpolation on the old non-equidistant $(\vartheta_B,\varphi_B)$ grid. This is performed subsequently
re-interpolating over $\vartheta_B$ keeping $\varphi$ fixed (one needs previously to extend the range of $\theta$
variable from $[0,2\pi]$ to $[-2\pi,4\pi]$ in order to avoid problems with periodic boundaries)
to get $\Delta\vartheta_{BV}(r,\theta(\vartheta_B,\varphi),\varphi)$ and
$\Delta\varphi_{BV}(r,\theta(\vartheta_B,\varphi),\varphi)$
and then over $\varphi_B$ keeping $\vartheta_B$ fixed (similar range extension is needed than for the toroidal
angle).
Re-interpolating $G_F(r,\theta,\varphi)$ and $B(r,\theta,\varphi)$ together with transformation functions
one obtains $G_B(\bx_B)$ and $B(\bx_B)$ specified on the equidistant grid of Boozer angles.
Note that all the functions which are re-interpolated are periodic functions of angles - no problems appear
due to multi-valuedness of angles.

\subsection{Radial component}

For the radial component, we have an expression via symmetry flux components
\bea{B_rsf}
B_r^B &=&
B_r+B_\vartheta\difp{}{r}\vartheta(\bx_B)+B_\varphi\difp{}{r}\varphi(\bx_B)
\nonumber \\
&=&
B_r-B_\vartheta\difp{}{r}\iota(r)G_B(\bx_B)-B_\varphi\difp{}{r}G_B(\bx_B).
\eea
Re-interpolating covariant symmetry flux components $B_k(\bx_V)$ to the equidistant grid of Boozer angles
(within the transformation of the previous section) gives us $B_k(\bx_B)$.
Thus, all quantities in the r.h.s. of~\eq{B_rsf} are specified on the equidistant grid of Boozer angles.
What remains is to compute
radial derivatives by finite difference scheme (we use 4-th order Lagrange polynomial for this).

\bigskip
Finally, we store and spline interpolate up to six 3D functions. Arguments of these functions
indicate equidistant angular grid in particular variables ($\bx_V$ means VMEC grid and $\bx_B$ means Boozer grid).
These functions are $B(\bx_B)$ which is mandatory, $B_r(\bx_B)$ which is optional (needed if one uses usual
integrator for exact orbits), $\Delta \vartheta_{BV}(\bx_V)$ and $\Delta\varphi_{BV}(\bx_V)$ which are also
mandatory but are needed only for the conversion of initial starting points from VMEC to Boozer coordinates
and backward conversion of final points by 2D Newton method (i.e. they are not needed by the integrators), and
$\Delta \vartheta_{BV}(\bx_B)$ and $\Delta\varphi_{BV}(\bx_B)$ (optional). Last two quantities
provide the first iteration for the inverse transformation $\bx_B\rightarrow\bx_V$ however they can be safely
ignored since they save only one iteration (normally 4 Newton iterations converge up to computer accuracy).

\end{document}


\documentclass{article}

%Packages
%	Front
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
%	From template
\usepackage{tabularx}
\usepackage{booktabs}
%	Mine
\usepackage{cite}
\usepackage{graphicx}
\usepackage{indentfirst}
\usepackage{amsmath}
\usepackage{cleveref}
\usepackage{float}
\title{CAS 741: Problem Statement\\STEM Moir{\'e} GPA}

\author{Alexandre Pofelski \\
macid: pofelska}

\date{15 September 2017}

\input{../Comments}

\begin{document}

\maketitle
\clearpage

\begin{table}[hp]
\caption{Revision History} \label{TblRevisionHistory}
\begin{tabularx}{\textwidth}{llX}
\toprule
\textbf{Date} & \textbf{Developer(s)} & \textbf{Change}\\
\midrule
15/09/2017 & Alex & First draft\\
19/09/2017 & Alex & Small revisions\\
\bottomrule
\end{tabularx}
\end{table}

\clearpage
\tableofcontents
\clearpage

\section{Introduction}
\subsection{"STEM"}
The success of semiconductor devices application in the past decades couldn't
have been possible without development of methods able to characterize them.
Build and interconnect billions of transistors with each other on a cm$^{2}$
chip is a real challenge such as measuring the gate length of one of them.
Scanning Transmission Electron Microscopy (STEM) revealed to be a particularly
adapted characterization method to probe matter at atomic scale.
Nowadays, with aberration correctors, it is possible without much difficulty to
form a small electron probe capable to resolve a spacing down to 50pm
\cite{Erni2009}. Such probe is smaller than the atomic spacing by an order of
magnitude therefore, by scanning the probe on the sample and collecting the
electrons crossing it from separate locations (pixels) to form an electron
micrograph, it is possible to image the atomic arrangement of matter. The
scanning range can be extended to a few microns making STEM an efficient
technique to, for example, characterize any semiconductor devices present in a
modern smartphones.
\subsection{"GPA"}
Variety of parameters are affecting the performance of a semiconductor device at
a transistor level. Temperature, defect density, doping concentration are few
examples known to influence the transistor behaviour. Some secondary parameters
like the elastic deformation is also affecting the device performance by
changing the mobility of carriers within the semiconductor material. In current
technologies the silicon underneath the gate of a transistor (channel) must be
elastically deformed to reach the level of performance desired by the market.
Methods to measure locally and quantitatively the elastic strain in crystals
were thus massively developed in the last decades to help the design of
such strained semiconductor devices. One method called Geometric Phase Analysis
(GPA) emerged above its competitor because of its easiness and elegance in
quantifying strain from an atomically resolved STEM electron micrograph (or
image). The Fourier based processing method enabled GPA to track quantitatively
the aperiodicities in the image to convert them into relative strain fields
\cite{Hytch1998}. A sensitivity down to $10^-{3}$ is claimed by the STEM GPA
method with a resolution of roughly 1 nm.
\subsection{"Moir{\'e}"}
A limitation of the STEM GPA technique lies on how spatially extended a strain
map can be. Since a minimum of a few pixels are needed to image the atomic
spacing, the number of pixels of the detection system is limiting the field of
view (FOV) of the electron micrograph. For example, with 16 millions pixels a
FOV up to 150nm can be reached. The more pixels are used the greater is the FOV
however with more pixels, the processing is more resource demanding. To overcome
this issue, a technique based on Moir{\'e} interferometry has been recently
developed. The principle is to make interfere the scanning grid of the STEM
probe with the crystalline lattice of the sample by choosing a scanning step
close but not equal to the atomic spacing (undersampling condition). The
resulting interference generates a STEM Moir{\'e }hologram displaying an altered
version of the sample structural properties on a larger FOV at a cost of a
poorer resolution compared to STEM GPA. To be treatable by the GPA
method, the hologram needs to be converted by removing the alteration generated
by the sampling condition chosen \cite{Pofelski2017}. The STEM Moire GPA method
enables thus the strain field from larger devices to be characterized up to a
few microns.

\section{Objective}
As a scientific program developer, the objective is to implement a program
capable of converting a STEM Moir{\'e} hologram into quantitative relative
strain maps. The relative strain maps correspond to two dimensional (2D) maps
from the 3 components of the 2D strain tensor and a 2D map of the 2D rotation
tensor component. The expectations of the program are summarized in
\cref{fig:STEM_Moire_GPA_Objective}. The software should be able to run on all
major operating system (Windows,Mac,Linux) without being highly resource
demanding to be usable on a desktop computer.
\begin{figure}[H]
	\centering
	\includegraphics[width=\linewidth]{Figures/STEM_Moire_GPA_objective.png}
	\caption[STEM Moir{\'e} GPA objective]{On the left is presented one STEM
Moir{\'e} hologram, with its corresponding fast Fourier transform image
highlighted in the bottom left corner, acquired on two AlGaN/GaN nanowire Light
Emitting Diode (LED) devices. On the right are highlighted the expected relative
strain maps, each one corresponding to their respective component of the strain
and rotation tensor}
	\label{fig:STEM_Moire_GPA_Objective}
\end{figure}

\section{Interest}
As a characterization technique, the STEM Moir{\'e} interferometry method is
relatively easy to implement on any modern transmission electron microscope
equipped with a scanning module and a probe corrector. The only requirement once
the STEM probe is set up, is to define properly the sampling condition of the
scanning grid. In comparison, other holography techniques such as Dark-Field
Electron Holography (DEFH) \cite{Hytch2008} requires the use of a biprism to
bring in interference the diffracted beam issued from two separated areas. In
addition, good quality dark-field holograms can only be achieved if the sampled
is tilted to respect the ``two beam conditions'' \wss{quotation marks should be
  ``done using the proper LaTeX'' symbols} \an{done} which is not straight forward. Other
diffraction based techniques such as Nano Beam (Precession) Electron Diffraction
(NB(P)ED) \cite{Rouviere2013} can also provide large FOV strain maps with
similar simplicity however acquiring a diffraction pattern on each pixel of the
map is very time consuming. Therefore, STEM Moir{\'e} GPA appears as a very
competitive strain characterization technique with respect to current available
methods.\par \medskip On the program side, a characterization technique cannot
exist without a dedicated software because the raw data is nearly unusable until
converted into quantified strain maps. Therefore, implement a software and make
it available to the research and industry community is mandatory in order
\wss{in order to can nearly always be replaced by to} \an{done} to
expect the strain characterization method to be recognized and
applied. Regarding the applicability of the technique, a wide range of user can
be expected (from an expert in the field to an analyst performing routine
electron microscopy characterization).

\wss{Use a width of 80 columns in your tex file with a hard return ending each
  line.}
\an{done}

\bibliography{biblio_pbl_stat}
\bibliographystyle{ieeetr}

\end{document}