text:
\startproduct analyser
\environment  reportlayout

%\startsetups local

\setupbodyfontenvironment[default]
  [em=italic]

\definefloat[rule][rules]
\setupfloat[rule]
  [location=left,
   default=force,
   leftmargin=2em,
   indentnext=auto]
\setupcaption[rule]
  [location=right,
   number=no,
   style=\ss]

\let\leadsto\implies
\define\SPL  {{\sc spl}}
\define\SSM  {{\sc ssm}}
\define\Stm  {{\math{\mathcal{S}}}}
\define\Exp  {{\math{\mathcal{E}}}}
\define\Op   {{\math{\mathcal{O}}}}
\define\Stms {{\math{\mathcal{S}^+}}}
\define\Exps {{\math{\mathcal{E}^+}}}

\definemathcommand[bigbowtie][limop]{\bowtie\:}

\define[1]\definelabel
  {\setvalue{#1}{\text{\ss\tf #1}}}
\definelabel{Int}
\definelabel{Bool}
\definelabel{Void}
\definelabel{PC}
\definelabel{SP}
\definelabel{MP}
\definelabel{RR}
\definelabel{GP}
\definelabel{ifLabel}
\definelabel{thenLabel}
\definelabel{elseLabel}
\definelabel{fiLabel}
\definelabel{whileLabel}
\definelabel{doLabel}
\definelabel{odLabel}

\define[2]\definekeyword
  {\setvalue{#1}{\text{\tt\bf #2}}}
\definekeyword{Return}{return}
\definekeyword{If}{if}
\definekeyword{Else}{else}
\definekeyword{While}{while}
\definekeyword{True}{True}
\definekeyword{False}{False}
\definekeyword{VOID}{Void}
\definekeyword{INT}{Int}
\definekeyword{BOOL}{Bool}
\definekeyword{Print}{print}
\definekeyword{IsEmpty}{isEmpty}
\definekeyword{Head}{head}
\definekeyword{Tail}{tail}
\definekeyword{Fst}{fst}
\definekeyword{Snd}{snd}
\definekeyword{Main}{main}

\define[2]\defineoperator
  {\setvalue{#1}{\text{\tt\tf #2}}}
\defineoperator{Add}{+}
\defineoperator{Sub}{-}
\defineoperator{Mul}{*}
\defineoperator{Div}{/}
\defineoperator{Mod}{\%}
\defineoperator{Eq}{==}
\defineoperator{Ne}{!=}
\defineoperator{Lt}{<}
\defineoperator{Gt}{>}
\defineoperator{Le}{<=}
\defineoperator{Ge}{>=}
\defineoperator{And}{&&}
\defineoperator{Or}{||}
\defineoperator{Cons}{:}
\defineoperator{Not}{!}
\defineoperator{Neg}{-}

\define[1]\defineinstruction
  {\setvalue{#1}{\text{\tt\tf #1}}}
\defineinstruction{ADD}
\defineinstruction{SUB}
\defineinstruction{MUL}
\defineinstruction{DIV}
\defineinstruction{MOD}
\defineinstruction{NEG}
\defineinstruction{AND}
\defineinstruction{OR}
\defineinstruction{XOR}
\defineinstruction{NOT}
\defineinstruction{EQ}
\defineinstruction{NE}
\defineinstruction{GT}
\defineinstruction{LT}
\defineinstruction{GE}
\defineinstruction{LE}
\defineinstruction{LDC}
\defineinstruction{LDS}
\defineinstruction{LDL}
\defineinstruction{LDA}
\defineinstruction{LDR}
\defineinstruction{LDH}
\defineinstruction{STS}
\defineinstruction{STL}
\defineinstruction{STA}
\defineinstruction{STR}
\defineinstruction{STH}
\defineinstruction{LDMS}
\defineinstruction{LDML}
\defineinstruction{LDMA}
\defineinstruction{LDMH}
\defineinstruction{STMS}
\defineinstruction{STML}
\defineinstruction{STMA}
\defineinstruction{STMH}
\defineinstruction{BRA}
\defineinstruction{BRT}
\defineinstruction{BRF}
\defineinstruction{AJS}
\defineinstruction{NOP}
\defineinstruction{HALT}
\defineinstruction{TRAP}
\defineinstruction{JSR}
\defineinstruction{BSR}
\defineinstruction{RET}
\defineinstruction{ANNOTE}
\defineinstruction{LDAA}
\defineinstruction{LDRR}
\defineinstruction{LDLA}
\defineinstruction{LDSA}
\defineinstruction{LINK}
\defineinstruction{UNLINK}
\defineinstruction{SWP}
\defineinstruction{SWPR}
\defineinstruction{SWPRR}

\definetabulate[grammar][|lI|cM|lI|]
\define\TQ{\NC \to \NC}
\define\OQ{\NR\NC\NC \mid \NC}

\makecharacteractive @ %@
\def@#1@{{\tt\tf #1}}

\def\startderivationformula#1\NL#2\stopderivationformula
  {\starttabulate[|cM|]
   \NC #1 \NR
   \HL
   \NC #2 \NR
   \stoptabulate}
\def\startextendedderivationformula#1\NL#2\LR#3\stopextendedderivationformula
  {\starttabulate[|cM|]
   \NC #1 \NR
   \HL
   \NC #2 \NR
   \NC #3 \NR
   \stoptabulate}
%\starttexdefinition startderivationformula
%  \start
%    \define\NL{\NR\HL\NC}
%    \starttabulate[|cM|]
%      \NC
%\stoptexdefinition
%\starttexdefinition stopderivationformula
%      \NR
%    \stoptabulate
%  \stop
%\stoptexdefinition
%\define\startderivationformula
  %{\starttabulate[|cM|] \NC}
%\define\stopderivationformula
  %{\NR \stoptabulate}
%\define\NL
  %{\NR\HL\NC}

%\stopsetups
%\setups[local]

\startstandardmakeup
  \vfill
  {\bfa Compiler Constructon}
  \blank
  {\ss\bfd SPL, a Haskell implementation}
  \blank
  {\tfa Tim Steenvoorden (s0712663)}
  \blank
  {\tfa \date}
  \vfill
  \vfill
  \startlines
  Radboud University Nijmegen
  Faculty of Science
  Heyendaalseweg 135
  6525 AJ Nijmegen
  \stoplines
\stopstandardmakeup

\startfrontmatter

\completecontent[criterium=all]

\chapter[chp:intro]{Introduction}

This report describes the implementation of a compiler for the \emph{Simple Programming Language}. First, in \see[chp:language], we explain our choice for Haskell as an implementation language. The following sections describe each a particular phase of the compiler implementation. The first phase, parsing and lexing, is discussed \see[chp:parser], including our modifications to the grammar. The pretty printer is discussed in \see[chp:printer]. In \see[chp:analyser] we discus semantic analysis by defining scoping and typing rules. Also, we include some examples characterizing these rules. \see[chp:simplifier] shows which simplifications and transformations we perform on the program, to make compilation easier. The translation itself is discussed in \see[chp:translator]. We conclude in \see[chp:remarks] with an overview of the time investment and some remarks about working on the implementation.
\stopfrontmatter

\startbodymatter
\chapter[chp:language]{Language}

As an implementation language I chose Haskell, a pure functional programming language. Haskell is know for its rigid type system, its strong functional programming paradigm and its large community. There are also many great libraries which can be installed through the Cabal package manager. Most importantly, because of its large community there is a lot of documentation on the internet.

Besides these language based arguments, there are some personal aspects I took into account. I wanted to push my functional programming skills to a higher level using functors, applicative functors, monads and monad transformers. It is a real challenge learning, understanding and using these constructs in a real world application!

\chapter[chp:parser]{Lexing and Parsing}

\section{Grammar}

The grammar used to define \SPL\ is shown in \see[tab:grammar].
Apart from some name changes, there are some other small differences from the original grammar. First, we make no distinction between return \emph{Type}s and other \emph{Type}s. Second, this grammar allows new \emph{Declaration}s as well as \emph{Definition}s inside a function definition. Third, we make a new rule for \emph{Block}s. These \emph{Block}s are multiple \emph{Statement}s between braces or just a single \emph{Statement}. We use these \emph{Block}s in \If\ and \While\ statements. As a consequence extra braces inside a block or function definition are \emph{not} allowed.

\placetable[][tab:grammar]
  {The grammar specifying this version of \SPL. Non-terminals are in {\it italics}, terminals in {\tt teletype}. \*, \+ and \? are used respectively to denote zero or more, one or more or possible occurrence of objects.}
  \startgrammar
  \NC Program     \TQ Construct\+ \NR
  \NC Construct   \TQ Declaration
                \OQ Definition \NR
  \NC Declaration \TQ Type Name @=@ Expression @;@ \NR
  \NC Definition  \TQ Type Name @(@ Parameters\? @)@
    @\{@ Declaration\* Statement\+ @\}@ \NR
  \NC Type        \TQ \VOID\ \| \INT\ \| \BOOL\
                \OQ @(@ Type @,@ Type @)@
                \OQ @[@ Type @]@
                \OQ Name \NR
  \NC Parameters  \TQ Type Name (@,@ Parameters)\? \NR
  \NC Arguments   \TQ Expression (@,@ Arguments)\? \NR
  \NC Block       \TQ @\{@ Statement\* @\}@
                \OQ Statement \NR
  \NC Statement   \TQ \If\ @(@ Expression @)@ Block (\Else\ Block)\?
                \OQ \While\ @(@ Expression @)@ Block
                \OQ \Return\ Expression\? @;@
                \OQ Name @=@ Expression @;@
                \OQ Call @;@ \NR
  \NC Call        \TQ Name @(@ Arguments\? @)@ \NR
  \NC Expression  \TQ \True\ \| \False\ \| Decimal \| @[]@ \| @(@ Expression @,@ Expression @)@
                \OQ Name \| Call
                \OQ Expression Binary Expression \| Unary Expression
                \OQ @(@ Expression @)@ \NR
  \NC Binary      \TQ \Add\ \| \Sub\ \| \Mul\ \| \Div\ \| \Mod\
                \OQ \Eq\ \| \Ne\ \| \Lt\ \| \Gt\ \| \Le\ \| \Ge\
                \OQ \And\ \| \Or\ \| \Cons\ \NR
  \NC Unary       \TQ \Not\ \| \Neg\ \NR
  \stopgrammar

\section{Lexemes}

Lexemes consist of braces, brackets and parentheses, punctuation symbols and the equality symbol. Besides that we have operators, keywords and built in names. All are listed in \see[tab:lexemes]

Spaces, tabs, newlines et cetera are ignored. So are single line comments, starting with @//@ and multi line comments between @/*@ and @*/@. Multi line comments \emph{can} be nested.

\placetable[][tab:lexemes]
  {Lexemes used in the lexing phase of the compiler for \SPL.}
  \starttabulate[|l|lT|]
  \NC braces        \NC \{ \} \NR
  \NC brackets      \NC [ ] \NR
  \NC parentheses   \NC ( ) \NR
  \NC interpunction \NC , ; \NR
  \NC equal         \NC = \NR
  \NC comments      \NC // /* */ \NR
  \NC operators     \NC + - * / \% == != < > <= >= && || ! : \NR
  \NC keywords      \NC if else while return True False Void Int Bool \NR
  \NC builtins      \NC print isEmpty head tail fst snd main \NR
  \stoptabulate

Names of other variables and functions are lexed as shown in \see[tab:lexers]. We also give the definition of \emph{Decimal} numbers. The minus sign is \emph{not} lexed together with a \emph{Decimal} lexime but as a separate \emph{Unary} operator.

\placetable[][tab:lexers]
  {Lexemes used for \emph{Decimals} and \emph{Names}.}
  \startgrammar
  \NC Decimal \TQ Number\+ \NR
  \NC Name    \TQ Letter (Letter \| Decimal \| @_@)\* \NR
  \NC Letter  \TQ @a@ \| \ldots\ \| @z@ \| @A@ \| \ldots\ \| @Z@ \NR
  \NC Number  \TQ @0@ \| \ldots\ \| @9@ \NR
  \stopgrammar

%%% The grammar used to parse \SPL, if it is different from the given grammar. If you used any supporting libraries explain what their role in your parser is.
%%% => Grammar reflected by ast
%%% => Parsec for all the work

Source file: @Language/SPL/Lexer.hs@.

\section{Implementation}

The parser is written using Parsec, a Haskell parser combinator library originally developed by Daan Leijen \cite[leijen2001parsec]. All work is done chaining Parsec parsers in a Applicative or Monadic way. Parsec also enables us to use \emph{expression tables}: a way to express prefix and infix operators, denoting their fixity and precedence. Therefore we do not have to modify the grammar to express operator precedence.

The abstract syntax tree is an almost one-to-one translation of the grammar found in \see[tab:grammar].

Source files: @Language/SPL/Parser.hs@, @Language/SPL/Expression.hs@,\crlf @Language/SPL/Program.hs@.

\chapter[chp:printer]{Pretty Printing}

The pretty printer is implemented using the \emph{ansi-wl-pprint} \cite[leijen2001pprint] package from Cabal. This is a modified version of Philip Wadler's \emph{A prettier printer} \cite[wadler2003prettier] making use of colored terminal output. There is also a version available which makes use of the @Text@ data type. This could be used in the future for better performance.

Source file: @Language/SPL/Printer.hs@.

\chapter[chp:analyser]{Analysing}

\section{Scope}

Scoping is defined in four levels:

\startitemize
\head Built in

Contains all predefined functions. These are \Print, \IsEmpty, \Head, \Tail, \Fst\ and \Snd.

\head Global

Contains functions and variables defined and declared at the top level of the file.

\head Parameter

Contains only variables declared as a parameter list when defining a function.

\head Local

Contains only variables declared at the start of the function body.
\stopitemize

All bindings are contained in an \emph{environment}: a map from names to variable and function information.
To lookup names in function bodies will first look at the local declarations, then at the function parameters, then at the global declarations and at last at the built in definitions.

Source file: @Language/SPL/Environment.hs@.

\section{Types}

In this section we discuss several type check rules for \SPL. Each rule uses an \emph{environment} $\Gamma : X \to \Sigma$, a map from variables $X$ to types $\Sigma$. The environment is constructed by following the scoping rules given above. Typing statements are given by $\Gamma \vdash x:\sigma$, which should be read as \emph{$x$ has type $\sigma$ is derived from $\Gamma$}. Basic types are \Bool, \Int, $[\sigma]$ (list of $\sigma$) and $(\sigma,\tau)$ (pair of $\sigma$ and $\tau$). The types of other language constructs are derived by the rules given in this section.

\subsubject{Expressions}

We start with the rules for the four basic types:

\startsidebysidetext
\placerule{boolean}
  \startderivationformula
  b \in \booleans
  \NL
  \gamma \vdash b:\BOOL
  \stopderivationformula

\placerule{integer}
  \startderivationformula
  i \in \integers
  \NL
  \Gamma \vdash i:\Int
  \stopderivationformula

\nextsidebysidetext

\placerule{list}
  \startderivationformula
  \NL
  \Gamma \vdash []:[\sigma]
  \stopderivationformula

\placerule{pair}
  \startderivationformula
  \Gamma \vdash e_1:\sigma \qquad \Gamma \vdash e_2:\tau
  \NL
  \Gamma \vdash (e_1,e_2) : (\sigma,\tau)
  \stopderivationformula
\stopsidebysidetext

Here $\integers$ is the set containing all the integers and $\booleans$ is the set defined as
\startformula
\booleans := \{\True,\False\}
\stopformula

Types of values are looked up in the environment $\Gamma$:

\placerule{value}
  \startderivationformula
  x:\sigma \in \Gamma
  \NL
  \Gamma \vdash x:\sigma
  \stopderivationformula

Infix operators of different types have their own derivation rules:

\startsidebysidetext
\placerule{relational}
  \startextendedderivationformula
  \Gamma \vdash e_1:\Int \qquad \Gamma \vdash e_2:\Int
  \NL
  \Gamma \vdash (e_1 \boxminus e_2):\Bool
  \LR
  \where\ \boxminus \in \{\Eq,\Ne,\Lt,\Gt,\Le,\Ge\}
  \stopextendedderivationformula

\placerule{numerical}
  \startextendedderivationformula
  \Gamma \vdash e_1:\Int \qquad \Gamma \vdash e_2:\Int
  \NL
  \Gamma \vdash (e_1 \boxplus e_2):\Int
  \LR
  \where\ \boxplus \in \{\Add,\Sub,\Mul,\Div,\Mod\}
  \stopextendedderivationformula

\nextsidebysidetext

\placerule{logical}
  \startextendedderivationformula
  \Gamma \vdash e_1:\Bool \qquad \Gamma \vdash e_2:\Bool
  \NL
  \Gamma \vdash (e_1 \boxtimes e_2):\Bool
  \LR
  \where\ \boxtimes \in \{\And, \Or\}
  \stopextendedderivationformula

\placerule{constructional}
  \startderivationformula
  \Gamma \vdash e_1:[\sigma] \qquad \Gamma \vdash e_2:[\sigma]
  \NL
  \Gamma \vdash (e_1 \Cons e_2):[\sigma]
  \stopderivationformula
\stopsidebysidetext

Prefix operators are defined in the same way:

\startsidebysidetext
\placerule{not}
  \startderivationformula
  \Gamma \vdash e:\Bool
  \NL
  \Gamma \vdash\, (\Not e):\Bool
  \stopderivationformula

\nextsidebysidetext

\placerule{negate}
  \startderivationformula
  \Gamma \vdash e:\Int
  \NL
  \Gamma \vdash (\Neg e):\Int
  \stopderivationformula
\stopsidebysidetext

A function call is like a generalized operator:

\placerule{call}
  \startderivationformula
  \Gamma \vdash f:\rho \qquad \Gamma \vdash e_i:\sigma_i \land p_i:\sigma_i \quad \forall i\in\underline{n}
  \NL
  \Gamma \vdash f(e_1:\sigma_1, e_2:\sigma_2, \ldots, e_n:\sigma_n):\rho
  \stopderivationformula

\subsubject{Statements}

Statements in \SPL\ do not have types. We make an exception to certain statements, because we want to check the return type of a function matches the type of the expressions it returns. For functions which do not return a value, we use the extra type \Void.

\startsidebysidetext
\placerule{void}
  \startderivationformula
  \NL
  \Gamma \vdash \Return:\Void
  \stopderivationformula

\nextsidebysidetext

\placerule{return}
  \startderivationformula
  \Gamma \vdash e:\sigma
  \NL
  \Gamma \vdash \Return\ e:\sigma
  \stopderivationformula
\stopsidebysidetext

Blocks of \If\ and \While\ statements can also contain a \Return, so we have to match the statements inside the containing blocks as well:

\startsidebysidetext
\placerule{if}
  \startderivationformula
  \Gamma \vdash s_t:\sigma \qquad \Gamma \vdash s_f:\sigma
  \NL
  \Gamma \vdash \If\ e\ s_t\ s_f:\sigma
  \stopderivationformula

\nextsidebysidetext

\placerule{while}
  \startderivationformula
  \Gamma \vdash s:\sigma
  \NL
  \Gamma \vdash \While\ c\ s:\sigma
  \stopderivationformula
\stopsidebysidetext

Types are not assigned to other statements.

\subsubject{Built-in functions}

Built in functions have the following types:

\startsidebysidetext
\placerule{print}
  \startderivationformula
  \Gamma \vdash e:\sigma
  \NL
  \Gamma \vdash \Print(e):\Void
  \stopderivationformula

\placerule{head}
  \startderivationformula
  \Gamma \vdash e:[\sigma]
  \NL
  \Gamma \vdash \Head(e):\sigma
  \stopderivationformula

\placerule{fst}
  \startderivationformula
  \Gamma \vdash e:(\sigma,\tau)
  \NL
  \Gamma \vdash \Fst(e):\sigma
  \stopderivationformula

\placerule{main}
  \startderivationformula
  \NL
  \Gamma \vdash \Main():\Void
  \stopderivationformula

\nextsidebysidetext

\placerule{isempty}
  \startderivationformula
  \Gamma \vdash e:[\sigma]
  \NL
  \Gamma \vdash \IsEmpty(e):\Bool
  \stopderivationformula

\placerule{tail}
  \startderivationformula
  \Gamma \vdash e:[\sigma]
  \NL
  \Gamma \vdash \Tail(e):[\sigma]
  \stopderivationformula

\placerule{snd}
  \startderivationformula
  \Gamma \vdash e:(\sigma,\tau)
  \NL
  \Gamma \vdash \Fst(e):\tau
  \stopderivationformula
\stopsidebysidetext

\section{Examples}

\subsubject{Pass}

\typeSPLfile{Examples/Analyser/globals.spl}
\typeSPLfile{Examples/Analyser/order.spl}
\typeSPLfile{Examples/Analyser/infinite.spl}
\typeSPLfile{Examples/Library/lists.spl}

\subsubject{Fail}

\typeSPLfile{Examples/Analyser/arguments.spl}
\typeSPLfile{Examples/Analyser/return.spl}
\typeSPLfile{Examples/Analyser/call.spl}
\typeSPLfile{Examples/Analyser/duplicates.spl}
\typeSPLfile{Examples/Analyser/undeclared.spl}
\typeSPLfile{Examples/Analyser/unmatched.spl}

\section{Implementation}

The analyser is implemented by stacking the @Reader@ and @Writer@ monads on top of each other. @Reader@ is used to pass around the environment implicitly and @Writer@ to collect the errors produced during the analyser phase.

Source files: @Language/SPL/Error.hs@, @Language/SPL/Analyser.hs@.

\chapter[chp:simplifier]{Simplifying}

We do not use a special intermediate representation. The \SPL\ language has a clear separation between statements and expressions and is simple enough to serve this purpose. Nevertheless, we need to simplify our original program a bit to make generation of instructions easier.

First of all we transform all declarations to ordinary assignments, so that a canonical \SPL\ function starts with the initialization of its local variables. All global variables have to be initialized too. Therefore we add the corresponding assignments to the \Main\ function. Second, we have to make sure expressions do not have side effects. The only way side effects can occur is by a function call inside an expressions. Thus we need to extract function calls, assign the result to a temporary variable and refer to this variable in the original expression.

\section{Rules}

In the next paragraphs we give the simplification rules for \SPL. As with the typing rules in \see[chp:types], they consist of a premise and a result. There are four types of simplifications: for a statement ($\Stm$), for an expression ($\Exp$) and for sequences of statements ($\Stms$) or expressions ($\Exps$). These simplifications are denoted by a double arrow $\leadsto_x$ where the subscript $x$ is used to discriminate between the four types.

\reference[txt:sequences]
In the rules we use the notion of \emph{sequences}. A sequence is an ordered list of elements between angle brackets. The sequence of the numbers one till five is given by $\<1,2,3,4,5\>$. We can perform three different operations on sequences: append an element to the left (\emph{cons}), append an element to the right (\emph{snoc}) and \emph{concatenate} two sequences. These operations are performed by the operators $\triangleleft$, $\triangleright$ and $\bowtie$. Thus the result of $\<1,2\> \triangleright 3$ is the sequence $\<1,2,3\>$.

\subsubject{Statements}

The simplification of a statement can return multiple statements. Thus $\leadsto_\Stm$ has the following type:

\placeformula[for:simplify_stm]
  \startformula
  \leadsto_\Stm : Statement \to \<Statement\>
  \stopformula

\placerule{Assign}
  \startderivationformula
  e \leadsto_\Exp (\< s_1, \dots, s_n \>, e')
  \NL
  x = e \leadsto_\Stm \< s1, \dots, s_n \> \triangleright n = e'
  \stopderivationformula

\placerule{If}
  \startderivationformula
  e \leadsto_\Exp (\< s_1, \dots, s_n \>, e') \qquad
  s_t \leadsto_\Stms s_t' \qquad
  s_f \leadsto_\Stms s_f'
  \NL
  \If\ e\ s_t\ s_f \leadsto_\Stm \< s_1, \dots, s_n \>
                             \triangleright \If\ e'\ s_t'\ s_f'
  \stopderivationformula

\placerule{While}
  \startderivationformula
  e \leadsto_\Exp (\< s_1, \dots, s_n \>, e') \qquad
  s \leadsto_\Stms s'
  \NL
  \While\ e\ s \leadsto_\Stm \< s_1, \dots, s_2 \>
                            \triangleright \While\ e'\ s'
  \stopderivationformula

\placerule{ReturnNothing}
  \startderivationformula
  \NL
  \Return \leadsto_\Stm \Return
  \stopderivationformula

\placerule{ReturnJust}
  \startderivationformula
  e \leadsto_\Exp (\< s_1, \dots, s_n \>, e')
  \NL
  \Return\ e \leadsto_\Stm \< s_1, \dots, s_n \> \triangleright \Return\ e'
  \stopderivationformula

\placerule{Execute}
  \startderivationformula
  \<e_1,\dots,e_n\> \leadsto_\Exps (\<s_1',\dots,s_n'\>, \<e_1',\dots,e_n'\>)
  \NL
  f(e_1,\dots,e_n) \leadsto_\Stm \< s_1, \dots, s_n \>
                     \triangleright f(e_1',\dots,e_n')
  \stopderivationformula

\subsubject{Expressions}

The simplification of an expressions pulls side effects and pushes them to new statements. Next to a new expression, the simplification also needs to return these statments:

\placeformula[for:simplify_exp]
  \startformula
  \leadsto_\Exp : Expression \to (\<Statement\>, Expression)
  \stopformula

\startsidebysidetext

\placerule{Value}
  \startderivationformula
  x \in \identifiers
  \NL
  x \leadsto_\Exp (\<\>, x)
  \stopderivationformula

\placerule{Integer}
  \startderivationformula
  i \in \integers
  \NL
  i \leadsto_\Exp (\<\>, i)
  \stopderivationformula

\nextsidebysidetext

\placerule{Boolean}
  \startderivationformula
  b \in \booleans
  \NL
  b \leadsto_\Exp (\<\>, b)
  \stopderivationformula

\placerule{List}
  \startderivationformula
  \NL
  [] \leadsto_\Exp (\<\>, [])
  \stopderivationformula

\stopsidebysidetext

\placerule{Pair}
  \startderivationformula
  \<e_1,e_2\> \leadsto_\Exps (\<s_1,\dots,s_m\>, \<e_1',e_2'\>)
  \NL
  (e_1,e_2) \leadsto_\Exp (\<s_1,\dots,s_m\>, (e_1,e_2))
  \stopderivationformula

\placerule{Infix}
  \startextendedderivationformula
  \<e_1,e_2\> \leadsto_\Exps (\<s_1,\dots,s_m\>, \<e_1',e_2'\>)
  \NL
  e_1 \boxdot e_2 \leadsto_\Exp (\<s_1,\dots,s_m\>, e_1 \boxdot e_2)
  \LR
  \where\ \boxdot \in \{\Add,\Sub,\Mul,\Div,\Mod,
                \Eq,\Ne,\Lt,\Gt,\Le,\Ge,
                \And,\Or,\Cons\}
  \stopextendedderivationformula

\placerule{Prefix}
  \startextendedderivationformula
  e \leadsto_\Exp (\<s_1,\dots,s_m\>, e')
  \NL
  \diamond e \leadsto_\Exp (\<s_1,\dots,s_m\>, \diamond e')
  \LR
  \where\ \diamond \in \{\Not,\Neg\}
  \stopextendedderivationformula

\placerule{Call}
  \startextendedderivationformula
  \<e_1,\dots,e_n\> \leadsto_\Exps (\<s_1,\dots,s_m\>, \<e_1',\dots,e_n'\>)
  \NL
  f(e_1,\dots,e_n) \leadsto_\Stm
  (\<s_1,\dots,s_m\> \triangleright x_t = f(e_1',\dots,e_n'), x_t)
  \LR
  \where\ x_t \text{ is a fresh variable}
  \stopextendedderivationformula

\subsubject{Multiple statements and expressions}

Multiple statements or expressions are denoted as sequences. Simplification have the trivial types:

\placeformula[for:simplify_stms]
  \startformula
  \leadsto_\Stms : \<Statement\> \to \<Statement\>
  \stopformula

\placeformula[for:simplify_exps]
  \startformula
  \leadsto_\Exps : \<Expression\> \to (\<Statement\>, \<Expression\>)
  \stopformula

Simplifying a sequence of statements is just simplifying each statement and concatenating the result:

\placerule[][rul:stms]{Statements}
  \startderivationformula
  s_1 \leadsto_\Stm \<s^{(1)}_1,\dots,s^{(1)}_{m_1}\> \qquad \dots \qquad
  s_n \leadsto_\Stm \<s^{(n)}_1,\dots,s^{(n)}_{m_n}\> \qquad
  \NL
  \<s_1,\dots,s_n\> \leadsto_\Stms \bigbowtie_{i=1}^n \<s^{(i)}_1,\dots,s^{(i)}_{m_i}\>
  \stopderivationformula

To simplify a sequence of expressions we some extra machinery. Lets simplify one expression, this leads to statements $\<s_1,\dots,s_n\>$ and a new expression $e_1$. Simplifying another expression leads to $\<s_1',\dots,s_m'\>$ and $e_2$. We can only pull $e_1$ over the statements $\<s_1',\dots,s_m'\>$ iff the statements do not interfere with the result of expression $e_1$: they have to \emph{commute}. Otherwise we need to introduce a new temporary variable, assign the result of $e_1$ to it and pull \emph{this variable} over $\<s_1',\dots,s_m'\>$. This is formalized in \see[for:add].

\placeformula[for:add]
  \startformula
    \startmultiline
      \big(\<s_1,\dots,s_n\>, e\big) \oplus \big(\<s_1',\dots,s_m'\>, \<e_1',\dots,e_k'\>\big) \SR
      = \startcases
        \NC \big(\<s_1,\dots,s_n\> \bowtie \<s_1',\dots,s_m'\> \NC\NR
        \NC ,e \triangleleft \<e_1',\dots,e_k'\>\big)
        \NC if $e \leftrightarrow \<s_1',\dots,s_m'\>$
        \NR
        \NC \big(\<s_1,\dots,s_n\> \bowtie x_t = e \triangleleft \<s_1',\dots,s_m'\> \NC\NR
        \NC ,x_t \triangleleft \<e_1',\dots,e_k'\>\big)
        \NC otherwise
        \NR
        \stopcases \SR
      \where\ x_t \text{ is a fresh variable}
    \stopmultiline
  \stopformula

An expression $e$ commutes with a sequence of statements iff it commutes with each single statement. Commutation with a statement $s$ (notation $e \leftrightarrow s$) is not possible if $e$ is a function call, because of possible side effects. Container expressions commute with a statement if the containing expressions commute with a statement. Values and literals trivially commute.

Now we can give the simplification rule for a sequence of expressions:

\placerule[][rul:exps]{Expressions}
  \startderivationformula
  e_1 \leadsto_\Exp (\<s^{(1)}_1,\dots,s^{(1)}_{m_1}\>, e_1') \qquad \dots \qquad
  e_n \leadsto_\Exp (\<s^{(n)}_1,\dots,s^{(n)}_{m_n}\>, e_n')
  \NL
  \<e_1,\dots,e_n\> \leadsto_\Exps
  \bigoplus_{i=1}^n \big(\<s^{(i)}_1,\dots,s^{(i)}_{m_i}\>, e_i'\big)
  \stopderivationformula

\section{Implementation}

The implementation in Haskell as almost a straight translation of the math above. Concatenation and addition in the rule \about[rul:stms] and \about[rul:exps] are represented as folds. Fresh variables are supplied by the \type{Supply} monad.\footnote{Yes, another one!}

Source file: \type{Language/SPL/Simplifier.hs}

\chapter[chp:translator]{Translating}

This chapter describes the translation from a canonical \SPL\ program to instructions supported by the \SSM.

\emph{This is not yet fully worked out and implemented!}

\section{Rules}

\subsubject{Statements}

A statement is translated with the function $\Stm\[\]$. It takes a statement and produces a sequence of instructions. (See \at{Page}[txt:sequences] for an explenation about sequences.)

\startformula
\Stm\[\] : Statement \to \<Instruction\>
\stopformula

Generated instructions are each shown on a new line. Concatenating these lines gives us the desired instructions.
Labels are off course freshly generated.

\startformula
\Stm\[x = e\] = \startcases
  \NC \Exp\[e\] \NC\NR
  \NC \STL\ loc(x) \NC if $x$ is local \NR
  \NC\NC\NR
  \NC \Exp\[e\] \NC\NR
  \NC \LDR\ \GP \NC\NR
  \NC \STA\ loc(c) \NC if $x$ is global \NR
  \stopcases
\stopformula

\startformula\startsplit[n=3]
\Stm\[\If\ e\ s_t\ s_f\] = \SC
  \ifLabel:   \NC \Exp\[e\]        \SR
              \NC \BRF\ \elseLabel \SR
  \thenLabel: \NC \Stm\[s_t\]      \SR
              \NC \BRA\ \fiLabel   \SR
  \elseLabel: \NC \Stm\[s_f\]      \SR
  \fiLabel:   \NC \<\>
\stopsplit\stopformula

\startformula\startsplit[n=3]
\Stm\[\While\ e\ s\] = \SC
  \whileLabel: \NC \Exp\[e\]         \SR
               \NC \BRF\ \odLabel    \SR
  \doLabel:    \NC \Stm\[s\]         \SR
               \NC \BRA\ \whileLabel \SR
  \odLabel:    \NC \<\>
\stopsplit\stopformula

\startformula
\Stm\[\Return\] = \RET
\stopformula

\startformula\startsplit
\Stm\[\Return\ e\] = \SC
  \Exp\[e\] \SR
  \RET
\stopsplit\stopformula

\startformula\startsplit
\Stm\[f(e_1,\dots,e_n)\] = \SC
  \Exp\[e_n\] \SR
  \vdots \SR
  \Exp\[e_1\] \SR
  \JSR
\stopsplit\stopformula

\subsubject{Expressions}

\startformula
\Exp\[\] : Expression \to \<Instruction\>
\stopformula

\startformula
\Exp\[x\] = \startcases
  \NC \LDL\ loc(x) \NC if $x$ is local \NR
  \NC\NC\NR
  \NC \LDR\ \GP \NC\NR
  \NC \LDA\ loc(x)\> \NC if $x$ is global \NR
  \stopcases
\stopformula

\startformula
\Exp\[i\] = \LDC\ i
\stopformula

\startformula
\Exp\[\True\] = \LDC\ 1
\stopformula

\startformula
\Exp\[\False\] = \LDC\ -1
\stopformula

\startformula\startsplit
\Exp\[(e_1,e_2)\] = \SC
  \Exp\[e_1\] \SR
  \Exp\[e_2\] \SR
  \STMH\ 2
\stopsplit\stopformula

\startformula
\Exp\[[]\] = \dots
\stopformula

\startformula\startsplit
\Exp\[e_1 \boxdot e_2\] = \SC
  \Exp\[e_1\] \SR
  \Exp\[e_2\] \SR
  \Op\[\boxdot\] \SR
  \where\ \boxdot \in \{\Add,\Sub,\Mul,\Div,\Mod,
                \Eq,\Ne,\Lt,\Gt,\Le,\Ge,
                \And,\Or,\Cons\}
\stopsplit\stopformula

\startformula\startsplit
\Exp\[\diamond e\] = \SC
  \Exp\[e\] \SR
  \Op\[\diamond\] \SR
  \where\ \diamond \in \{\Not,\Neg\}
\stopsplit\stopformula

\startformula\startsplit
\Exp\[f(e_1,\dots,e_n)\] = \SC
  \Exp\[e_n\] \SR
  \vdots \SR
  \Exp\[e_1\] \SR
  \JSR
\stopsplit\stopformula

\subsubject{Operators}

\startformula
\Op\[\] : Operator \to \<Instruction\>
\stopformula

Translation of operators is a trivial mapping from the \SPL\ operator to its corresponding \SSM\ instruction. For example: $\Op\[\Eq\] = \EQ$ and $\Op\[\Add\] = \ADD$. Only \Cons\ is different\dots

\subsubject{Functions}

\emph{Not yet implemented}

\section{Examples}

\emph{Have to be created and tested}

\section{Implementation}

Once again the implementation is almost a direct translation of the math given in this chapter. Labels are generated fresh by the \type{Supply} monad. Checking for local of global variables is done through asking the \type{Reader} monad. She reads from a \emph{display} which contains this information.

Source files: \type{Language/SPL/Translator.hs}, \type{Language/SPL/Instruction.hs},\crlf \type{Language/SPL/Display.hs}

\chapter[chp:remarks]{Remarks}

Apart from time reading books and documentation, \see[tab:time] contains some information about the time investment in each part of the compiler till now. \see[tab:loc] gives an overview of all source code files and their contents.

\placetable[][tab:time]
  {Time investment in working days for each part of the compiler.}
  \starttabulate[|l|l|]
  \FL
  \NC Part       \NC Time investment \NR
  \ML
  \NC Lexer      \NC 1 day           \NR
  \NC Parser     \NC 3 days          \NR
  \NC Printer    \NC \half\ day      \NR
  \NC Analyser   \NC 6 days          \NR
  \NC Simplifier \NC 2\half\ days    \NR
  \NC Translator \NC 3 days          \NR
  \LL
  \stoptabulate

\placetable[][tab:loc]
  {Lines of code for each part of the compiler}
  \starttabulate[|lT|r|r|r|]
  \FL
  \RC File                           \NC Blank    \NC Comment       \NC Code \NR
  \ML
  \NC Lexer.hs                       \NC    13    \NC       5       \NC   53 \NR
  \NC Parser.hs                      \NC    26    \NC      19       \NC  105 \NR
  \NC Printer.hs                     \NC     8    \NC       9       \NC   25 \NR
  \NC Analyser.hs                    \NC    36    \NC      70       \NC   96 \NR
  \NC Simplifier.hs                  \NC    28    \NC      12       \NC   81 \NR
  \NC Translator.hs                  \NC    18    \NC       8       \NC   90 \NR
  \NC Data/Position.hs               \NC     6    \NC       0       \NC   12 \NR
  \NC Data/Program.hs                \NC    32    \NC       3       \NC  142 \NR
  \NC Data/Error.hs                  \NC    13    \NC       3       \NC   62 \NR
  \NC Data/Environment.hs            \NC    18    \NC       0       \NC   59 \NR
  \NC Data/Display.hs                \NC    10    \NC       1       \NC   19 \NR
  \NC Data/Instruction.hs            \NC    15    \NC       2       \NC   57 \NR
  \ML
  \RC Total                          \NC   223    \NC     132       \NC  801 \NR
  \LL
  \stoptabulate

\stopbodymatter

\startbackmatter
\chapter{References}

\placepublications[criterium=all]
\stopbackmatter

\stopproduct

% vim: ft=context spell spl=en cole=1

max_stars_repo_name: timjs/spl-compiler

max_issues_repo_name: timjs/spl-compiler

max_forks_repo_name: timjs/spl-compiler


text:
\chapter{Source Code}
\label{sec:source}
\section{Implementation}
The \texttt{phduio} class is implemented in the following way:
\lstinputlisting[language = {[LaTeX]{TeX}}]{phduio.cls}

ext: tex

max_stars_repo_name: martinhelso/phduio-monograph

max_issues_repo_name: martinhelso/phduio-monograph

max_forks_repo_name: martinhelso/phduio-monograph


text:
    \filetitle{reshape}{Reshape size of time series in 2nd and higher dimensions}{tseries/reshape}

	\paragraph{Syntax}\label{syntax}

\begin{verbatim}
x = reshape(x,newsize)
\end{verbatim}

\paragraph{Input arguments}\label{input-arguments}

\begin{itemize}
\item
  \texttt{x} {[} tseries {]} - Tseries object whose data will be
  reshaped in 2nd and/or higher dimensions.
\item
  \texttt{newsize} {[} numeric {]} - New size of the tseries object
  data; the first dimension (time) must be preserved.
\end{itemize}

\paragraph{Output arguments}\label{output-arguments}

\begin{itemize}
\itemsep1pt\parskip0pt\parsep0pt
\item
  \texttt{x} {[} tseries {]} - Reshaped tseries object.
\end{itemize}

\paragraph{Description}\label{description}

\paragraph{Example}\label{example}

\}

max_stars_repo_name: OGResearch/IRIS-Toolbox-For-Octave

max_issues_repo_name: OGResearch/IRIS-Toolbox-For-Octave

max_forks_repo_name: OGResearch/IRIS-Toolbox-For-Octave


text:
\section{State file}
\label{sec:statefile}
All data structures are saved to the \sqlstate file in sqlite3 format, see http://www.sqlite.org/.
They are available in form of tables in the \sqlstate file as can be seen by the command\\
{\small \sqlite \sqlstate \texttt{" .tables "}}

An example of such a table are \sqlmolecules. The full table can be displayed using the command (similar for the other tables)\\
{\small \sqlite \sqlstate \texttt{" SELECT * FROM \sqlmolecules"}}\\
The meaning of all the entries in the table can be displayed by a command like\\
{\small \sqlite \sqlstate \texttt{" .SCHEMA \sqlmolecules"}}\\
The first and second entry are  integers for internal and regular id of the molecule and the third entry is the name.
A single field from the table like the name of the molecule can be displayed by a command like\\
{\small \sqlite \sqlstate \texttt{" SELECT name FROM \sqlmolecules"}}\\
Besides \sqlmolecules, the following tables are stored in the \sqlstate:

\sqlconjsegproperties:\\
Conjugated segments are stored with id, name and x,y,z coordinates of the center of mass in nm.

\sqlconjsegs:\\
Reorganization energies for charging or discharging a conjugated segment are stored together with the coulomb energy and any other user defined energy contribution (in eV) and occupation probabilities.

\sqlpairs:\\
The pairs from the neighborlist are stored with the pair id, the id of the first and second segment, the rate from the first to the second , the rate from the second to the first (both in s$^-1$)  and the x,y,z coordinates in nm of the distance between the first and the second segment.

\sqlpairintegrals:\\
Transfer integrals for all pairs are stored in the following way:  The pair id , the number for counting possible different electronic overlaps (e.g if only the frontier orbitals are taken into account this is always zero, while an effective value is stored in addition to the different overlaps of e.g. HOMO-1 and HOMO-1 if more frontier orbitals are taken into account) and the integral in eV.

\sqlpairproperties:\\
The outer sphere reorganization energy of all pairs is stored by an id, the pair id, a string \texttt{lambda\_outer} and the energy in eV.

\sqlconjsegs:\\
Conjugated segments are saved in the following way: The id, the name, the type, the molecule id, the time frame, the x,y,z coordinates in nm and the occupation probability.

\sqlconjsegproperties:\\
Properties of the conjugated segments like reorganization energies for charging or discharging a charge unit or the coulomb contribution to the site energy are stored by: id, conjugated segment id, a string like \texttt{lambda\_intra\_charging}, \texttt{lambda\_intra\_discharging} or \texttt{energy\_coulomb} and a corresponding value in eV.

The tables \sqlrigidfragproperties, \sqlrigidfrags and \sqlframes offer information about rigid fragments and time frames including periodic boundary conditions.

The data in the \sqlstate file can also be modified by the user. Here is an example how to modify the transfer integral between the conjugated segments number one and two assuming that they are in the neighborlist.
Their pair id can be found by the command \\
{\small \texttt{pair\_ID=`}\sqlite \sqlstate \texttt{"SELECT \_id FROM pairs WHERE conjseg1=1 AND conjseg2=2"`}} \\
The old value of the transfer integral can be deleted using\\
{\small \sqlite \sqlstate \texttt{"DELETE FROM pair\_integrals WHERE pair=\$pair\_ID"}}\\
Finally the new transfer integral $J$ can be written to the \sqlstate file by the command\\
{\small \sqlite \sqlstate \texttt{"INSERT INTO pair\_integrals (pair,num,J) VALUES (\$pair\_ID,0,\$J)"}}
Here the \texttt{num=0} indicates that only the effective transfer integrals is written to the file, while other values of \texttt{num}
would correspond to overlap between other orbitals than the frontier orbitals.

In a similar way the coulomb contribution to the site energy of the first conjugated segment can be overwritten by first getting its id\\
{\small \texttt{c\_ID=`}\sqlite \sqlstate \texttt{"SELECT \_id from conjseg\_properties}}
{\small \texttt{ where conjseg=1 AND key =$\backslash$"energy\_coulomb$\backslash$""}} \\
Then deleting the old value\\
{\small \sqlite \sqlstate \texttt{"DELETE FROM from conjseg\_properties WHERE \_id=\$c\_ID"}}\\
Then the new coulomb energy $E$ can be written to this id\\
{\small \sqlite \sqlstate \texttt{"INSERT INTO conjseg\_properties (\_id,conjseg,key,value)\\
VALUES (\$c\_ID,1,$\backslash$"energy\_coulomb$\backslash$",\$E)"}}\\
Finally the resulting coulomb contribution to all conjugated segments can be displayed by\\
{\small \sqlite \sqlstate \texttt{"SELECT * from conjseg\_properties WHERE key=$\backslash$"energy\_coulomb$\backslash$""}}

max_stars_repo_name: jimbach/ctp

max_issues_repo_name: choudarykvsp/xtp

max_forks_repo_name: choudarykvsp/xtp


text:
\documentclass[a4paper]{article}

\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage[colorinlistoftodos]{todonotes}

\title{Quantum Hall effect report template}

\author{Your names and group number}

\date{\today}

\begin{document}
\maketitle

\begin{abstract}
Enter a short summary here. What topic do you want to investigate and why? What experiment did you perform? What were your main results and conclusion?
\end{abstract}

\section{Introduction 5 lines to max 1/2 page}
\label{sec:introduction}

Explain the context of the experiment here. Why is condensed matter physics interesting or important?
Optional things you could talk about (but don't have to -- this is up to you): transistors, computers, Quantum computers, fundamental knowledge (e.g. the resistance quantum).

Briefly explain what methods you will use in the experiment, and what values you will extract from the data.

For this section and all following sections: If you refer to an equation, previous result or theory that is not regarded as common knowledge, then cite the source (article or book) where you found this. For example, you can cite the Nano 3 Lecture notes \cite{nano3}.

\section{Theory 2-3 pages}
\label{sec:theory}

\subsection{Two-dimensional Electron Gas}
Here, explain the concept of a 2-DEG in GaAs/AlGaAs. What is a 2-DEG and why does it arise?

\subsection{Hall Effect}
Explain the classical Hall effect in your own words. What do I measure at $B=0$? And what happens if $B>0$? Which effect gives rise to the voltage drop in the vertical direction?

\subsection{Quantum Hall Effect}
Explain the IQHE in your own words. What does the density of states look like in a 2-DEG when $B=0$? What are Landau levels and how do they arise? What are edge states? What does the electron transport look like when you change the magnetic field? What do you expect to measure?

\section{Experiment 1-2 pages}
\subsection{Fabrication}
Explain a step-by-step recipe for fabrication here. How long did you etch and why? What is an Ohmic contact?
\subsection{Experimental set-up}
Explain the experimental set-up here. Use a schematic picture (make it yourself in photoshop, paint, ...) to show how the components are connected. Briefly explain how a lock-in amplifier works.

\section{Results and interpretation 2-3 pages}
Show a graph of the longitudinal resistivity ($\rho_{xx}$) and Hall resistivity ($\rho_{xy}$) versus magnetic field, extracted from the raw data shown in figure \ref{fig:data}. You will have the link to the data in your absalon messages, if not e-mail Guen (guen@nbi.dk). Explain how you calculated these values, and refer to the theory.

\begin{figure}
\centering
\includegraphics[width=1\textwidth]{raw_data.png}
\caption{\label{fig:data}Raw (unprocessed) data. Replace this figure with the one you've made, that shows the resistivity.}
\end{figure}

\subsection{Classical regime}
Calculate the sheet electron density $n_{s}$ and electron mobility $\mu$ from the data in the low-field regime, and refer to the theory in section \ref{sec:theory}. Explain how you retrieved the values from the data (did you use a linear fit?).
Round values off to 1 or 2 significant digits: 8.1643 ~= 8.2. Also, 5e-6 is easier to read than 0.000005.

!OBS: This part is optional (only if you have time left).
Calculate the uncertainty as follows: \newline $u(f(x, y, z)) = \sqrt{(\frac{\delta f}{\delta{x}} u(x))^{2} + (\frac{\delta f}{\delta{y}} u(y))^{2} + (\frac{\delta f}{\delta{z}} u(z))^{2}}$, where $f$ is the calculated value ($n_{s}$ or $\mu$), $x, y, z$ are the variables taken from the measurement and $u(x)$ is the uncertainty in x (and so on).

\subsection{Quantum regime}
Calculate $n_{s}$ for the high-field regime.
Show a graph of the longitudinal conductivity ($\rho_{xx}$) and Hall conductivity($\rho_{xy}$) \textbf{in units of the resistance quantum} ($\frac{h}{e^{2}}$), depicting the integer filling factors for each plateau.
Show a graph of the plateau number versus its corresponding value of $1/B$. From this you can determine the slope, which you use to calculate the electron density.
Again, calculate the uncertainty for your obtained values.

\section{Discussion 1/2-1 page}
Discuss your results. Compare the two values of $n_{s}$ that you've found in the previous section. Compare your results with literature and comment on the difference. If you didn't know the value of the resistance quantum, would you be able to deduce it from your measurements? If yes/no, why?

\newpage
\section{Some LaTeX tips}
\label{sec:latex}
\subsection{How to Include Figures}

First you have to upload the image file (JPEG, PNG or PDF) from your computer to writeLaTeX using the upload link the project menu. Then use the includegraphics command to include it in your document. Use the figure environment and the caption command to add a number and a caption to your figure. See the code for Figure \ref{fig:frog} in this section for an example.

\begin{figure}
\centering
\includegraphics[width=0.3\textwidth]{frog.jpg}
\caption{\label{fig:frog}This frog was uploaded to writeLaTeX via the project menu.}
\end{figure}

\subsection{How to Make Tables}

Use the table and tabular commands for basic tables --- see Table~\ref{tab:widgets}, for example.

\begin{table}
\centering
\begin{tabular}{l|r}
Item & Quantity \\\hline
Widgets & 42 \\
Gadgets & 13
\end{tabular}
\caption{\label{tab:widgets}An example table.}
\end{table}

\subsection{How to Write Mathematics}

\LaTeX{} is great at typesetting mathematics. Let $X_1, X_2, \ldots, X_n$ be a sequence of independent and identically distributed random variables with $\text{E}[X_i] = \mu$ and $\text{Var}[X_i] = \sigma^2 < \infty$, and let

\begin{equation}
S_n = \frac{X_1 + X_2 + \cdots + X_n}{n}
      = \frac{1}{n}\sum_{i}^{n} X_i
\label{eq:sn}
\end{equation}

denote their mean. Then as $n$ approaches infinity, the random variables $\sqrt{n}(S_n - \mu)$ converge in distribution to a normal $\mathcal{N}(0, \sigma^2)$.

The equation \ref{eq:sn} is very nice.

\subsection{How to Make Sections and Subsections}

Use section and subsection commands to organize your document. \LaTeX{} handles all the formatting and numbering automatically. Use ref and label commands for cross-references.

\subsection{How to Make Lists}

You can make lists with automatic numbering \dots

\begin{enumerate}
\item Like this,
\item and like this.
\end{enumerate}
\dots or bullet points \dots
\begin{itemize}
\item Like this,
\item and like this.
\end{itemize}
\dots or with words and descriptions \dots
\begin{description}
\item[Word] Definition
\item[Concept] Explanation
\item[Idea] Text
\end{description}

We hope you find write\LaTeX\ useful, and please let us know if you have any feedback using the help menu above.

\begin{thebibliography}{9}
\bibitem{nano3}
  K. Grove-Rasmussen og Jesper Nygård,
  \emph{Kvantefænomener i Nanosystemer}.
  Niels Bohr Institute \& Nano-Science Center, Københavns Universitet

\end{thebibliography}
\end{document}

max_stars_repo_name: sanjit-bhat/AB-ACSL

max_issues_repo_name: sanjit-bhat/AB-ACSL

max_forks_repo_name: sanjit-bhat/AB-ACSL


text:
\chapter{Mt. Gagazet}
\begin{enumerate}
	\item Walk up, \cs[3:40], walk up, \sd
\end{enumerate}
\begin{battle}{Biran and Yenke}
	\begin{itemize}
		\kimahrif Steal from Biran
		\kimahrif Gem Yenke
		\kimahrif Gem Biran
	\end{itemize}
	Pay attention to your drops, they affect \yuna's sphere grid below.
\end{battle}
\begin{spheregrid}
	\begin{multicols}{2}
		\begin{itemize}
			\luluf
			\begin{itemize}
				\item Move $\uparrow\uparrow$
				\item Level 2 Key Sphere
				\item Move $\downarrow x9$
				\item Level 3 Key Sphere
				\item Move $\searrow\searrow$
			\end{itemize}
			\includegraphics[width=.8\columnwidth]{graphics/lulu_grid}
			\yunaf
			\begin{itemize}
				\item \textit{If you got \textbf{4 Return Spheres}:}
				      \begin{itemize}
					      \item Return to the last Str+2 node in \wakka's grid, Hold $\searrow$
					      \item Move $\leftarrow$
					      \item Mag+3, Level 1 Key Sphere
					      \item Move $\downarrow\downarrow$
					      \item Str+2, Agi+4
				      \end{itemize}
				      \includegraphics{graphics/4_returns_1}
				\item \textit{If you got \textbf{2 Return Spheres}:}
				      \begin{itemize}
					      \item Friend Sphere to \lulu,  $\downarrow\downarrow$
					      \item Str+4, Str+4
					            \luluf Move $\nearrow\uparrow\uparrow$
					            \yunaf Friend Sphere to \lulu,
					      \item Str+3, Agi+4, Agi+4
				      \end{itemize}
				      \includegraphics{graphics/2_and_2}
				      \columnbreak
				\item \textit{If you got \textbf{0 Return Spheres}:}
				      \begin{itemize}
					      \item \textit{If you \wonblitz:}
					            \begin{itemize}
						            \tidusf Move to Str+4 by Mental Break $\rightarrow x3, \downarrow, \rightarrow x3$
						            \yunaf Friend Sphere to \tidus
						            \item Str+4
						                  \tidusf Move $\nwarrow\leftarrow$ or $\swarrow\swarrow$
						            \item Armor Break
					            \end{itemize}
					      \item \textit{If you \lostblitz:}
					            \begin{itemize}
						            \tidusf Move to Armor Break $\rightarrow x3, \downarrow x6$
						            \tidusf Armor Break
						            \tidusf Move to HP $\searrow\searrow$
						            \yunaf Friend Sphere to \tidus
						            \item Str+4
					            \end{itemize}
					      \item Do the 2 Return Sphere Menu
					            \rikkuf: Move $\downarrow x5$
					            \yunaf Friend to \rikku\ $\downarrow$
					      \item Agi+4, MgDef +2 \textit{(Skip MgDef if \blitzloss)}
					      \item Move $\leftarrow$
					      \item Str+2
				      \end{itemize}
				      \includegraphics[width=.8\columnwidth]{graphics/post_BY_0_returns}
				      \includegraphics[width=.8\columnwidth]{graphics/0_returns_pt2}
			\end{itemize}
			\item \tidus\ \textit{if you didn't get Armor Break:}
			      \begin{itemize}
				      \item \textit{If you got \textbf{4 Return Spheres}:}
				            \begin{itemize}
					            \item Return Sphere $\downarrow\searrow\searrow$, Str+4 near Armor Break
					            \item Move $\nwarrow\leftarrow$ or $\swarrow\swarrow$
				            \end{itemize}
				      \item \textit{If you got \textbf{2 Return Spheres}:}
				            \begin{itemize}
					            \item Move to Armor Break $\rightarrow x3, \downarrow x6$
				            \end{itemize}
				      \item Armor Break
			      \end{itemize}

		\end{itemize}
	\end{multicols}
\end{spheregrid}
\begin{enumerate}[resume]
	\item \textit{If you had 2 or 4 \textbf{Return Spheres}:}
	      \begin{itemize}
		      \item Customize:
		            \begin{itemize}
			            \auronf Shimmering Blade $\rightarrow$ First Strike
			            \yunaf Staff $\rightarrow$ First Strike
		            \end{itemize}
	      \end{itemize}
	\item \formation{\tidus}{\rikku}{\auron} \textit{If you need need to build up \rikku\ \od\ else } \formation{\tidus}{\kimahri}{\wakka}.
\end{enumerate}

\begin{equip}
	\begin{itemize}
		\auronf Sonic Blade
	\end{itemize}
\end{equip}
\begin{enumerate}[resume]
	\item Walk up, \sd, \cs[1:20], continue walking up, avoid the gravestones.
	\item Make sure you charge \rikku's \od, can skip if you still have a Silence Grenade
	\item Follow the path around.
	\item Once you're on the Seymour Flux screen, if you're using \rikku\ \od, then Hi-Potion Rikku
	\item \formation{\tidus}{\yuna}{\auron} \textit{If you had 2 or 4 Return Spheres else } \formation{\tidus}{\kimahri}{\wakka}
\end{enumerate}
\begin{battle}[70000]{Seymour Flux}
	\begin{itemize}
		\item \textit{If you had 2 or 4 \textbf{Return Spheres}:}
		      \begin{itemize}
			      \yunaf Attack
			      \tidusf Haste \yuna
			      \switch{\auron}{\rikku}
			      \rikkuf Silence Grenade or \od\ HP Sphere + Grenade
			      \summon{\bahamut}
			      \bahamutf Impulse
			      \yunaf Attack
			      \tidusf Attack. If \yuna\ crit, skip the second Attack to try and get Overkill
		      \end{itemize}
		\item \textit{If you had 0 \textbf{Return Spheres}:}
		      \begin{itemize}
			      \switch{\tidus}{\yuna}
			      \summon{\bahamut}
			      \bahamutf Attack \textit{If \blitzwin Else} Impulse
		      \end{itemize}
	\end{itemize}
\end{battle}
\begin{enumerate}[resume]
	\item \formation{\tidus}{\kimahri}{\auron}
	\item \save\ if \bahamut was banished, Walk to the next screen. \skippablefmv[0:20], \sd, walk up to \tidus\ House, go into the center, \sd. Follow the boy outside, speak to him upstairs, \sd.
	\item Walk up to the next screen, go up the steps. Go down the left path into the water, \sd, swim up. Go up the steps, play the minigame, return to the previous screen.
	\item \tidus\ can attack Splashers for Power Spheres if needed. Try to only attack the 3 fish groups.
	\item Return to Save Sphere, go up and left, then go down the right path, swim up into the next screen. Complete the minigame, \rikku\ Green, \tidus\ Blue, \wakka\ Red. Return.
	\item Go up left path, \sd, continue up the path, \save\ if \bahamut\ was banished and you didn't touch one earlier.
	\item \formation{\tidus}{\yuna}{\kimahri}. Go onto the next screen.
\end{enumerate}
\begin{battle}[40000]{Sanctuary Keeper}
	\begin{itemize}
		\item \textit{If either (2 or 4 \textbf{Return Spheres}) or (0 \textbf{Returns Spheres} and \blitzloss):}
		      \begin{itemize}
			      \yunaf Defend
			      \tidusf Armor Break
		      \end{itemize}
		\item \textit{If 0 \textbf{Returns Spheres} and \blitzwin:}
		      \begin{itemize}
			      \tidusf Defend
		      \end{itemize}
		      \summon{\bahamut}
		      \bahamutf Attack
	\end{itemize}
\end{battle}
\newpage


text:
\chapter{Table of Orbit-length Partition for Small Degree Polynomials}
\label{chap:appD}
This table can be found in L. Soicher and J. McKay's \citep{soicher1985computing} articles.

\begin{table}[htbp]
\centering
\begin{tabular}{cccc}
\hline
$G$ & $x_1+x_2$ & $x_1+x_2+x_3$ & $x_1-x_2$\\
\hline
\textbf{Degree 3} &  &  &  \\
+$A_3$ &  & & $3^2$\\
$S_3$ &  & & 6\\

\textbf{Degree 4} &  &  &  \\
$Z_4$ & 2,4  & & $4^3$\\
+$V_4$ & $2^3$  & & $4^3$\\
$D_4$ & 2,4  & & 4,8\\
+$A_4$ &6  & & 12\\
$S_4$ &6  & & 12\\

\textbf{Degree 6} &  &  &  \\
$Z_6$ & 3,$6^2$  &2,$6^3$ & $6^5$\\
$S_3$ & $3^3$,6  &2,$6^3$ & $6^5$\\
$D_6$ & 3,$6^2$  &2,$6,12$ & 6,$12^2$\\
+$A_4$ &3,12  &$4^2,6^2$ & 6,$12^2$\\
$G_{18}$ &6,9  &2,18 & $6^2$,18\\
$G_{24}$ & 3,12 &$6^2$,8 &6,$12^2$\\
+$S_4/V_4$ & 3,12&$4^2$,12&6,24\\
$S_4/Z_4$ & 3,12 &8,12&6,24\\
$G_{36}^1$ & 6,9 &2,18&12,18\\
+$G_{36}^2$ & 6,9 &2,18&12,18\\
$G_{48}$& 3,12 &8,12 &6,24\\
+$\text{PSL}_2(5)$ & 15 & $10^2$ & 30\\
$G_{72}$ & 6,9 &2,18&12,18\\
$\text{PGL}_2(5)$ & 15&20&30\\
+$A_6$ & 15&20&30\\
$S_6$ & 15&20&30\\
\hline
\end{tabular}
\caption{Orbit-length Partition of Polynomial with Degree 3,4,6}
\label{tab:allorbits}
\end{table}

where ``+" means that the discriminants of the corresponding polynomial is square. Note that we need a non-linear resolvent to determine $PGL_2(5)$ and $S_6$ etc.

max_stars_repo_name: daidahao/sustcthesis

max_issues_repo_name: daidahao/sustcthesis

max_forks_repo_name: daidahao/sustcthesis


text:
\subsection{Stress Homogenization}

The homogenized Cauchy stress, $\langle\boldsymbol{\sigma}\rangle$, is derived from the definition of the spatial average of the microscale stress of the deformable blocks of the DEM simulation, $\boldsymbol{\sigma}^m$, over the homogenization domain $\Omega^{h}$.
\begin{equation}
\langle\boldsymbol{\sigma}\rangle=\frac{1}{A^{h}}\int_{\Omega^{h}}\boldsymbol{\sigma}^m dA\label{eqn:stress1}
\end{equation}

%As previously mentioned, there exists a necessary distinction between the block subdomain and the void subdomain when dealing with stress. Here, the integration over the homogenization domain can be decomposed into two seperate integrations over the block subdomain and the void subdomain:

%\begin{equation}
%\langle\boldsymbol{\sigma}\rangle=\frac{1}{A^{h}}\left[\int_{\Omega^{b}}\boldsymbol{\sigma}dA+\int_{\Omega^{v}}\boldsymbol{\sigma}dA\right]\label{eqn:stress2}
%\end{equation}

%This distinction is made due to the fact that in a purely mechanical model, there isn't any pressure or stress being retained in the void space, resulting in a negligable contribution to the overall stress state. This allows for the void subdomain integration term to be dropped from the formulation:

%\begin{equation}
%\langle\boldsymbol{\sigma}\rangle=\frac{1}{A^{h}}\int_{\Omega^{b}}\boldsymbol{\sigma}dA\label{eqn:stress2a}
%\end{equation}

When each deformable block is discretized by constant stress triangles (elements/zones), the integration of the stress over each deformable block subdomain can be written as a summation in the form of a spatially weighted average of the zone stresses. Let $\boldsymbol{\sigma}_{IJ}^{m}$ denote the stress in zone $J$ of deformable block $I$, $N_{I}^{z}$ denote the number of zones within block $I$, $A_{IJ}$ denote area of zone $J$ in block $I$, and $N^{b}$ denote the number of deformable blocks. The homogenized stress is then defined as

\begin{equation}
\langle\boldsymbol{\sigma}\rangle=\frac{1}{A^{h}}\sum_{I=1}^{N^{b}}\sum_{J=1}^{N_{I}^{z}}\boldsymbol{\sigma}_{IJ}^{m}A_{IJ}\label{eqn:stress4}
\end{equation}

In our implementation, (\ref{eqn:stress4}) is incorporated into the homogenization module.

max_stars_repo_name: yetisir/up-scaling-dem-simulations

max_issues_repo_name: yetisir/up-scaling-dem-simulations

max_forks_repo_name: yetisir/up-scaling-dem-simulations


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% writeLaTeX Example: A quick guide to LaTeX
%
% Source: Dave Richeson (divisbyzero.com), Dickinson College
%
% A one-size-fits-all LaTeX cheat sheet. Kept to two pages, so it
% can be printed (double-sided) on one piece of paper
%
% Feel free to distribute this example, but please keep the referral
% to divisbyzero.com
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% How to use writeLaTeX:
%
% You edit the source code here on the left, and the preview on the
% right shows you the result within a few seconds.
%
% Bookmark this page and share the URL with your co-authors. They can
% edit at the same time!
%
% You can upload figures, bibliographies, custom classes and
% styles using the files menu.
%
% If you're new to LaTeX, the wikibook is a great place to start:
% http://en.wikibooks.org/wiki/LaTeX
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\documentclass[10pt,landscape]{article}
\usepackage{amssymb,amsmath,amsthm,amsfonts}
\usepackage{multicol,multirow}
\usepackage{calc}
\usepackage{ifthen}
\usepackage[landscape]{geometry}
\usepackage[colorlinks=true,citecolor=blue,linkcolor=blue]{hyperref}
\usepackage{listings}
\usepackage{balance}

\ifthenelse{\lengthtest { \paperwidth = 11in}}
    { \geometry{top=.5in,left=.5in,right=.5in,bottom=.5in} }
	{\ifthenelse{ \lengthtest{ \paperwidth = 297mm}}
		{\geometry{top=1cm,left=1cm,right=1cm,bottom=1cm} }
		{\geometry{top=1cm,left=1cm,right=1cm,bottom=1cm} }
	}
\pagestyle{empty}
\makeatletter
\renewcommand{\section}{\@startsection{section}{1}{0mm}%
                                {-1ex plus -.5ex minus -.2ex}%
                                {0.5ex plus .2ex}%x
                                {\normalfont\large\bfseries}}
\renewcommand{\subsection}{\@startsection{subsection}{2}{0mm}%
                                {-1explus -.5ex minus -.2ex}%
                                {0.5ex plus .2ex}%
                                {\normalfont\normalsize\bfseries}}
\renewcommand{\subsubsection}{\@startsection{subsubsection}{3}{0mm}%
                                {-1ex plus -.5ex minus -.2ex}%
                                {1ex plus .2ex}%
                                {\normalfont\small\bfseries}}
\newcommand{\river}{RIVER}
\newcommand{\rr}{\raggedright}
\newcommand{\tn}{\tabularnewline}
\makeatother
\setcounter{secnumdepth}{0}
\setlength{\parindent}{0pt}
\setlength{\parskip}{0pt plus 0.5ex}
% -----------------------------------------------------------------------

\title{Quick Guide to LaTeX}

\begin{document}

\raggedright
\footnotesize

\begin{center}
	\Large{\textbf{{\river} Cheat Sheet}} \\
\end{center}
\begin{multicols*}{3}
\setlength{\premulticols}{1pt}
\setlength{\postmulticols}{1pt}
\setlength{\multicolsep}{1pt}
\setlength{\columnsep}{2pt}

\section{What is \river?}
	{\river} spelled backwards stands for \textbf{REV}ersible \textbf{I}ntermediate \textbf{R}epresentation. {\river} is a fixed length extended x86 instruction set. It is designed to be translated to and from x86. {\river} instrumentation helps tracing binaries (no need for program source code) and provides analysis information about each basic block that was executed by target program. Provided details are: module name, instruction pointer offset, execution cost, jump type, jump instruction and number of instructions.

\section{Constant Definitions}

	\subsection{{\river} Modifiers}

	\begin{tabular}{ p{6cm} p{1.3cm} }
		RIVER\_MODIFIER\_NOSEG & 0x00000000\\
		RIVER\_MODIFIER\_ESSEG & 0x00000001\\
		RIVER\_MODIFIER\_CSSEG & 0x00000002\\
		RIVER\_MODIFIER\_SSSEG & 0x00000003\\
		RIVER\_MODIFIER\_DSSEG & 0x00000004\\
		RIVER\_MODIFIER\_FSSEG & 0x00000005\\
		RIVER\_MODIFIER\_GSSEG & 0x00000006\\
							   \\
		RIVER\_MODIFIER\_EXT &	0x00000008\\
		RIVER\_MODIFIER\_O8 & 0x00000010\\
		RIVER\_MODIFIER\_O16 & 0x00000020\\
		RIVER\_MODIFIER\_A16 & 0x00000040\\
		RIVER\_MODIFIER\_LOCK & 0x00000080\\
		RIVER\_MODIFIER\_REP & 0x00000100\\
		RIVER\_MODIFIER\_REPZ & 0x00000200\\
		RIVER\_MODIFIER\_REPNZ & 0x00000400\\
	\end{tabular}

	\subsection{{\river} Family}
	\begin{tabular}{ p{6cm} p{1.3cm} }
		RIVER\_FAMILY\_NATIVE & 0x00000000\\
		RIVER\_FAMILY\_RIVER & 0x00000001\\
		RIVER\_FAMILY\_TRACK & 0x00000002\\
		RIVER\_FAMILY\_PRETRACK & 0x00000003\\
		RIVER\_FAMILY\_PREMETA & 0x00000004\\
		RIVER\_FAMILY\_POSTMETA & 0x00000005\\
		RIVER\_FAMILY\_RIVER\_TRACK & 0x00000006\\

		RIVER\_FAMILY\_FLAG\_METAPROCESSED & 0x00000020\\
		RIVER\_FAMILY\_FLAG\_ORIG\_xSP & 0x00000040\\
		RIVER\_FAMILY\_FLAG\_IGNORE & 0x00000080\\
	\end{tabular}

	\subsection{{\river} Branch Instruction}
	\begin{tabular}{ p{6cm} p{1.3cm} }
		RIVER\_BRANCH\_INSTR\_RET & 0x00001000\\
		RIVER\_BRANCH\_INSTR\_JMP & 0x00002000\\
		RIVER\_BRANCH\_INSTR\_JXX & 0x00004000\\
		RIVER\_BRANCH\_INSTR\_CALL & 0x00008000\\
		RIVER\_BRANCH\_INSTR\_SYSCALL & 0x00010000\\
	\end{tabular}

	\subsection{{\river} Branch Type}
	\begin{tabular}{p{6cm} p{1.3cm} }
		RIVER\_BRANCH\_TYPE\_IMM & 0x00020000\\
		RIVER\_BRANCH\_TYPE\_REG & 0x00040000\\
		RIVER\_BRANCH\_TYPE\_MEM & 0x00080000\\
	\end{tabular}

	\subsection{{\river} Virtual Registers}
	\begin{tabular}{p{6cm} p{1.3cm}}
		RIVER\_REG\_xAX & 0x00\\
		RIVER\_REG\_xCX & 0x01\\
		RIVER\_REG\_xDX & 0x02\\
		RIVER\_REG\_xBX & 0x03\\
		RIVER\_REG\_xSP & 0x04\\
		RIVER\_REG\_xBP & 0x05\\
		RIVER\_REG\_xSI & 0x06\\
		RIVER\_REG\_xDI & 0x07\\
	\end{tabular}

	\subsection{{\river} Virtual Registers Size}
	\begin{tabular}{p{6cm} p{1.3cm}}
		RIVER\_REG\_SZ32 & 0x00\\
		RIVER\_REG\_SZ16 & 0x08\\
		RIVER\_REG\_SZ8\_L & 0x10\\
		RIVER\_REG\_SZ8\_H & 0x18\\
	\end{tabular}

	\subsection{{\river} Segment Registers}
	\begin{tabular}{p{6cm} p{1.3cm}}
		RIVER\_REG\_ES & 0x20\\
		RIVER\_REG\_SEGMENT & 0x20\\
		RIVER\_REG\_CS & 0x21\\
		RIVER\_REG\_SS & 0x22\\
		RIVER\_REG\_DS & 0x23\\
		RIVER\_REG\_FS & 0x24\\
		RIVER\_REG\_GS & 0x25\\
	\end{tabular}

	\subsection{{\river} Control Registers}
	\begin{tabular}{p{6cm} p{1.3cm}}
		RIVER\_REG\_CONTROL & 0x30\\
		RIVER\_REG\_CR0 & 0x30\\
		RIVER\_REG\_CR2 & 0x32\\
		RIVER\_REG\_CR3 & 0x33\\
		RIVER\_REG\_CR4 & 0x34\\
	\end{tabular}

	\subsection{{\river} Debug Registers}
	\begin{tabular}{p{6cm} p{1.3cm}}
		RIVER\_REG\_DEBUG & 0x40\\
		RIVER\_REG\_DR0 & 0x40\\
		RIVER\_REG\_DR1 & 0x41\\
		RIVER\_REG\_DR2 & 0x42\\
		RIVER\_REG\_DR3 & 0x43\\
		RIVER\_REG\_DR4 & 0x44\\
		RIVER\_REG\_DR5 & 0x45\\
		RIVER\_REG\_DR6 & 0x46\\
		RIVER\_REG\_DR7 & 0x47\\
	\end{tabular}

	\subsection{{\river} Other Registers}
	\begin{tabular}{p{6cm} p{1.3cm}}
		RIVER\_REG\_NONE & 0x20\\
	\end{tabular}

	\subsection{RiverAddress components}
	\begin{tabular}{p{6cm} p{1.3cm}}
		RIVER\_ADDR\_DISP8 & 0x01\\
		RIVER\_ADDR\_DISP & 0x02\\
		RIVER\_ADDR\_SCALE & 0x04\\
		RIVER\_ADDR\_BASE & 0x08\\
		RIVER\_ADDR\_INDEX & 0x10\\
		RIVER\_ADDR\_DIRTY & 0x80\\
	\end{tabular}

	\subsection{{\river} Operand Types}
	\begin{tabular}{p{6cm} p{1.3cm}}
		RIVER\_OPTYPE\_NONE & 0x00\\
		RIVER\_OPTYPE\_IMM & 0x04\\
		RIVER\_OPTYPE\_REG & 0x08\\
		RIVER\_OPTYPE\_MEM & 0x0C\\
		RIVER\_OPTYPE\_ALL & 0x10\\
	\end{tabular}

	\subsection{{\river} Operand Size}
	\begin{tabular}{p{6cm} p{1.3cm}}
		RIVER\_OPSIZE\_32 & 0x00\\
		RIVER\_OPSIZE\_16 & 0x01\\
		RIVER\_OPSIZE\_8 & 0x02\\
	\end{tabular}

	\subsection{{\river} Operation Specifiers}
	\begin{tabular}{p{6cm} p{1.3cm}}
		RIVER\_SPEC\_MODIFIES\_OP1 & 0x0001\\
		RIVER\_SPEC\_MODIFIES\_OP2 & 0x0002\\
		RIVER\_SPEC\_MODIFIES\_OP3 & 0x0004\\
		RIVER\_SPEC\_MODIFIES\_OP4 & 0x0008\\
		\\
		RIVER\_SPEC\_MODIFIES\_FLG & 0x0010\\
		\\
		RIVER\_SPEC\_MODIFIES\_xSP & 0x0020\\
		\\
		RIVER\_SPEC\_MODIFIES\_CUSTOM & 0x0040\\
		\\
		RIVER\_SPEC\_IGNORES\_MEMORY & 0x0080\\
		\\
		RIVER\_SPEC\_IGNORES\_OP1 & 0x0100\\
		RIVER\_SPEC\_IGNORES\_OP2 & 0x0200\\
		RIVER\_SPEC\_IGNORES\_OP3 & 0x0400\\
		RIVER\_SPEC\_IGNORES\_OP4 & 0x0800\\
		\\
		RIVER\_SPEC\_IGNORES\_FLG & 0x1000\\
	\end{tabular}

	\subsection{{\river} Operation Flags}
	\begin{tabular}{p{6cm} p{1.3cm}}
		RIVER\_SPEC\_IDX\_CF & 0x00\\
		RIVER\_SPEC\_IDX\_PF & 0x01\\
		RIVER\_SPEC\_IDX\_AF & 0x02\\
		RIVER\_SPEC\_IDX\_ZF & 0x03\\
		RIVER\_SPEC\_IDX\_SF & 0x04\\
		RIVER\_SPEC\_IDX\_OF & 0x05\\
		RIVER\_SPEC\_IDX\_DF & 0x06\\
	\end{tabular}

	\newpage
	\section{Structure Definitions}
	\subsection{struct RiverAddress}
	\lstinputlisting[language=C]{code/RiverAddress.h}

	\subsection{struct RiverOperand}
	\lstinputlisting[language=C]{code/RiverOperand.h}

	\columnbreak
	\subsection{struct RiverInstruction}
	\lstinputlisting[language=C]{code/RiverInstruction.h}

\end{multicols*}

\end{document}


text:
\documentclass{article}
\author{Sahar Memon, Andrew Zimolzak, Li Wei\\(VA Houston / Baylor
  College of Medicine)}
\title{InSTRuCt Study E-Trigger Manual}
\date{March, 2020}
\usepackage{listings}
%\usepackage{indentfirst}
\begin{document}
\maketitle

\section{Overview}

This manual outlines procedures for VA facilities participating in the
InSTRuCt project and enables their data-analysts/informatics personnel
to run electronic triggers (e-triggers) on the data warehouse. The SQL
code for the InSTRuCt study comprises e-triggers to identify missed
opportunities in follow-up of `red flag' findings suspicious for
several cancers, including bladder, breast, colorectal (FOBT and IDA),
hepatocellular, and lung. In general, each SQL file proceeds by--

\begin{enumerate}
\item defining the red flags that warrant additional evaluation for
  cancer (often labs or imaging),

\item excluding other explanations for the red flags, such as already
  diagnosed colon cancer, or known cause of bleeding in the upper GI
  tract (often based on ICD/CPT codes),

\item excluding patients for whom follow-up is not deemed necessary,
  and

\item excluding patients for whom appropriate follow-up was already
  done (usually based on stop codes and procedure codes).
\end{enumerate}

As an example, the e-trigger for colorectal cancer identifies patients
with positive fecal blood tests, and then excludes patients with any
of the following: advanced age, deceased status, known colon cancer,
prior colectomy, terminal illnesses or hospice care, presence of a
known diagnosis that would cause bleeding in the upper GI tract rather
than lower GI tract, and appropriate colonoscopy or GI referral.

\section{How to Apply e-Trigger Process at Your Facility}

\begin{enumerate}

\item Start your operational access to the data warehouse via your
  usual method (e.g.\ desktop or Citrix connection to SQL Server
  Management Studio software). Login to a SQL server
  (e.g.\ \texttt{vhacdwa01.vha.med.va.gov}) and authenticate (using
  either username such as \texttt{vha01\textbackslash{}vhabhs\ldots{}}\ plus
  password, or using Windows authentication).

\item The most recent version of the code can be downloaded from
  github.com/zimolzak/instruct-project-etrigger-sql where you can also
  find additional procedures for setting dates, and guidance about
  which tables to export for final reporting.

\item Most changes to adapt the code to the operational database and
  schema names have been performed automatically (marked by comments
  reading ``\texttt{--altered}''). However, you will need to make
  further one-time edits to make the code function in your site's
  local database environment. The SQL code as provided uses
  placeholder names of \texttt{MyDB} and \texttt{MySchema} schema for
  outputs. Replace these with any database/schema combination where
  you have write permissions. \emph{You may have to request write
    permissions} if you have never been granted access to write out an
  intermediate table.

\item For the final project, you will be limiting queries to
  approximately one month of data at a time, and you will be running
  only 1--3 triggers depending on your facility's choice. Lines of
  code contain variable assignment statements that allow you to
  customize the query date ranges to your local station, such as:

\begin{verbatim}
set @VISN=12
--set @Sta3n=580 -- -1 all sta3n
set @run_date=getdate()
set @sp_start='2020-01-01 00:00:00'
set @sp_end='2020-01-31 23:59:59'
\end{verbatim}

\item Recommended: Run sections of the SQL file sequentially (for
  example, lines 1--132 of \texttt{Fobt.sql} cover the first two
  \texttt{INSERT INTO} operations concerning tables that were newly
  created), inspecting for errors. Alternatively: run query all at
  once, inspecting for errors. Inspection for errors should include
  not only SQL errors, but data validation through a few record
  reviews performed by the site champion. (Randomly select a few
  patients with positive e-trigger, and securely transmit last name
  and last 4 of SSN from these patients to the site champion, who will
  validate via CPRS that the sample patients have a positive red flag
  inside the time period of interest.)

\item ONLY when your site enters the ``action'' phase: translate
  output tables into reports as requested by participants in the
  InSTRuCt virtual breakthrough series (e.g.\ leadership, laboratory
  managers). The most valuable tables are
  \texttt{Lung\_Sta3n528\_3\_Ins\_U\_TriggerPos} (contains PHI, for your site's
  internal use only) and \texttt{Lung\_Sta3n528\_4\_01\_Count} (aggregate data
  only, suitable to copy/paste into Excel sheet for display on the
  monthly phone calls).

\end{enumerate}

\section{Estimated Analyst Time Commitment}

\subsection{Initial set up (one-time tasks)}

\textbf{Global modifications to adapt e-triggers to the operational
  Data Warehouse: complete}

The e-triggers were developed on the Corporate Data Warehouse using a
research database and schema. Even though research data and
operational data are both hosted on the CDW, their data schemas are
not identical. In cooperation with cluster 1, we have made changes to
the SQL code, and it now runs on the operational schema.

\noindent\textbf{All sites: Local modifications to the SQL code: 40
  person-hours}

With runnable triggers, each site might need to make changes to the
SQL code which are specific to their facility. The typical changes
would be on the data server name, database name, and the
interpretations of the test/image values. For example, for an abnormal
result, some sites mark it as `A', some sites mark it as `+', some
sites use descriptions as `many', `TNTC', or ranges such as
`\textgreater{}100', `50-2000', etc. As another example, some sites
may use a `+' to mark a normal and `++' to mark an abnormal. We
recommend that the site analyst work with local clinical groups to
best customize the test/image interpretations. We predict that the
analyst and a clinician will need to get together to review, parse,
and categorize some lab/test results. Another place that might need
attention is the lab test and procedure codes (CPT, ICDProc, LOINC
etc\ldots{}). They are standard codes, but if your site uses them in
different flavors you might need do some customization. Our estimated
time dedicated to this task will be 40 person-hours of analyst time.
The study team (VA Houston) will also provide guidance to the
pioneer site in this process.

\subsection{On-going tasks for the duration of the site's participation}

\noindent\textbf{Run SQL code to retrieve data: 17 minutes per trigger
  per month}

The time between pressing the `Run' button to retrieve data output (if
run monthly on a single site) is a few minutes if no errors are
encountered. This also depends on the size of the site, network
speed/traffic, data servers' performance, and their concurrent load.
Here is the breakdown based on 6 months: 17 minutes x 6 time points x
2 triggers = 3.4 computer hours.

\noindent\textbf{Ongoing modifications to SQL code: 40-person hours
  per year}

The CDW releases patch updates periodically, and this might require
ongoing minor changes/updates to SQL code, by each site analyst.
Standard codes (CPT, ICD, ICDProc, LOINC, Stopcode, etc.) tend to
change every year, with addition of new codes and removal of old
codes. These changes require corresponding updates in the SQL code.
Important note here is that you only add new codes to the SQL, do NOT
remove the old ones (this is so the e-trigger continues to capture
usage of both the historical and new codes).

\subsection{Summary}

40 person-hours one-time effort.\\
40 person-hours per year ongoing effort.\\
3 hours computer time during 6 month intervention.

\section{Further reading}

\subsection{InSTRuCt project documents}

\emph{Reducing Missed Test Results Change Package}\\
\emph{InSTRuCt Study FAQ}, also known as \texttt{IIR FAQ 5.6.19.docx}\\
\emph{Standard Operating Procedure}, also known as \texttt{SOP for
  INSTRUCT\_4.5.19.pdf}\\
\emph{InSTRuCt Project Overview}, also known as \texttt{IIR Project
  Charter\_7.12.19.pdf}

\subsection{List of auxiliary files documenting the SQL code, November 2018}

\begin{verbatim}
Bladder Cancer Trigger Criteria.docx
Bladder cancer trigger- ICD 9 to ICD 10 codes.docx
Breast Cancer Trigger Criteria.docx
Breast cancer- ICD 9 to ICD 10 codes.docx
Colorectal Cancer Trigger Criteria.docx
Colorectal Cancer- ICD 9 to ICD 10 codes.docx
Hepatocellular Carcinoma Trigger Criteria.doc
Hepatocellular Carcinoma- ICD 9 to ICD 10 codes.docx
Lung Cancer Trigger Criteria.doc
Lung cancer Trigger- ICD 9 to ICD 10 codes.docx
bladder cancer ICD andCPT codes.docx
\end{verbatim}

\end{document}

max_stars_repo_name: zimolzak/instruct-project-etrigger-sql

max_issues_repo_name: zimolzak/instruct-project-etrigger-sql

max_forks_repo_name: zimolzak/instruct-project-etrigger-sql